three.webgpu.nodes.js 1.9 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740
  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, SphereGeometry, NormalBlending, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, PlaneGeometry, FrontSide, CustomBlending, AddEquation, ZeroFactor, CylinderGeometry, Quaternion, WebXRController, RAD2DEG, PCFShadowMap, FrustumArray, Frustum, RedIntegerFormat, RedFormat, ShortType, ByteType, UnsignedShortType, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, TimestampQuery, createCanvasElement, ReverseSubtractEquation, SubtractEquation, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcAlphaFactor, SrcColorFactor, OneFactor, CullFaceNone, CullFaceBack, CullFaceFront, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, UnsignedInt101111Type, AlphaFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, R11_EAC_Format, SIGNED_R11_EAC_Format, SIGNED_RG11_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, SIGNED_RED_GREEN_RGTC2_Format, MirroredRepeatWrapping, RepeatWrapping, NearestMipmapNearestFilter, NotEqualCompare, GreaterCompare, GreaterEqualCompare, EqualCompare, LessEqualCompare, AlwaysCompare, NeverCompare, LinearTransfer, getByteLength, isTypedArray, NotEqualStencilFunc, GreaterStencilFunc, GreaterEqualStencilFunc, EqualStencilFunc, LessEqualStencilFunc, LessStencilFunc, AlwaysStencilFunc, NeverStencilFunc, DecrementWrapStencilOp, IncrementWrapStencilOp, DecrementStencilOp, IncrementStencilOp, InvertStencilOp, ReplaceStencilOp, ZeroStencilOp, KeepStencilOp, MaxEquation, MinEquation, SpotLight, PointLight, DirectionalLight, RectAreaLight, AmbientLight, HemisphereLight, LightProbe, LinearToneMapping, ReinhardToneMapping, CineonToneMapping, ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, Group, Loader, FileLoader, MaterialLoader, ObjectLoader } from './three.core.js';
  7. export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, ExternalTexture, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, PCFSoftShadowMap, Path, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, Timer, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding, getConsoleFunction, setConsoleFunction } from './three.core.js';
  8. const refreshUniforms = [
  9. 'alphaMap',
  10. 'alphaTest',
  11. 'anisotropy',
  12. 'anisotropyMap',
  13. 'anisotropyRotation',
  14. 'aoMap',
  15. 'aoMapIntensity',
  16. 'attenuationColor',
  17. 'attenuationDistance',
  18. 'bumpMap',
  19. 'clearcoat',
  20. 'clearcoatMap',
  21. 'clearcoatNormalMap',
  22. 'clearcoatNormalScale',
  23. 'clearcoatRoughness',
  24. 'color',
  25. 'dispersion',
  26. 'displacementMap',
  27. 'emissive',
  28. 'emissiveIntensity',
  29. 'emissiveMap',
  30. 'envMap',
  31. 'envMapIntensity',
  32. 'gradientMap',
  33. 'ior',
  34. 'iridescence',
  35. 'iridescenceIOR',
  36. 'iridescenceMap',
  37. 'iridescenceThicknessMap',
  38. 'lightMap',
  39. 'lightMapIntensity',
  40. 'map',
  41. 'matcap',
  42. 'metalness',
  43. 'metalnessMap',
  44. 'normalMap',
  45. 'normalScale',
  46. 'opacity',
  47. 'roughness',
  48. 'roughnessMap',
  49. 'sheen',
  50. 'sheenColor',
  51. 'sheenColorMap',
  52. 'sheenRoughnessMap',
  53. 'shininess',
  54. 'specular',
  55. 'specularColor',
  56. 'specularColorMap',
  57. 'specularIntensity',
  58. 'specularIntensityMap',
  59. 'specularMap',
  60. 'thickness',
  61. 'transmission',
  62. 'transmissionMap'
  63. ];
  64. /**
  65. * A WeakMap to cache lights data for node materials.
  66. * Cache lights data by render ID to avoid unnecessary recalculations.
  67. *
  68. * @private
  69. * @type {WeakMap<LightsNode,Object>}
  70. */
  71. const _lightsCache = new WeakMap();
  72. /**
  73. * This class is used by {@link WebGPURenderer} as management component.
  74. * It's primary purpose is to determine whether render objects require a
  75. * refresh right before they are going to be rendered or not.
  76. */
  77. class NodeMaterialObserver {
  78. /**
  79. * Constructs a new node material observer.
  80. *
  81. * @param {NodeBuilder} builder - The node builder.
  82. */
  83. constructor( builder ) {
  84. /**
  85. * A node material can be used by more than one render object so the
  86. * monitor must maintain a list of render objects.
  87. *
  88. * @type {WeakMap<RenderObject,Object>}
  89. */
  90. this.renderObjects = new WeakMap();
  91. /**
  92. * Whether the material uses node objects or not.
  93. *
  94. * @type {boolean}
  95. */
  96. this.hasNode = this.containsNode( builder );
  97. /**
  98. * Whether the node builder's 3D object is animated or not.
  99. *
  100. * @type {boolean}
  101. */
  102. this.hasAnimation = builder.object.isSkinnedMesh === true;
  103. /**
  104. * A list of all possible material uniforms
  105. *
  106. * @type {Array<string>}
  107. */
  108. this.refreshUniforms = refreshUniforms;
  109. /**
  110. * Holds the current render ID from the node frame.
  111. *
  112. * @type {number}
  113. * @default 0
  114. */
  115. this.renderId = 0;
  116. }
  117. /**
  118. * Returns `true` if the given render object is verified for the first time of this observer.
  119. *
  120. * @param {RenderObject} renderObject - The render object.
  121. * @return {boolean} Whether the given render object is verified for the first time of this observer.
  122. */
  123. firstInitialization( renderObject ) {
  124. const hasInitialized = this.renderObjects.has( renderObject );
  125. if ( hasInitialized === false ) {
  126. this.getRenderObjectData( renderObject );
  127. return true;
  128. }
  129. return false;
  130. }
  131. /**
  132. * Returns `true` if the current rendering produces motion vectors.
  133. *
  134. * @param {Renderer} renderer - The renderer.
  135. * @return {boolean} Whether the current rendering produces motion vectors or not.
  136. */
  137. needsVelocity( renderer ) {
  138. const mrt = renderer.getMRT();
  139. return ( mrt !== null && mrt.has( 'velocity' ) );
  140. }
  141. /**
  142. * Returns monitoring data for the given render object.
  143. *
  144. * @param {RenderObject} renderObject - The render object.
  145. * @return {Object} The monitoring data.
  146. */
  147. getRenderObjectData( renderObject ) {
  148. let data = this.renderObjects.get( renderObject );
  149. if ( data === undefined ) {
  150. const { geometry, material, object } = renderObject;
  151. data = {
  152. material: this.getMaterialData( material ),
  153. geometry: {
  154. id: geometry.id,
  155. attributes: this.getAttributesData( geometry.attributes ),
  156. indexVersion: geometry.index ? geometry.index.version : null,
  157. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  158. },
  159. worldMatrix: object.matrixWorld.clone()
  160. };
  161. if ( object.center ) {
  162. data.center = object.center.clone();
  163. }
  164. if ( object.morphTargetInfluences ) {
  165. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  166. }
  167. if ( renderObject.bundle !== null ) {
  168. data.version = renderObject.bundle.version;
  169. }
  170. if ( data.material.transmission > 0 ) {
  171. const { width, height } = renderObject.context;
  172. data.bufferWidth = width;
  173. data.bufferHeight = height;
  174. }
  175. data.lights = this.getLightsData( renderObject.lightsNode.getLights() );
  176. this.renderObjects.set( renderObject, data );
  177. }
  178. return data;
  179. }
  180. /**
  181. * Returns an attribute data structure holding the attributes versions for
  182. * monitoring.
  183. *
  184. * @param {Object} attributes - The geometry attributes.
  185. * @return {Object} An object for monitoring the versions of attributes.
  186. */
  187. getAttributesData( attributes ) {
  188. const attributesData = {};
  189. for ( const name in attributes ) {
  190. const attribute = attributes[ name ];
  191. attributesData[ name ] = {
  192. version: attribute.version
  193. };
  194. }
  195. return attributesData;
  196. }
  197. /**
  198. * Returns `true` if the node builder's material uses
  199. * node properties.
  200. *
  201. * @param {NodeBuilder} builder - The current node builder.
  202. * @return {boolean} Whether the node builder's material uses node properties or not.
  203. */
  204. containsNode( builder ) {
  205. const material = builder.material;
  206. for ( const property in material ) {
  207. if ( material[ property ] && material[ property ].isNode )
  208. return true;
  209. }
  210. if ( builder.context.modelViewMatrix || builder.context.modelNormalViewMatrix || builder.context.ao )
  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 byte boundary for the given data type.
  551. *
  552. * @private
  553. * @method
  554. * @param {string} type - The data type.
  555. * @return {number} The byte boundary.
  556. */
  557. function getByteBoundaryFromType( 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 48;
  564. if ( /mat4/.test( type ) ) return 64;
  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. getByteBoundaryFromType: getByteBoundaryFromType,
  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 label context value for a given node.
  5606. *
  5607. * @tsl
  5608. * @function
  5609. * @deprecated
  5610. * @param {Node} node - The node whose context should be modified.
  5611. * @param {string} name - The name/label to set.
  5612. * @returns {ContextNode}
  5613. */
  5614. function label( node, name ) {
  5615. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  5616. return setName( node, name );
  5617. }
  5618. addMethodChaining( 'context', context );
  5619. addMethodChaining( 'label', label );
  5620. addMethodChaining( 'uniformFlow', uniformFlow );
  5621. addMethodChaining( 'setName', setName );
  5622. /**
  5623. * Class for representing shader variables as nodes. Variables are created from
  5624. * existing nodes like the following:
  5625. *
  5626. * ```js
  5627. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5628. * ```
  5629. *
  5630. * @augments Node
  5631. */
  5632. class VarNode extends Node {
  5633. static get type() {
  5634. return 'VarNode';
  5635. }
  5636. /**
  5637. * Constructs a new variable node.
  5638. *
  5639. * @param {Node} node - The node for which a variable should be created.
  5640. * @param {?string} [name=null] - The name of the variable in the shader.
  5641. * @param {boolean} [readOnly=false] - The read-only flag.
  5642. */
  5643. constructor( node, name = null, readOnly = false ) {
  5644. super();
  5645. /**
  5646. * The node for which a variable should be created.
  5647. *
  5648. * @type {Node}
  5649. */
  5650. this.node = node;
  5651. /**
  5652. * The name of the variable in the shader. If no name is defined,
  5653. * the node system auto-generates one.
  5654. *
  5655. * @type {?string}
  5656. * @default null
  5657. */
  5658. this.name = name;
  5659. /**
  5660. * `VarNode` sets this property to `true` by default.
  5661. *
  5662. * @type {boolean}
  5663. * @default true
  5664. */
  5665. this.global = true;
  5666. /**
  5667. * This flag can be used for type testing.
  5668. *
  5669. * @type {boolean}
  5670. * @readonly
  5671. * @default true
  5672. */
  5673. this.isVarNode = true;
  5674. /**
  5675. *
  5676. * The read-only flag.
  5677. *
  5678. * @type {boolean}
  5679. * @default false
  5680. */
  5681. this.readOnly = readOnly;
  5682. /**
  5683. *
  5684. * Add this flag to the node system to indicate that this node require parents.
  5685. *
  5686. * @type {boolean}
  5687. * @default true
  5688. */
  5689. this.parents = true;
  5690. /**
  5691. * This flag is used to indicate that this node is used for intent.
  5692. *
  5693. * @type {boolean}
  5694. * @default false
  5695. */
  5696. this.intent = false;
  5697. }
  5698. /**
  5699. * Sets the intent flag for this node.
  5700. *
  5701. * This flag is used to indicate that this node is used for intent
  5702. * and should not be built directly. Instead, it is used to indicate that
  5703. * the node should be treated as a variable intent.
  5704. *
  5705. * It's useful for assigning variables without needing creating a new variable node.
  5706. *
  5707. * @param {boolean} value - The value to set for the intent flag.
  5708. * @returns {VarNode} This node.
  5709. */
  5710. setIntent( value ) {
  5711. this.intent = value;
  5712. return this;
  5713. }
  5714. /**
  5715. * Returns the intent flag of this node.
  5716. *
  5717. * @return {boolean} The intent flag.
  5718. */
  5719. getIntent() {
  5720. return this.intent;
  5721. }
  5722. getMemberType( builder, name ) {
  5723. return this.node.getMemberType( builder, name );
  5724. }
  5725. getElementType( builder ) {
  5726. return this.node.getElementType( builder );
  5727. }
  5728. getNodeType( builder ) {
  5729. return this.node.getNodeType( builder );
  5730. }
  5731. getArrayCount( builder ) {
  5732. return this.node.getArrayCount( builder );
  5733. }
  5734. isAssign( builder ) {
  5735. const properties = builder.getNodeProperties( this );
  5736. let assign = properties.assign;
  5737. if ( assign !== true ) {
  5738. if ( this.node.isShaderCallNodeInternal && this.node.shaderNode.getLayout() === null ) {
  5739. if ( builder.fnCall && builder.fnCall.shaderNode ) {
  5740. const shaderNodeData = builder.getDataFromNode( this.node.shaderNode );
  5741. if ( shaderNodeData.hasLoop ) {
  5742. assign = true;
  5743. }
  5744. }
  5745. }
  5746. }
  5747. return assign;
  5748. }
  5749. build( ...params ) {
  5750. const builder = params[ 0 ];
  5751. if ( this._hasStack( builder ) === false && builder.buildStage === 'setup' ) {
  5752. if ( builder.context.nodeLoop || builder.context.nodeBlock ) {
  5753. builder.getBaseStack().addToStack( this );
  5754. }
  5755. }
  5756. if ( this.intent === true ) {
  5757. if ( this.isAssign( builder ) !== true ) {
  5758. return this.node.build( ...params );
  5759. }
  5760. }
  5761. return super.build( ...params );
  5762. }
  5763. generate( builder ) {
  5764. const { node, name, readOnly } = this;
  5765. const { renderer } = builder;
  5766. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5767. let isDeterministic = false;
  5768. let shouldTreatAsReadOnly = false;
  5769. if ( readOnly ) {
  5770. isDeterministic = builder.isDeterministic( node );
  5771. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5772. }
  5773. const nodeType = this.getNodeType( builder );
  5774. if ( nodeType == 'void' ) {
  5775. if ( this.intent !== true ) {
  5776. error( 'TSL: ".toVar()" can not be used with void type.' );
  5777. }
  5778. const snippet = node.build( builder );
  5779. return snippet;
  5780. }
  5781. const vectorType = builder.getVectorType( nodeType );
  5782. const snippet = node.build( builder, vectorType );
  5783. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5784. const propertyName = builder.getPropertyName( nodeVar );
  5785. let declarationPrefix = propertyName;
  5786. if ( shouldTreatAsReadOnly ) {
  5787. if ( isWebGPUBackend ) {
  5788. declarationPrefix = isDeterministic
  5789. ? `const ${ propertyName }`
  5790. : `let ${ propertyName }`;
  5791. } else {
  5792. const count = node.getArrayCount( builder );
  5793. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5794. }
  5795. }
  5796. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5797. return propertyName;
  5798. }
  5799. _hasStack( builder ) {
  5800. const nodeData = builder.getDataFromNode( this );
  5801. return nodeData.stack !== undefined;
  5802. }
  5803. }
  5804. /**
  5805. * TSL function for creating a var node.
  5806. *
  5807. * @tsl
  5808. * @function
  5809. * @param {Node} node - The node for which a variable should be created.
  5810. * @param {?string} name - The name of the variable in the shader.
  5811. * @returns {VarNode}
  5812. */
  5813. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5814. /**
  5815. * TSL function for creating a var node.
  5816. *
  5817. * @tsl
  5818. * @function
  5819. * @param {Node} node - The node for which a variable should be created.
  5820. * @param {?string} name - The name of the variable in the shader.
  5821. * @returns {VarNode}
  5822. */
  5823. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5824. /**
  5825. * TSL function for creating a const node.
  5826. *
  5827. * @tsl
  5828. * @function
  5829. * @param {Node} node - The node for which a constant should be created.
  5830. * @param {?string} name - The name of the constant in the shader.
  5831. * @returns {VarNode}
  5832. */
  5833. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5834. //
  5835. //
  5836. /**
  5837. * TSL function for creating a var intent node.
  5838. *
  5839. * @tsl
  5840. * @function
  5841. * @param {Node} node - The node for which a variable should be created.
  5842. * @param {?string} name - The name of the variable in the shader.
  5843. * @returns {VarNode}
  5844. */
  5845. const VarIntent = ( node ) => {
  5846. return createVar( node ).setIntent( true ).toStack();
  5847. };
  5848. // Method chaining
  5849. addMethodChaining( 'toVar', Var );
  5850. addMethodChaining( 'toConst', Const );
  5851. addMethodChaining( 'toVarIntent', VarIntent );
  5852. /**
  5853. * This node is used to build a sub-build in the node system.
  5854. *
  5855. * @augments Node
  5856. * @param {Node} node - The node to be built in the sub-build.
  5857. * @param {string} name - The name of the sub-build.
  5858. * @param {?string} [nodeType=null] - The type of the node, if known.
  5859. */
  5860. class SubBuildNode extends Node {
  5861. static get type() {
  5862. return 'SubBuild';
  5863. }
  5864. constructor( node, name, nodeType = null ) {
  5865. super( nodeType );
  5866. /**
  5867. * The node to be built in the sub-build.
  5868. *
  5869. * @type {Node}
  5870. */
  5871. this.node = node;
  5872. /**
  5873. * The name of the sub-build.
  5874. *
  5875. * @type {string}
  5876. */
  5877. this.name = name;
  5878. /**
  5879. * This flag can be used for type testing.
  5880. *
  5881. * @type {boolean}
  5882. * @readonly
  5883. * @default true
  5884. */
  5885. this.isSubBuildNode = true;
  5886. }
  5887. getNodeType( builder ) {
  5888. if ( this.nodeType !== null ) return this.nodeType;
  5889. builder.addSubBuild( this.name );
  5890. const nodeType = this.node.getNodeType( builder );
  5891. builder.removeSubBuild();
  5892. return nodeType;
  5893. }
  5894. build( builder, ...params ) {
  5895. builder.addSubBuild( this.name );
  5896. const data = this.node.build( builder, ...params );
  5897. builder.removeSubBuild();
  5898. return data;
  5899. }
  5900. }
  5901. /**
  5902. * Creates a new sub-build node.
  5903. *
  5904. * @tsl
  5905. * @function
  5906. * @param {Node} node - The node to be built in the sub-build.
  5907. * @param {string} name - The name of the sub-build.
  5908. * @param {?string} [type=null] - The type of the node, if known.
  5909. * @returns {Node} A node object wrapping the SubBuildNode instance.
  5910. */
  5911. const subBuild = ( node, name, type = null ) => nodeObject( new SubBuildNode( nodeObject( node ), name, type ) );
  5912. /**
  5913. * Class for representing shader varyings as nodes. Varyings are create from
  5914. * existing nodes like the following:
  5915. *
  5916. * ```js
  5917. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5918. * ```
  5919. *
  5920. * @augments Node
  5921. */
  5922. class VaryingNode extends Node {
  5923. static get type() {
  5924. return 'VaryingNode';
  5925. }
  5926. /**
  5927. * Constructs a new varying node.
  5928. *
  5929. * @param {Node} node - The node for which a varying should be created.
  5930. * @param {?string} name - The name of the varying in the shader.
  5931. */
  5932. constructor( node, name = null ) {
  5933. super();
  5934. /**
  5935. * The node for which a varying should be created.
  5936. *
  5937. * @type {Node}
  5938. */
  5939. this.node = node;
  5940. /**
  5941. * The name of the varying in the shader. If no name is defined,
  5942. * the node system auto-generates one.
  5943. *
  5944. * @type {?string}
  5945. * @default null
  5946. */
  5947. this.name = name;
  5948. /**
  5949. * This flag can be used for type testing.
  5950. *
  5951. * @type {boolean}
  5952. * @readonly
  5953. * @default true
  5954. */
  5955. this.isVaryingNode = true;
  5956. /**
  5957. * The interpolation type of the varying data.
  5958. *
  5959. * @type {?string}
  5960. * @default null
  5961. */
  5962. this.interpolationType = null;
  5963. /**
  5964. * The interpolation sampling type of varying data.
  5965. *
  5966. * @type {?string}
  5967. * @default null
  5968. */
  5969. this.interpolationSampling = null;
  5970. /**
  5971. * This flag is used for global cache.
  5972. *
  5973. * @type {boolean}
  5974. * @default true
  5975. */
  5976. this.global = true;
  5977. }
  5978. /**
  5979. * Defines the interpolation type of the varying.
  5980. *
  5981. * @param {string} type - The interpolation type.
  5982. * @param {?string} sampling - The interpolation sampling type
  5983. * @return {VaryingNode} A reference to this node.
  5984. */
  5985. setInterpolation( type, sampling = null ) {
  5986. this.interpolationType = type;
  5987. this.interpolationSampling = sampling;
  5988. return this;
  5989. }
  5990. getHash( builder ) {
  5991. return this.name || super.getHash( builder );
  5992. }
  5993. getNodeType( builder ) {
  5994. // VaryingNode is auto type
  5995. return this.node.getNodeType( builder );
  5996. }
  5997. /**
  5998. * This method performs the setup of a varying node with the current node builder.
  5999. *
  6000. * @param {NodeBuilder} builder - The current node builder.
  6001. * @return {NodeVarying} The node varying from the node builder.
  6002. */
  6003. setupVarying( builder ) {
  6004. const properties = builder.getNodeProperties( this );
  6005. let varying = properties.varying;
  6006. if ( varying === undefined ) {
  6007. const name = this.name;
  6008. const type = this.getNodeType( builder );
  6009. const interpolationType = this.interpolationType;
  6010. const interpolationSampling = this.interpolationSampling;
  6011. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  6012. properties.node = subBuild( this.node, 'VERTEX' );
  6013. }
  6014. // this property can be used to check if the varying can be optimized for a variable
  6015. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  6016. return varying;
  6017. }
  6018. setup( builder ) {
  6019. this.setupVarying( builder );
  6020. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6021. }
  6022. analyze( builder ) {
  6023. this.setupVarying( builder );
  6024. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6025. }
  6026. generate( builder ) {
  6027. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  6028. const properties = builder.getNodeProperties( this );
  6029. const varying = this.setupVarying( builder );
  6030. if ( properties[ propertyKey ] === undefined ) {
  6031. const type = this.getNodeType( builder );
  6032. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  6033. // force node run in vertex stage
  6034. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  6035. properties[ propertyKey ] = propertyName;
  6036. }
  6037. return builder.getPropertyName( varying );
  6038. }
  6039. }
  6040. /**
  6041. * TSL function for creating a varying node.
  6042. *
  6043. * @tsl
  6044. * @function
  6045. * @param {Node} node - The node for which a varying should be created.
  6046. * @param {?string} name - The name of the varying in the shader.
  6047. * @returns {VaryingNode}
  6048. */
  6049. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  6050. /**
  6051. * Computes a node in the vertex stage.
  6052. *
  6053. * @tsl
  6054. * @function
  6055. * @param {Node} node - The node which should be executed in the vertex stage.
  6056. * @returns {VaryingNode}
  6057. */
  6058. const vertexStage = ( node ) => varying( node );
  6059. addMethodChaining( 'toVarying', varying );
  6060. addMethodChaining( 'toVertexStage', vertexStage );
  6061. // Deprecated
  6062. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  6063. warn( 'TSL: .varying() has been renamed to .toVarying().' );
  6064. return varying( ...params );
  6065. } );
  6066. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  6067. warn( 'TSL: .vertexStage() has been renamed to .toVertexStage().' );
  6068. return varying( ...params );
  6069. } );
  6070. /**
  6071. * Converts the given color value from sRGB to linear-sRGB color space.
  6072. *
  6073. * @tsl
  6074. * @function
  6075. * @param {Node<vec3>} color - The sRGB color.
  6076. * @return {Node<vec3>} The linear-sRGB color.
  6077. */
  6078. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6079. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  6080. const b = color.mul( 0.0773993808 );
  6081. const factor = color.lessThanEqual( 0.04045 );
  6082. const rgbResult = mix( a, b, factor );
  6083. return rgbResult;
  6084. } ).setLayout( {
  6085. name: 'sRGBTransferEOTF',
  6086. type: 'vec3',
  6087. inputs: [
  6088. { name: 'color', type: 'vec3' }
  6089. ]
  6090. } );
  6091. /**
  6092. * Converts the given color value from linear-sRGB to sRGB color space.
  6093. *
  6094. * @tsl
  6095. * @function
  6096. * @param {Node<vec3>} color - The linear-sRGB color.
  6097. * @return {Node<vec3>} The sRGB color.
  6098. */
  6099. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6100. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  6101. const b = color.mul( 12.92 );
  6102. const factor = color.lessThanEqual( 0.0031308 );
  6103. const rgbResult = mix( a, b, factor );
  6104. return rgbResult;
  6105. } ).setLayout( {
  6106. name: 'sRGBTransferOETF',
  6107. type: 'vec3',
  6108. inputs: [
  6109. { name: 'color', type: 'vec3' }
  6110. ]
  6111. } );
  6112. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  6113. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  6114. /**
  6115. * This node represents a color space conversion. Meaning it converts
  6116. * a color value from a source to a target color space.
  6117. *
  6118. * @augments TempNode
  6119. */
  6120. class ColorSpaceNode extends TempNode {
  6121. static get type() {
  6122. return 'ColorSpaceNode';
  6123. }
  6124. /**
  6125. * Constructs a new color space node.
  6126. *
  6127. * @param {Node} colorNode - Represents the color to convert.
  6128. * @param {string} source - The source color space.
  6129. * @param {string} target - The target color space.
  6130. */
  6131. constructor( colorNode, source, target ) {
  6132. super( 'vec4' );
  6133. /**
  6134. * Represents the color to convert.
  6135. *
  6136. * @type {Node}
  6137. */
  6138. this.colorNode = colorNode;
  6139. /**
  6140. * The source color space.
  6141. *
  6142. * @type {string}
  6143. */
  6144. this.source = source;
  6145. /**
  6146. * The target color space.
  6147. *
  6148. * @type {string}
  6149. */
  6150. this.target = target;
  6151. }
  6152. /**
  6153. * This method resolves the constants `WORKING_COLOR_SPACE` and
  6154. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  6155. * color management and renderer.
  6156. *
  6157. * @param {NodeBuilder} builder - The current node builder.
  6158. * @param {string} colorSpace - The color space to resolve.
  6159. * @return {string} The resolved color space.
  6160. */
  6161. resolveColorSpace( builder, colorSpace ) {
  6162. if ( colorSpace === WORKING_COLOR_SPACE ) {
  6163. return ColorManagement.workingColorSpace;
  6164. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  6165. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  6166. }
  6167. return colorSpace;
  6168. }
  6169. setup( builder ) {
  6170. const { colorNode } = this;
  6171. const source = this.resolveColorSpace( builder, this.source );
  6172. const target = this.resolveColorSpace( builder, this.target );
  6173. let outputNode = colorNode;
  6174. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  6175. return outputNode;
  6176. }
  6177. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  6178. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  6179. }
  6180. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  6181. outputNode = vec4(
  6182. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  6183. outputNode.a
  6184. );
  6185. }
  6186. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  6187. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  6188. }
  6189. return outputNode;
  6190. }
  6191. }
  6192. /**
  6193. * TSL function for converting a given color node from the current working color space to the given color space.
  6194. *
  6195. * @tsl
  6196. * @function
  6197. * @param {Node} node - Represents the node to convert.
  6198. * @param {string} targetColorSpace - The target color space.
  6199. * @returns {ColorSpaceNode}
  6200. */
  6201. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  6202. /**
  6203. * TSL function for converting a given color node from the given color space to the current working color space.
  6204. *
  6205. * @tsl
  6206. * @function
  6207. * @param {Node} node - Represents the node to convert.
  6208. * @param {string} sourceColorSpace - The source color space.
  6209. * @returns {ColorSpaceNode}
  6210. */
  6211. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  6212. /**
  6213. * TSL function for converting a given color node from one color space to another one.
  6214. *
  6215. * @tsl
  6216. * @function
  6217. * @param {Node} node - Represents the node to convert.
  6218. * @param {string} sourceColorSpace - The source color space.
  6219. * @param {string} targetColorSpace - The target color space.
  6220. * @returns {ColorSpaceNode}
  6221. */
  6222. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  6223. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  6224. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  6225. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  6226. /**
  6227. * This class is only relevant if the referenced property is array-like.
  6228. * In this case, `ReferenceElementNode` allows to refer to a specific
  6229. * element inside the data structure via an index.
  6230. *
  6231. * @augments ArrayElementNode
  6232. */
  6233. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  6234. static get type() {
  6235. return 'ReferenceElementNode';
  6236. }
  6237. /**
  6238. * Constructs a new reference element node.
  6239. *
  6240. * @param {ReferenceBaseNode} referenceNode - The reference node.
  6241. * @param {Node} indexNode - The index node that defines the element access.
  6242. */
  6243. constructor( referenceNode, indexNode ) {
  6244. super( referenceNode, indexNode );
  6245. /**
  6246. * Similar to {@link ReferenceBaseNode#reference}, an additional
  6247. * property references to the current node.
  6248. *
  6249. * @type {?ReferenceBaseNode}
  6250. * @default null
  6251. */
  6252. this.referenceNode = referenceNode;
  6253. /**
  6254. * This flag can be used for type testing.
  6255. *
  6256. * @type {boolean}
  6257. * @readonly
  6258. * @default true
  6259. */
  6260. this.isReferenceElementNode = true;
  6261. }
  6262. /**
  6263. * This method is overwritten since the node type is inferred from
  6264. * the uniform type of the reference node.
  6265. *
  6266. * @return {string} The node type.
  6267. */
  6268. getNodeType() {
  6269. return this.referenceNode.uniformType;
  6270. }
  6271. generate( builder ) {
  6272. const snippet = super.generate( builder );
  6273. const arrayType = this.referenceNode.getNodeType();
  6274. const elementType = this.getNodeType();
  6275. return builder.format( snippet, arrayType, elementType );
  6276. }
  6277. };
  6278. /**
  6279. * Base class for nodes which establishes a reference to a property of another object.
  6280. * In this way, the value of the node is automatically linked to the value of
  6281. * referenced object. Reference nodes internally represent the linked value
  6282. * as a uniform.
  6283. *
  6284. * @augments Node
  6285. */
  6286. class ReferenceBaseNode extends Node {
  6287. static get type() {
  6288. return 'ReferenceBaseNode';
  6289. }
  6290. /**
  6291. * Constructs a new reference base node.
  6292. *
  6293. * @param {string} property - The name of the property the node refers to.
  6294. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6295. * @param {?Object} [object=null] - The object the property belongs to.
  6296. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6297. */
  6298. constructor( property, uniformType, object = null, count = null ) {
  6299. super();
  6300. /**
  6301. * The name of the property the node refers to.
  6302. *
  6303. * @type {string}
  6304. */
  6305. this.property = property;
  6306. /**
  6307. * The uniform type that should be used to represent the property value.
  6308. *
  6309. * @type {string}
  6310. */
  6311. this.uniformType = uniformType;
  6312. /**
  6313. * The object the property belongs to.
  6314. *
  6315. * @type {?Object}
  6316. * @default null
  6317. */
  6318. this.object = object;
  6319. /**
  6320. * When the linked property is an array, this parameter defines its length.
  6321. *
  6322. * @type {?number}
  6323. * @default null
  6324. */
  6325. this.count = count;
  6326. /**
  6327. * The property name might have dots so nested properties can be referred.
  6328. * The hierarchy of the names is stored inside this array.
  6329. *
  6330. * @type {Array<string>}
  6331. */
  6332. this.properties = property.split( '.' );
  6333. /**
  6334. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6335. * since the final reference might be updated from calling code.
  6336. *
  6337. * @type {?Object}
  6338. * @default null
  6339. */
  6340. this.reference = object;
  6341. /**
  6342. * The uniform node that holds the value of the reference node.
  6343. *
  6344. * @type {UniformNode}
  6345. * @default null
  6346. */
  6347. this.node = null;
  6348. /**
  6349. * The uniform group of the internal uniform.
  6350. *
  6351. * @type {UniformGroupNode}
  6352. * @default null
  6353. */
  6354. this.group = null;
  6355. /**
  6356. * Overwritten since reference nodes are updated per object.
  6357. *
  6358. * @type {string}
  6359. * @default 'object'
  6360. */
  6361. this.updateType = NodeUpdateType.OBJECT;
  6362. }
  6363. /**
  6364. * Sets the uniform group for this reference node.
  6365. *
  6366. * @param {UniformGroupNode} group - The uniform group to set.
  6367. * @return {ReferenceBaseNode} A reference to this node.
  6368. */
  6369. setGroup( group ) {
  6370. this.group = group;
  6371. return this;
  6372. }
  6373. /**
  6374. * When the referred property is array-like, this method can be used
  6375. * to access elements via an index node.
  6376. *
  6377. * @param {IndexNode} indexNode - indexNode.
  6378. * @return {ReferenceElementNode} A reference to an element.
  6379. */
  6380. element( indexNode ) {
  6381. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  6382. }
  6383. /**
  6384. * Sets the node type which automatically defines the internal
  6385. * uniform type.
  6386. *
  6387. * @param {string} uniformType - The type to set.
  6388. */
  6389. setNodeType( uniformType ) {
  6390. const node = uniform( null, uniformType );
  6391. if ( this.group !== null ) {
  6392. node.setGroup( this.group );
  6393. }
  6394. this.node = node;
  6395. }
  6396. /**
  6397. * This method is overwritten since the node type is inferred from
  6398. * the type of the reference node.
  6399. *
  6400. * @param {NodeBuilder} builder - The current node builder.
  6401. * @return {string} The node type.
  6402. */
  6403. getNodeType( builder ) {
  6404. if ( this.node === null ) {
  6405. this.updateReference( builder );
  6406. this.updateValue();
  6407. }
  6408. return this.node.getNodeType( builder );
  6409. }
  6410. /**
  6411. * Returns the property value from the given referred object.
  6412. *
  6413. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6414. * @return {any} The value.
  6415. */
  6416. getValueFromReference( object = this.reference ) {
  6417. const { properties } = this;
  6418. let value = object[ properties[ 0 ] ];
  6419. for ( let i = 1; i < properties.length; i ++ ) {
  6420. value = value[ properties[ i ] ];
  6421. }
  6422. return value;
  6423. }
  6424. /**
  6425. * Allows to update the reference based on the given state. The state is only
  6426. * evaluated {@link ReferenceBaseNode#object} is not set.
  6427. *
  6428. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6429. * @return {Object} The updated reference.
  6430. */
  6431. updateReference( state ) {
  6432. this.reference = this.object !== null ? this.object : state.object;
  6433. return this.reference;
  6434. }
  6435. /**
  6436. * The output of the reference node is the internal uniform node.
  6437. *
  6438. * @return {UniformNode} The output node.
  6439. */
  6440. setup() {
  6441. this.updateValue();
  6442. return this.node;
  6443. }
  6444. /**
  6445. * Overwritten to update the internal uniform value.
  6446. *
  6447. * @param {NodeFrame} frame - A reference to the current node frame.
  6448. */
  6449. update( /*frame*/ ) {
  6450. this.updateValue();
  6451. }
  6452. /**
  6453. * Retrieves the value from the referred object property and uses it
  6454. * to updated the internal uniform.
  6455. */
  6456. updateValue() {
  6457. if ( this.node === null ) this.setNodeType( this.uniformType );
  6458. const value = this.getValueFromReference();
  6459. if ( Array.isArray( value ) ) {
  6460. this.node.array = value;
  6461. } else {
  6462. this.node.value = value;
  6463. }
  6464. }
  6465. }
  6466. /**
  6467. * TSL function for creating a reference base node.
  6468. *
  6469. * @tsl
  6470. * @function
  6471. * @param {string} name - The name of the property the node refers to.
  6472. * @param {string} type - The uniform type that should be used to represent the property value.
  6473. * @param {Object} object - The object the property belongs to.
  6474. * @returns {ReferenceBaseNode}
  6475. */
  6476. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  6477. /**
  6478. * This node is a special type of reference node which is intended
  6479. * for linking renderer properties with node values.
  6480. * ```js
  6481. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6482. * ```
  6483. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6484. * automatically be updated.
  6485. *
  6486. * @augments ReferenceBaseNode
  6487. */
  6488. class RendererReferenceNode extends ReferenceBaseNode {
  6489. static get type() {
  6490. return 'RendererReferenceNode';
  6491. }
  6492. /**
  6493. * Constructs a new renderer reference node.
  6494. *
  6495. * @param {string} property - The name of the property the node refers to.
  6496. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6497. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6498. * the node refers to the renderer of the current state.
  6499. */
  6500. constructor( property, inputType, renderer = null ) {
  6501. super( property, inputType, renderer );
  6502. /**
  6503. * The renderer the property belongs to. When no renderer is set,
  6504. * the node refers to the renderer of the current state.
  6505. *
  6506. * @type {?Renderer}
  6507. * @default null
  6508. */
  6509. this.renderer = renderer;
  6510. this.setGroup( renderGroup );
  6511. }
  6512. /**
  6513. * Updates the reference based on the given state. The state is only evaluated
  6514. * {@link RendererReferenceNode#renderer} is not set.
  6515. *
  6516. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6517. * @return {Object} The updated reference.
  6518. */
  6519. updateReference( state ) {
  6520. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6521. return this.reference;
  6522. }
  6523. }
  6524. /**
  6525. * TSL function for creating a renderer reference node.
  6526. *
  6527. * @tsl
  6528. * @function
  6529. * @param {string} name - The name of the property the node refers to.
  6530. * @param {string} type - The uniform type that should be used to represent the property value.
  6531. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6532. * the node refers to the renderer of the current state.
  6533. * @returns {RendererReferenceNode}
  6534. */
  6535. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  6536. /**
  6537. * This node represents a tone mapping operation.
  6538. *
  6539. * @augments TempNode
  6540. */
  6541. class ToneMappingNode extends TempNode {
  6542. static get type() {
  6543. return 'ToneMappingNode';
  6544. }
  6545. /**
  6546. * Constructs a new tone mapping node.
  6547. *
  6548. * @param {number} toneMapping - The tone mapping type.
  6549. * @param {Node} exposureNode - The tone mapping exposure.
  6550. * @param {Node} [colorNode=null] - The color node to process.
  6551. */
  6552. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6553. super( 'vec3' );
  6554. /**
  6555. * The tone mapping type.
  6556. *
  6557. * @private
  6558. * @type {number}
  6559. */
  6560. this._toneMapping = toneMapping;
  6561. /**
  6562. * The tone mapping exposure.
  6563. *
  6564. * @type {Node}
  6565. * @default null
  6566. */
  6567. this.exposureNode = exposureNode;
  6568. /**
  6569. * Represents the color to process.
  6570. *
  6571. * @type {?Node}
  6572. * @default null
  6573. */
  6574. this.colorNode = colorNode;
  6575. }
  6576. /**
  6577. * Overwrites the default `customCacheKey()` implementation by including the tone
  6578. * mapping type into the cache key.
  6579. *
  6580. * @return {number} The hash.
  6581. */
  6582. customCacheKey() {
  6583. return hash$1( this._toneMapping );
  6584. }
  6585. /**
  6586. * Sets the tone mapping type.
  6587. *
  6588. * @param {number} value - The tone mapping type.
  6589. * @return {ToneMappingNode} A reference to this node.
  6590. */
  6591. setToneMapping( value ) {
  6592. this._toneMapping = value;
  6593. return this;
  6594. }
  6595. /**
  6596. * Gets the tone mapping type.
  6597. *
  6598. * @returns {number} The tone mapping type.
  6599. */
  6600. getToneMapping() {
  6601. return this._toneMapping;
  6602. }
  6603. setup( builder ) {
  6604. const colorNode = this.colorNode || builder.context.color;
  6605. const toneMapping = this._toneMapping;
  6606. if ( toneMapping === NoToneMapping ) return colorNode;
  6607. let outputNode = null;
  6608. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6609. if ( toneMappingFn !== null ) {
  6610. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6611. } else {
  6612. error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6613. outputNode = colorNode;
  6614. }
  6615. return outputNode;
  6616. }
  6617. }
  6618. /**
  6619. * TSL function for creating a tone mapping node.
  6620. *
  6621. * @tsl
  6622. * @function
  6623. * @param {number} mapping - The tone mapping type.
  6624. * @param {Node<float> | number} exposure - The tone mapping exposure.
  6625. * @param {Node<vec3> | Color} color - The color node to process.
  6626. * @returns {ToneMappingNode<vec3>}
  6627. */
  6628. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6629. /**
  6630. * TSL object that represents the global tone mapping exposure of the renderer.
  6631. *
  6632. * @tsl
  6633. * @type {RendererReferenceNode<vec3>}
  6634. */
  6635. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6636. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6637. /**
  6638. * Internal buffer attribute library.
  6639. *
  6640. * @private
  6641. * @type {WeakMap<TypedArray, InterleavedBuffer>}
  6642. */
  6643. const _bufferLib = new WeakMap();
  6644. /**
  6645. * Internal method for retrieving or creating interleaved buffers.
  6646. *
  6647. * @private
  6648. * @param {TypedArray} value - The attribute data.
  6649. * @param {number} itemSize - The attribute item size.
  6650. * @returns {InterleavedBuffer} The interleaved buffer.
  6651. */
  6652. function _getBufferAttribute( value, itemSize ) {
  6653. let buffer = _bufferLib.get( value );
  6654. if ( buffer === undefined ) {
  6655. buffer = new InterleavedBuffer( value, itemSize );
  6656. _bufferLib.set( value, buffer );
  6657. }
  6658. return buffer;
  6659. }
  6660. /**
  6661. * In earlier `three.js` versions it was only possible to define attribute data
  6662. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6663. * on the node level.
  6664. * ```js
  6665. * const geometry = new THREE.PlaneGeometry();
  6666. * const positionAttribute = geometry.getAttribute( 'position' );
  6667. *
  6668. * const colors = [];
  6669. * for ( let i = 0; i < position.count; i ++ ) {
  6670. * colors.push( 1, 0, 0 );
  6671. * }
  6672. *
  6673. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6674. * ```
  6675. * This new approach is especially interesting when geometry data are generated via
  6676. * compute shaders. The below line converts a storage buffer into an attribute node.
  6677. * ```js
  6678. * material.positionNode = positionBuffer.toAttribute();
  6679. * ```
  6680. * @augments InputNode
  6681. */
  6682. class BufferAttributeNode extends InputNode {
  6683. static get type() {
  6684. return 'BufferAttributeNode';
  6685. }
  6686. /**
  6687. * Constructs a new buffer attribute node.
  6688. *
  6689. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6690. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6691. * @param {number} [bufferStride=0] - The buffer stride.
  6692. * @param {number} [bufferOffset=0] - The buffer offset.
  6693. */
  6694. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6695. super( value, bufferType );
  6696. /**
  6697. * This flag can be used for type testing.
  6698. *
  6699. * @type {boolean}
  6700. * @readonly
  6701. * @default true
  6702. */
  6703. this.isBufferNode = true;
  6704. /**
  6705. * The buffer type (e.g. `'vec3'`).
  6706. *
  6707. * @type {?string}
  6708. * @default null
  6709. */
  6710. this.bufferType = bufferType;
  6711. /**
  6712. * The buffer stride.
  6713. *
  6714. * @type {number}
  6715. * @default 0
  6716. */
  6717. this.bufferStride = bufferStride;
  6718. /**
  6719. * The buffer offset.
  6720. *
  6721. * @type {number}
  6722. * @default 0
  6723. */
  6724. this.bufferOffset = bufferOffset;
  6725. /**
  6726. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6727. * if you are planning to update the attribute data per frame.
  6728. *
  6729. * @type {number}
  6730. * @default StaticDrawUsage
  6731. */
  6732. this.usage = StaticDrawUsage;
  6733. /**
  6734. * Whether the attribute is instanced or not.
  6735. *
  6736. * @type {boolean}
  6737. * @default false
  6738. */
  6739. this.instanced = false;
  6740. /**
  6741. * A reference to the buffer attribute.
  6742. *
  6743. * @type {?BufferAttribute}
  6744. * @default null
  6745. */
  6746. this.attribute = null;
  6747. /**
  6748. * `BufferAttributeNode` sets this property to `true` by default.
  6749. *
  6750. * @type {boolean}
  6751. * @default true
  6752. */
  6753. this.global = true;
  6754. if ( value && value.isBufferAttribute === true && value.itemSize <= 4 ) {
  6755. this.attribute = value;
  6756. this.usage = value.usage;
  6757. this.instanced = value.isInstancedBufferAttribute;
  6758. }
  6759. }
  6760. /**
  6761. * This method is overwritten since the attribute data might be shared
  6762. * and thus the hash should be shared as well.
  6763. *
  6764. * @param {NodeBuilder} builder - The current node builder.
  6765. * @return {string} The hash.
  6766. */
  6767. getHash( builder ) {
  6768. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6769. let bufferData = builder.globalCache.getData( this.value );
  6770. if ( bufferData === undefined ) {
  6771. bufferData = {
  6772. node: this
  6773. };
  6774. builder.globalCache.setData( this.value, bufferData );
  6775. }
  6776. return bufferData.node.uuid;
  6777. }
  6778. return this.uuid;
  6779. }
  6780. /**
  6781. * This method is overwritten since the node type is inferred from
  6782. * the buffer attribute.
  6783. *
  6784. * @param {NodeBuilder} builder - The current node builder.
  6785. * @return {string} The node type.
  6786. */
  6787. getNodeType( builder ) {
  6788. if ( this.bufferType === null ) {
  6789. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6790. }
  6791. return this.bufferType;
  6792. }
  6793. /**
  6794. * Depending on which value was passed to the node, `setup()` behaves
  6795. * differently. If no instance of `BufferAttribute` was passed, the method
  6796. * creates an internal attribute and configures it respectively.
  6797. *
  6798. * @param {NodeBuilder} builder - The current node builder.
  6799. */
  6800. setup( builder ) {
  6801. if ( this.attribute !== null ) return;
  6802. //
  6803. const type = this.getNodeType( builder );
  6804. const itemSize = builder.getTypeLength( type );
  6805. const value = this.value;
  6806. const stride = this.bufferStride || itemSize;
  6807. const offset = this.bufferOffset;
  6808. let buffer;
  6809. if ( value.isInterleavedBuffer === true ) {
  6810. buffer = value;
  6811. } else if ( value.isBufferAttribute === true ) {
  6812. buffer = _getBufferAttribute( value.array, stride );
  6813. } else {
  6814. buffer = _getBufferAttribute( value, stride );
  6815. }
  6816. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6817. buffer.setUsage( this.usage );
  6818. this.attribute = bufferAttribute;
  6819. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6820. }
  6821. /**
  6822. * Generates the code snippet of the buffer attribute node.
  6823. *
  6824. * @param {NodeBuilder} builder - The current node builder.
  6825. * @return {string} The generated code snippet.
  6826. */
  6827. generate( builder ) {
  6828. const nodeType = this.getNodeType( builder );
  6829. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6830. const propertyName = builder.getPropertyName( nodeAttribute );
  6831. let output = null;
  6832. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6833. this.name = propertyName;
  6834. output = propertyName;
  6835. } else {
  6836. const nodeVarying = varying( this );
  6837. output = nodeVarying.build( builder, nodeType );
  6838. }
  6839. return output;
  6840. }
  6841. /**
  6842. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6843. *
  6844. * @param {NodeBuilder} builder - The current node builder.
  6845. * @return {string} The input type.
  6846. */
  6847. getInputType( /*builder*/ ) {
  6848. return 'bufferAttribute';
  6849. }
  6850. /**
  6851. * Sets the `usage` property to the given value.
  6852. *
  6853. * @param {number} value - The usage to set.
  6854. * @return {BufferAttributeNode} A reference to this node.
  6855. */
  6856. setUsage( value ) {
  6857. this.usage = value;
  6858. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6859. this.attribute.usage = value;
  6860. }
  6861. return this;
  6862. }
  6863. /**
  6864. * Sets the `instanced` property to the given value.
  6865. *
  6866. * @param {boolean} value - The value to set.
  6867. * @return {BufferAttributeNode} A reference to this node.
  6868. */
  6869. setInstanced( value ) {
  6870. this.instanced = value;
  6871. return this;
  6872. }
  6873. }
  6874. /**
  6875. * Internal method for creating buffer attribute nodes.
  6876. *
  6877. * @private
  6878. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6879. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6880. * @param {number} [stride=0] - The buffer stride.
  6881. * @param {number} [offset=0] - The buffer offset.
  6882. * @param {number} [usage=StaticDrawUsage] - The buffer usage.
  6883. * @param {boolean} [instanced=false] - Whether the buffer is instanced.
  6884. * @returns {BufferAttributeNode|Node} The buffer attribute node.
  6885. */
  6886. function createBufferAttribute( array, type = null, stride = 0, offset = 0, usage = StaticDrawUsage, instanced = false ) {
  6887. if ( type === 'mat3' || ( type === null && array.itemSize === 9 ) ) {
  6888. return mat3(
  6889. new BufferAttributeNode( array, 'vec3', 9, 0 ).setUsage( usage ).setInstanced( instanced ),
  6890. new BufferAttributeNode( array, 'vec3', 9, 3 ).setUsage( usage ).setInstanced( instanced ),
  6891. new BufferAttributeNode( array, 'vec3', 9, 6 ).setUsage( usage ).setInstanced( instanced )
  6892. );
  6893. } else if ( type === 'mat4' || ( type === null && array.itemSize === 16 ) ) {
  6894. return mat4(
  6895. new BufferAttributeNode( array, 'vec4', 16, 0 ).setUsage( usage ).setInstanced( instanced ),
  6896. new BufferAttributeNode( array, 'vec4', 16, 4 ).setUsage( usage ).setInstanced( instanced ),
  6897. new BufferAttributeNode( array, 'vec4', 16, 8 ).setUsage( usage ).setInstanced( instanced ),
  6898. new BufferAttributeNode( array, 'vec4', 16, 12 ).setUsage( usage ).setInstanced( instanced )
  6899. );
  6900. }
  6901. return new BufferAttributeNode( array, type, stride, offset );
  6902. }
  6903. /**
  6904. * TSL function for creating a buffer attribute node.
  6905. *
  6906. * @tsl
  6907. * @function
  6908. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6909. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6910. * @param {number} [stride=0] - The buffer stride.
  6911. * @param {number} [offset=0] - The buffer offset.
  6912. * @returns {BufferAttributeNode|Node}
  6913. */
  6914. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset );
  6915. /**
  6916. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6917. * Use this function if attribute data are updated per frame.
  6918. *
  6919. * @tsl
  6920. * @function
  6921. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6922. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6923. * @param {number} [stride=0] - The buffer stride.
  6924. * @param {number} [offset=0] - The buffer offset.
  6925. * @returns {BufferAttributeNode|Node}
  6926. */
  6927. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage );
  6928. /**
  6929. * TSL function for creating a buffer attribute node but with enabled instancing
  6930. *
  6931. * @tsl
  6932. * @function
  6933. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6934. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6935. * @param {number} [stride=0] - The buffer stride.
  6936. * @param {number} [offset=0] - The buffer offset.
  6937. * @returns {BufferAttributeNode|Node}
  6938. */
  6939. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, StaticDrawUsage, true );
  6940. /**
  6941. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6942. *
  6943. * @tsl
  6944. * @function
  6945. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6946. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6947. * @param {number} [stride=0] - The buffer stride.
  6948. * @param {number} [offset=0] - The buffer offset.
  6949. * @returns {BufferAttributeNode|Node}
  6950. */
  6951. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage, true );
  6952. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6953. /**
  6954. * TODO
  6955. *
  6956. * @augments Node
  6957. */
  6958. class ComputeNode extends Node {
  6959. static get type() {
  6960. return 'ComputeNode';
  6961. }
  6962. /**
  6963. * Constructs a new compute node.
  6964. *
  6965. * @param {Node} computeNode - TODO
  6966. * @param {Array<number>} workgroupSize - TODO.
  6967. */
  6968. constructor( computeNode, workgroupSize ) {
  6969. super( 'void' );
  6970. /**
  6971. * This flag can be used for type testing.
  6972. *
  6973. * @type {boolean}
  6974. * @readonly
  6975. * @default true
  6976. */
  6977. this.isComputeNode = true;
  6978. /**
  6979. * TODO
  6980. *
  6981. * @type {Node}
  6982. */
  6983. this.computeNode = computeNode;
  6984. /**
  6985. * TODO
  6986. *
  6987. * @type {Array<number>}
  6988. * @default [ 64 ]
  6989. */
  6990. this.workgroupSize = workgroupSize;
  6991. /**
  6992. * TODO
  6993. *
  6994. * @type {number|Array<number>}
  6995. */
  6996. this.count = null;
  6997. /**
  6998. * TODO
  6999. *
  7000. * @type {number}
  7001. */
  7002. this.version = 1;
  7003. /**
  7004. * The name or label of the uniform.
  7005. *
  7006. * @type {string}
  7007. * @default ''
  7008. */
  7009. this.name = '';
  7010. /**
  7011. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  7012. * is executed once per object by default.
  7013. *
  7014. * @type {string}
  7015. * @default 'object'
  7016. */
  7017. this.updateBeforeType = NodeUpdateType.OBJECT;
  7018. /**
  7019. * TODO
  7020. *
  7021. * @type {?Function}
  7022. */
  7023. this.onInitFunction = null;
  7024. }
  7025. /**
  7026. * TODO
  7027. *
  7028. * @param {number|Array<number>} count - Array with [ x, y, z ] values for dispatch or a single number for the count
  7029. * @return {ComputeNode}
  7030. */
  7031. setCount( count ) {
  7032. this.count = count;
  7033. return this;
  7034. }
  7035. /**
  7036. * TODO
  7037. *
  7038. * @return {number|Array<number>}
  7039. */
  7040. getCount() {
  7041. return this.count;
  7042. }
  7043. /**
  7044. * Executes the `dispose` event for this node.
  7045. */
  7046. dispose() {
  7047. this.dispatchEvent( { type: 'dispose' } );
  7048. }
  7049. /**
  7050. * Sets the {@link ComputeNode#name} property.
  7051. *
  7052. * @param {string} name - The name of the uniform.
  7053. * @return {ComputeNode} A reference to this node.
  7054. */
  7055. setName( name ) {
  7056. this.name = name;
  7057. return this;
  7058. }
  7059. /**
  7060. * Sets the {@link ComputeNode#name} property.
  7061. *
  7062. * @deprecated
  7063. * @param {string} name - The name of the uniform.
  7064. * @return {ComputeNode} A reference to this node.
  7065. */
  7066. label( name ) {
  7067. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  7068. return this.setName( name );
  7069. }
  7070. /**
  7071. * TODO
  7072. *
  7073. * @param {Function} callback - TODO.
  7074. * @return {ComputeNode} A reference to this node.
  7075. */
  7076. onInit( callback ) {
  7077. this.onInitFunction = callback;
  7078. return this;
  7079. }
  7080. /**
  7081. * The method execute the compute for this node.
  7082. *
  7083. * @param {NodeFrame} frame - A reference to the current node frame.
  7084. */
  7085. updateBefore( { renderer } ) {
  7086. renderer.compute( this );
  7087. }
  7088. setup( builder ) {
  7089. const result = this.computeNode.build( builder );
  7090. if ( result ) {
  7091. const properties = builder.getNodeProperties( this );
  7092. properties.outputComputeNode = result.outputNode;
  7093. result.outputNode = null;
  7094. }
  7095. return result;
  7096. }
  7097. generate( builder, output ) {
  7098. const { shaderStage } = builder;
  7099. if ( shaderStage === 'compute' ) {
  7100. const snippet = this.computeNode.build( builder, 'void' );
  7101. if ( snippet !== '' ) {
  7102. builder.addLineFlowCode( snippet, this );
  7103. }
  7104. } else {
  7105. const properties = builder.getNodeProperties( this );
  7106. const outputComputeNode = properties.outputComputeNode;
  7107. if ( outputComputeNode ) {
  7108. return outputComputeNode.build( builder, output );
  7109. }
  7110. }
  7111. }
  7112. }
  7113. /**
  7114. * TSL function for creating a compute kernel node.
  7115. *
  7116. * @tsl
  7117. * @function
  7118. * @param {Node} node - TODO
  7119. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7120. * @returns {AtomicFunctionNode}
  7121. */
  7122. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  7123. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  7124. error( 'TSL: compute() workgroupSize must have 1, 2, or 3 elements' );
  7125. }
  7126. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  7127. const val = workgroupSize[ i ];
  7128. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  7129. error( `TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer` );
  7130. }
  7131. }
  7132. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  7133. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  7134. //
  7135. return nodeObject( new ComputeNode( nodeObject( node ), workgroupSize ) );
  7136. };
  7137. /**
  7138. * TSL function for creating a compute node.
  7139. *
  7140. * @tsl
  7141. * @function
  7142. * @param {Node} node - TODO
  7143. * @param {number|Array<number>} count - TODO.
  7144. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7145. * @returns {AtomicFunctionNode}
  7146. */
  7147. const compute = ( node, count, workgroupSize ) => computeKernel( node, workgroupSize ).setCount( count );
  7148. addMethodChaining( 'compute', compute );
  7149. addMethodChaining( 'computeKernel', computeKernel );
  7150. /**
  7151. * This node can be used as a cache management component for another node.
  7152. * Caching is in general used by default in {@link NodeBuilder} but this node
  7153. * allows the usage of a shared parent cache during the build process.
  7154. *
  7155. * @augments Node
  7156. */
  7157. class IsolateNode extends Node {
  7158. static get type() {
  7159. return 'IsolateNode';
  7160. }
  7161. /**
  7162. * Constructs a new cache node.
  7163. *
  7164. * @param {Node} node - The node that should be cached.
  7165. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7166. */
  7167. constructor( node, parent = true ) {
  7168. super();
  7169. /**
  7170. * The node that should be cached.
  7171. *
  7172. * @type {Node}
  7173. */
  7174. this.node = node;
  7175. /**
  7176. * Whether this node refers to a shared parent cache or not.
  7177. *
  7178. * @type {boolean}
  7179. * @default true
  7180. */
  7181. this.parent = parent;
  7182. /**
  7183. * This flag can be used for type testing.
  7184. *
  7185. * @type {boolean}
  7186. * @readonly
  7187. * @default true
  7188. */
  7189. this.isIsolateNode = true;
  7190. }
  7191. getNodeType( builder ) {
  7192. const previousCache = builder.getCache();
  7193. const cache = builder.getCacheFromNode( this, this.parent );
  7194. builder.setCache( cache );
  7195. const nodeType = this.node.getNodeType( builder );
  7196. builder.setCache( previousCache );
  7197. return nodeType;
  7198. }
  7199. build( builder, ...params ) {
  7200. const previousCache = builder.getCache();
  7201. const cache = builder.getCacheFromNode( this, this.parent );
  7202. builder.setCache( cache );
  7203. const data = this.node.build( builder, ...params );
  7204. builder.setCache( previousCache );
  7205. return data;
  7206. }
  7207. setParent( parent ) {
  7208. this.parent = parent;
  7209. return this;
  7210. }
  7211. getParent() {
  7212. return this.parent;
  7213. }
  7214. }
  7215. /**
  7216. * TSL function for creating a cache node.
  7217. *
  7218. * @tsl
  7219. * @function
  7220. * @param {Node} node - The node that should be cached.
  7221. * @returns {IsolateNode}
  7222. */
  7223. const isolate = ( node ) => new IsolateNode( nodeObject( node ) );
  7224. /**
  7225. * TSL function for creating a cache node.
  7226. *
  7227. * @tsl
  7228. * @function
  7229. * @deprecated
  7230. * @param {Node} node - The node that should be cached.
  7231. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7232. * @returns {IsolateNode}
  7233. */
  7234. function cache( node, parent = true ) {
  7235. warn( 'TSL: "cache()" has been deprecated. Use "isolate()" instead.' ); // @deprecated r181
  7236. return isolate( node ).setParent( parent );
  7237. }
  7238. addMethodChaining( 'cache', cache );
  7239. addMethodChaining( 'isolate', isolate );
  7240. /**
  7241. * The class generates the code of a given node but returns another node in the output.
  7242. * This can be used to call a method or node that does not return a value, i.e.
  7243. * type `void` on an input where returning a value is required. Example:
  7244. *
  7245. * ```js
  7246. * material.colorNode = myColor.bypass( runVoidFn() )
  7247. *```
  7248. *
  7249. * @augments Node
  7250. */
  7251. class BypassNode extends Node {
  7252. static get type() {
  7253. return 'BypassNode';
  7254. }
  7255. /**
  7256. * Constructs a new bypass node.
  7257. *
  7258. * @param {Node} outputNode - The output node.
  7259. * @param {Node} callNode - The call node.
  7260. */
  7261. constructor( outputNode, callNode ) {
  7262. super();
  7263. /**
  7264. * This flag can be used for type testing.
  7265. *
  7266. * @type {boolean}
  7267. * @readonly
  7268. * @default true
  7269. */
  7270. this.isBypassNode = true;
  7271. /**
  7272. * The output node.
  7273. *
  7274. * @type {Node}
  7275. */
  7276. this.outputNode = outputNode;
  7277. /**
  7278. * The call node.
  7279. *
  7280. * @type {Node}
  7281. */
  7282. this.callNode = callNode;
  7283. }
  7284. getNodeType( builder ) {
  7285. return this.outputNode.getNodeType( builder );
  7286. }
  7287. generate( builder ) {
  7288. const snippet = this.callNode.build( builder, 'void' );
  7289. if ( snippet !== '' ) {
  7290. builder.addLineFlowCode( snippet, this );
  7291. }
  7292. return this.outputNode.build( builder );
  7293. }
  7294. }
  7295. /**
  7296. * TSL function for creating a bypass node.
  7297. *
  7298. * @tsl
  7299. * @function
  7300. * @param {Node} outputNode - The output node.
  7301. * @param {Node} callNode - The call node.
  7302. * @returns {BypassNode}
  7303. */
  7304. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  7305. addMethodChaining( 'bypass', bypass );
  7306. /**
  7307. * This node allows to remap a node value from one range into another. E.g a value of
  7308. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7309. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  7310. *
  7311. * @augments Node
  7312. */
  7313. class RemapNode extends Node {
  7314. static get type() {
  7315. return 'RemapNode';
  7316. }
  7317. /**
  7318. * Constructs a new remap node.
  7319. *
  7320. * @param {Node} node - The node that should be remapped.
  7321. * @param {Node} inLowNode - The source or current lower bound of the range.
  7322. * @param {Node} inHighNode - The source or current upper bound of the range.
  7323. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  7324. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  7325. */
  7326. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  7327. super();
  7328. /**
  7329. * The node that should be remapped.
  7330. *
  7331. * @type {Node}
  7332. */
  7333. this.node = node;
  7334. /**
  7335. * The source or current lower bound of the range.
  7336. *
  7337. * @type {Node}
  7338. */
  7339. this.inLowNode = inLowNode;
  7340. /**
  7341. * The source or current upper bound of the range.
  7342. *
  7343. * @type {Node}
  7344. */
  7345. this.inHighNode = inHighNode;
  7346. /**
  7347. * The target lower bound of the range.
  7348. *
  7349. * @type {Node}
  7350. * @default float(0)
  7351. */
  7352. this.outLowNode = outLowNode;
  7353. /**
  7354. * The target upper bound of the range.
  7355. *
  7356. * @type {Node}
  7357. * @default float(1)
  7358. */
  7359. this.outHighNode = outHighNode;
  7360. /**
  7361. * Whether the node value should be clamped before
  7362. * remapping it to the target range.
  7363. *
  7364. * @type {boolean}
  7365. * @default true
  7366. */
  7367. this.doClamp = true;
  7368. }
  7369. setup() {
  7370. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  7371. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  7372. if ( doClamp === true ) t = t.clamp();
  7373. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  7374. }
  7375. }
  7376. /**
  7377. * TSL function for creating a remap node.
  7378. *
  7379. * @tsl
  7380. * @function
  7381. * @param {Node} node - The node that should be remapped.
  7382. * @param {Node} inLowNode - The source or current lower bound of the range.
  7383. * @param {Node} inHighNode - The source or current upper bound of the range.
  7384. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7385. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7386. * @returns {RemapNode}
  7387. */
  7388. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  7389. /**
  7390. * TSL function for creating a remap node, but with enabled clamping.
  7391. *
  7392. * @tsl
  7393. * @function
  7394. * @param {Node} node - The node that should be remapped.
  7395. * @param {Node} inLowNode - The source or current lower bound of the range.
  7396. * @param {Node} inHighNode - The source or current upper bound of the range.
  7397. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7398. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7399. * @returns {RemapNode}
  7400. */
  7401. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  7402. addMethodChaining( 'remap', remap );
  7403. addMethodChaining( 'remapClamp', remapClamp );
  7404. /**
  7405. * This class can be used to implement basic expressions in shader code.
  7406. * Basic examples for that are `return`, `continue` or `discard` statements.
  7407. *
  7408. * @augments Node
  7409. */
  7410. class ExpressionNode extends Node {
  7411. static get type() {
  7412. return 'ExpressionNode';
  7413. }
  7414. /**
  7415. * Constructs a new expression node.
  7416. *
  7417. * @param {string} [snippet=''] - The native code snippet.
  7418. * @param {string} [nodeType='void'] - The node type.
  7419. */
  7420. constructor( snippet = '', nodeType = 'void' ) {
  7421. super( nodeType );
  7422. /**
  7423. * The native code snippet.
  7424. *
  7425. * @type {string}
  7426. * @default ''
  7427. */
  7428. this.snippet = snippet;
  7429. }
  7430. generate( builder, output ) {
  7431. const type = this.getNodeType( builder );
  7432. const snippet = this.snippet;
  7433. if ( type === 'void' ) {
  7434. builder.addLineFlowCode( snippet, this );
  7435. } else {
  7436. return builder.format( snippet, type, output );
  7437. }
  7438. }
  7439. }
  7440. /**
  7441. * TSL function for creating an expression node.
  7442. *
  7443. * @tsl
  7444. * @function
  7445. * @param {string} [snippet] - The native code snippet.
  7446. * @param {?string} [nodeType='void'] - The node type.
  7447. * @returns {ExpressionNode}
  7448. */
  7449. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  7450. /**
  7451. * Represents a `discard` shader operation in TSL.
  7452. *
  7453. * @tsl
  7454. * @function
  7455. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  7456. * @return {Node} The `discard` expression.
  7457. */
  7458. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  7459. /**
  7460. * Represents a `return` shader operation in TSL.
  7461. *
  7462. * @tsl
  7463. * @function
  7464. * @return {ExpressionNode} The `return` expression.
  7465. */
  7466. const Return = () => expression( 'return' ).toStack();
  7467. addMethodChaining( 'discard', Discard );
  7468. /**
  7469. * Normally, tone mapping and color conversion happens automatically
  7470. * before outputting pixel too the default (screen) framebuffer. In certain
  7471. * post processing setups this happens to late because certain effects
  7472. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  7473. * to apply tone mapping and color space conversion at an arbitrary point
  7474. * in the effect chain.
  7475. *
  7476. * When applying tone mapping and color space conversion manually with this node,
  7477. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  7478. *
  7479. * ```js
  7480. * const postProcessing = new PostProcessing( renderer );
  7481. * postProcessing.outputColorTransform = false;
  7482. *
  7483. * const scenePass = pass( scene, camera );
  7484. * const outputPass = renderOutput( scenePass );
  7485. *
  7486. * postProcessing.outputNode = outputPass;
  7487. * ```
  7488. *
  7489. * @augments TempNode
  7490. */
  7491. class RenderOutputNode extends TempNode {
  7492. static get type() {
  7493. return 'RenderOutputNode';
  7494. }
  7495. /**
  7496. * Constructs a new render output node.
  7497. *
  7498. * @param {Node} colorNode - The color node to process.
  7499. * @param {?number} toneMapping - The tone mapping type.
  7500. * @param {?string} outputColorSpace - The output color space.
  7501. */
  7502. constructor( colorNode, toneMapping, outputColorSpace ) {
  7503. super( 'vec4' );
  7504. /**
  7505. * The color node to process.
  7506. *
  7507. * @type {Node}
  7508. */
  7509. this.colorNode = colorNode;
  7510. /**
  7511. * The tone mapping type.
  7512. *
  7513. * @private
  7514. * @type {?number}
  7515. */
  7516. this._toneMapping = toneMapping;
  7517. /**
  7518. * The output color space.
  7519. *
  7520. * @type {?string}
  7521. */
  7522. this.outputColorSpace = outputColorSpace;
  7523. /**
  7524. * This flag can be used for type testing.
  7525. *
  7526. * @type {boolean}
  7527. * @readonly
  7528. * @default true
  7529. */
  7530. this.isRenderOutputNode = true;
  7531. }
  7532. /**
  7533. * Sets the tone mapping type.
  7534. *
  7535. * @param {number} value - The tone mapping type.
  7536. * @return {ToneMappingNode} A reference to this node.
  7537. */
  7538. setToneMapping( value ) {
  7539. this._toneMapping = value;
  7540. return this;
  7541. }
  7542. /**
  7543. * Gets the tone mapping type.
  7544. *
  7545. * @returns {number} The tone mapping type.
  7546. */
  7547. getToneMapping() {
  7548. return this._toneMapping;
  7549. }
  7550. setup( { context } ) {
  7551. let outputNode = this.colorNode || context.color;
  7552. // tone mapping
  7553. const toneMapping = ( this._toneMapping !== null ? this._toneMapping : context.toneMapping ) || NoToneMapping;
  7554. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  7555. if ( toneMapping !== NoToneMapping ) {
  7556. outputNode = outputNode.toneMapping( toneMapping );
  7557. }
  7558. // working to output color space
  7559. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  7560. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  7561. }
  7562. return outputNode;
  7563. }
  7564. }
  7565. /**
  7566. * TSL function for creating a posterize node.
  7567. *
  7568. * @tsl
  7569. * @function
  7570. * @param {Node} color - The color node to process.
  7571. * @param {?number} [toneMapping=null] - The tone mapping type.
  7572. * @param {?string} [outputColorSpace=null] - The output color space.
  7573. * @returns {RenderOutputNode}
  7574. */
  7575. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  7576. addMethodChaining( 'renderOutput', renderOutput );
  7577. class DebugNode extends TempNode {
  7578. static get type() {
  7579. return 'DebugNode';
  7580. }
  7581. constructor( node, callback = null ) {
  7582. super();
  7583. this.node = node;
  7584. this.callback = callback;
  7585. }
  7586. getNodeType( builder ) {
  7587. return this.node.getNodeType( builder );
  7588. }
  7589. setup( builder ) {
  7590. return this.node.build( builder );
  7591. }
  7592. analyze( builder ) {
  7593. return this.node.build( builder );
  7594. }
  7595. generate( builder ) {
  7596. const callback = this.callback;
  7597. const snippet = this.node.build( builder );
  7598. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  7599. const border = '-'.repeat( title.length );
  7600. let code = '';
  7601. code += '// #' + title + '#\n';
  7602. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  7603. code += '/* ... */ ' + snippet + ' /* ... */\n';
  7604. code += '// #' + border + '#\n';
  7605. if ( callback !== null ) {
  7606. callback( builder, code );
  7607. } else {
  7608. log$1( code );
  7609. }
  7610. return snippet;
  7611. }
  7612. }
  7613. /**
  7614. * TSL function for creating a debug node.
  7615. *
  7616. * @tsl
  7617. * @function
  7618. * @param {Node} node - The node to debug.
  7619. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  7620. * @returns {DebugNode}
  7621. */
  7622. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) ).toStack();
  7623. addMethodChaining( 'debug', debug );
  7624. /**
  7625. * InspectorBase is the base class for all inspectors.
  7626. *
  7627. * @class InspectorBase
  7628. */
  7629. class InspectorBase {
  7630. /**
  7631. * Creates a new InspectorBase.
  7632. */
  7633. constructor() {
  7634. /**
  7635. * The renderer associated with this inspector.
  7636. *
  7637. * @type {WebGLRenderer}
  7638. * @private
  7639. */
  7640. this._renderer = null;
  7641. /**
  7642. * The current frame being processed.
  7643. *
  7644. * @type {Object}
  7645. */
  7646. this.currentFrame = null;
  7647. }
  7648. /**
  7649. * Returns the node frame for the current renderer.
  7650. *
  7651. * @return {Object} The node frame.
  7652. */
  7653. get nodeFrame() {
  7654. return this._renderer._nodes.nodeFrame;
  7655. }
  7656. /**
  7657. * Sets the renderer for this inspector.
  7658. *
  7659. * @param {WebGLRenderer} renderer - The renderer to associate with this inspector.
  7660. * @return {InspectorBase} This inspector instance.
  7661. */
  7662. setRenderer( renderer ) {
  7663. this._renderer = renderer;
  7664. return this;
  7665. }
  7666. /**
  7667. * Returns the renderer associated with this inspector.
  7668. *
  7669. * @return {WebGLRenderer} The associated renderer.
  7670. */
  7671. getRenderer() {
  7672. return this._renderer;
  7673. }
  7674. /**
  7675. * Initializes the inspector.
  7676. */
  7677. init() { }
  7678. /**
  7679. * Called when a frame begins.
  7680. */
  7681. begin() { }
  7682. /**
  7683. * Called when a frame ends.
  7684. */
  7685. finish() { }
  7686. /**
  7687. * Inspects a node.
  7688. *
  7689. * @param {Node} node - The node to inspect.
  7690. */
  7691. inspect( /*node*/ ) { }
  7692. /**
  7693. * When a compute operation is performed.
  7694. *
  7695. * @param {ComputeNode} computeNode - The compute node being executed.
  7696. * @param {number|Array<number>} dispatchSizeOrCount - The dispatch size or count.
  7697. */
  7698. computeAsync( /*computeNode, dispatchSizeOrCount*/ ) { }
  7699. /**
  7700. * Called when a compute operation begins.
  7701. *
  7702. * @param {string} uid - A unique identifier for the render context.
  7703. * @param {ComputeNode} computeNode - The compute node being executed.
  7704. */
  7705. beginCompute( /*uid, computeNode*/ ) { }
  7706. /**
  7707. * Called when a compute operation ends.
  7708. *
  7709. * @param {string} uid - A unique identifier for the render context.
  7710. * @param {ComputeNode} computeNode - The compute node being executed.
  7711. */
  7712. finishCompute( /*uid*/ ) { }
  7713. /**
  7714. * Called when a render operation begins.
  7715. *
  7716. * @param {string} uid - A unique identifier for the render context.
  7717. * @param {Scene} scene - The scene being rendered.
  7718. * @param {Camera} camera - The camera being used for rendering.
  7719. * @param {?WebGLRenderTarget} renderTarget - The render target, if any.
  7720. */
  7721. beginRender( /*uid, scene, camera, renderTarget*/ ) { }
  7722. /**
  7723. * Called when an animation loop ends.
  7724. *
  7725. * @param {string} uid - A unique identifier for the render context.
  7726. */
  7727. finishRender( /*uid*/ ) { }
  7728. /**
  7729. * Called when a texture copy operation is performed.
  7730. *
  7731. * @param {Texture} srcTexture - The source texture.
  7732. * @param {Texture} dstTexture - The destination texture.
  7733. */
  7734. copyTextureToTexture( /*srcTexture, dstTexture*/ ) { }
  7735. /**
  7736. * Called when a framebuffer copy operation is performed.
  7737. *
  7738. * @param {Texture} framebufferTexture - The texture associated with the framebuffer.
  7739. */
  7740. copyFramebufferToTexture( /*framebufferTexture*/ ) { }
  7741. }
  7742. /**
  7743. * InspectorNode is a wrapper node that allows inspection of node values during rendering.
  7744. * It can be used to debug or analyze node outputs in the rendering pipeline.
  7745. *
  7746. * @augments Node
  7747. */
  7748. class InspectorNode extends Node {
  7749. /**
  7750. * Returns the type of the node.
  7751. *
  7752. * @returns {string}
  7753. */
  7754. static get type() {
  7755. return 'InspectorNode';
  7756. }
  7757. /**
  7758. * Creates an InspectorNode.
  7759. *
  7760. * @param {Node} node - The node to inspect.
  7761. * @param {string} [name=''] - Optional name for the inspector node.
  7762. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7763. */
  7764. constructor( node, name = '', callback = null ) {
  7765. super();
  7766. this.node = node;
  7767. this.name = name;
  7768. this.callback = callback;
  7769. this.updateType = NodeUpdateType.FRAME;
  7770. this.isInspectorNode = true;
  7771. }
  7772. /**
  7773. * Returns the name of the inspector node.
  7774. *
  7775. * @returns {string}
  7776. */
  7777. getName() {
  7778. return this.name || this.node.name;
  7779. }
  7780. /**
  7781. * Updates the inspector node, allowing inspection of the wrapped node.
  7782. *
  7783. * @param {NodeFrame} frame - A reference to the current node frame.
  7784. */
  7785. update( frame ) {
  7786. frame.renderer.inspector.inspect( this );
  7787. }
  7788. /**
  7789. * Returns the type of the wrapped node.
  7790. *
  7791. * @param {NodeBuilder} builder - The node builder.
  7792. * @returns {string}
  7793. */
  7794. getNodeType( builder ) {
  7795. return this.node.getNodeType( builder );
  7796. }
  7797. /**
  7798. * Sets up the inspector node.
  7799. *
  7800. * @param {NodeBuilder} builder - The node builder.
  7801. * @returns {Node} The setup node.
  7802. */
  7803. setup( builder ) {
  7804. let node = this.node;
  7805. if ( builder.context.inspector === true && this.callback !== null ) {
  7806. node = this.callback( node );
  7807. }
  7808. if ( builder.renderer.backend.isWebGPUBackend !== true && builder.renderer.inspector.constructor !== InspectorBase ) {
  7809. warnOnce( 'TSL: ".toInspector()" is only available with WebGPU.' );
  7810. }
  7811. return node;
  7812. }
  7813. }
  7814. /**
  7815. * Creates an inspector node to wrap around a given node for inspection purposes.
  7816. *
  7817. * @tsl
  7818. * @param {Node} node - The node to inspect.
  7819. * @param {string} [name=''] - Optional name for the inspector node.
  7820. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7821. * @returns {Node} The inspector node.
  7822. */
  7823. function inspector( node, name = '', callback = null ) {
  7824. node = nodeObject( node );
  7825. return node.before( new InspectorNode( node, name, callback ) );
  7826. }
  7827. addMethodChaining( 'toInspector', inspector );
  7828. function addNodeElement( name/*, nodeElement*/ ) {
  7829. warn( 'TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  7830. }
  7831. /**
  7832. * Base class for representing shader attributes as nodes.
  7833. *
  7834. * @augments Node
  7835. */
  7836. class AttributeNode extends Node {
  7837. static get type() {
  7838. return 'AttributeNode';
  7839. }
  7840. /**
  7841. * Constructs a new attribute node.
  7842. *
  7843. * @param {string} attributeName - The name of the attribute.
  7844. * @param {?string} nodeType - The node type.
  7845. */
  7846. constructor( attributeName, nodeType = null ) {
  7847. super( nodeType );
  7848. /**
  7849. * `AttributeNode` sets this property to `true` by default.
  7850. *
  7851. * @type {boolean}
  7852. * @default true
  7853. */
  7854. this.global = true;
  7855. this._attributeName = attributeName;
  7856. }
  7857. getHash( builder ) {
  7858. return this.getAttributeName( builder );
  7859. }
  7860. getNodeType( builder ) {
  7861. let nodeType = this.nodeType;
  7862. if ( nodeType === null ) {
  7863. const attributeName = this.getAttributeName( builder );
  7864. if ( builder.hasGeometryAttribute( attributeName ) ) {
  7865. const attribute = builder.geometry.getAttribute( attributeName );
  7866. nodeType = builder.getTypeFromAttribute( attribute );
  7867. } else {
  7868. nodeType = 'float';
  7869. }
  7870. }
  7871. return nodeType;
  7872. }
  7873. /**
  7874. * Sets the attribute name to the given value. The method can be
  7875. * overwritten in derived classes if the final name must be computed
  7876. * analytically.
  7877. *
  7878. * @param {string} attributeName - The name of the attribute.
  7879. * @return {AttributeNode} A reference to this node.
  7880. */
  7881. setAttributeName( attributeName ) {
  7882. this._attributeName = attributeName;
  7883. return this;
  7884. }
  7885. /**
  7886. * Returns the attribute name of this node. The method can be
  7887. * overwritten in derived classes if the final name must be computed
  7888. * analytically.
  7889. *
  7890. * @param {NodeBuilder} builder - The current node builder.
  7891. * @return {string} The attribute name.
  7892. */
  7893. getAttributeName( /*builder*/ ) {
  7894. return this._attributeName;
  7895. }
  7896. generate( builder ) {
  7897. const attributeName = this.getAttributeName( builder );
  7898. const nodeType = this.getNodeType( builder );
  7899. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  7900. if ( geometryAttribute === true ) {
  7901. const attribute = builder.geometry.getAttribute( attributeName );
  7902. const attributeType = builder.getTypeFromAttribute( attribute );
  7903. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  7904. if ( builder.shaderStage === 'vertex' ) {
  7905. return builder.format( nodeAttribute.name, attributeType, nodeType );
  7906. } else {
  7907. const nodeVarying = varying( this );
  7908. return nodeVarying.build( builder, nodeType );
  7909. }
  7910. } else {
  7911. warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  7912. return builder.generateConst( nodeType );
  7913. }
  7914. }
  7915. serialize( data ) {
  7916. super.serialize( data );
  7917. data.global = this.global;
  7918. data._attributeName = this._attributeName;
  7919. }
  7920. deserialize( data ) {
  7921. super.deserialize( data );
  7922. this.global = data.global;
  7923. this._attributeName = data._attributeName;
  7924. }
  7925. }
  7926. /**
  7927. * TSL function for creating an attribute node.
  7928. *
  7929. * @tsl
  7930. * @function
  7931. * @param {string} name - The name of the attribute.
  7932. * @param {?string} [nodeType=null] - The node type.
  7933. * @returns {AttributeNode}
  7934. */
  7935. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  7936. /**
  7937. * TSL function for creating an uv attribute node with the given index.
  7938. *
  7939. * @tsl
  7940. * @function
  7941. * @param {number} [index=0] - The uv index.
  7942. * @return {AttributeNode<vec2>} The uv attribute node.
  7943. */
  7944. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  7945. /**
  7946. * A node that represents the dimensions of a texture. The texture size is
  7947. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  7948. * or `textureSize()`.
  7949. *
  7950. * @augments Node
  7951. */
  7952. class TextureSizeNode extends Node {
  7953. static get type() {
  7954. return 'TextureSizeNode';
  7955. }
  7956. /**
  7957. * Constructs a new texture size node.
  7958. *
  7959. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7960. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7961. */
  7962. constructor( textureNode, levelNode = null ) {
  7963. super( 'uvec2' );
  7964. /**
  7965. * This flag can be used for type testing.
  7966. *
  7967. * @type {boolean}
  7968. * @readonly
  7969. * @default true
  7970. */
  7971. this.isTextureSizeNode = true;
  7972. /**
  7973. * A texture node which size should be retrieved.
  7974. *
  7975. * @type {TextureNode}
  7976. */
  7977. this.textureNode = textureNode;
  7978. /**
  7979. * A level node which defines the requested mip.
  7980. *
  7981. * @type {Node<int>}
  7982. * @default null
  7983. */
  7984. this.levelNode = levelNode;
  7985. }
  7986. generate( builder, output ) {
  7987. const textureProperty = this.textureNode.build( builder, 'property' );
  7988. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  7989. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  7990. }
  7991. }
  7992. /**
  7993. * TSL function for creating a texture size node.
  7994. *
  7995. * @tsl
  7996. * @function
  7997. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7998. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7999. * @returns {TextureSizeNode}
  8000. */
  8001. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  8002. /**
  8003. * A special type of uniform node that computes the
  8004. * maximum mipmap level for a given texture node.
  8005. *
  8006. * ```js
  8007. * const level = maxMipLevel( textureNode );
  8008. * ```
  8009. *
  8010. * @augments UniformNode
  8011. */
  8012. class MaxMipLevelNode extends UniformNode {
  8013. static get type() {
  8014. return 'MaxMipLevelNode';
  8015. }
  8016. /**
  8017. * Constructs a new max mip level node.
  8018. *
  8019. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8020. */
  8021. constructor( textureNode ) {
  8022. super( 0 );
  8023. /**
  8024. * The texture node to compute the max mip level for.
  8025. *
  8026. * @private
  8027. * @type {TextureNode}
  8028. */
  8029. this._textureNode = textureNode;
  8030. /**
  8031. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  8032. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  8033. *
  8034. * @type {string}
  8035. * @default 'frame'
  8036. */
  8037. this.updateType = NodeUpdateType.FRAME;
  8038. }
  8039. /**
  8040. * The texture node to compute the max mip level for.
  8041. *
  8042. * @readonly
  8043. * @type {TextureNode}
  8044. */
  8045. get textureNode() {
  8046. return this._textureNode;
  8047. }
  8048. /**
  8049. * The texture.
  8050. *
  8051. * @readonly
  8052. * @type {Texture}
  8053. */
  8054. get texture() {
  8055. return this._textureNode.value;
  8056. }
  8057. update() {
  8058. const texture = this.texture;
  8059. const images = texture.images;
  8060. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  8061. if ( image && image.width !== undefined ) {
  8062. const { width, height } = image;
  8063. this.value = Math.log2( Math.max( width, height ) );
  8064. }
  8065. }
  8066. }
  8067. /**
  8068. * TSL function for creating a max mip level node.
  8069. *
  8070. * @tsl
  8071. * @function
  8072. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8073. * @returns {MaxMipLevelNode}
  8074. */
  8075. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  8076. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  8077. /**
  8078. * This type of uniform node represents a 2D texture.
  8079. *
  8080. * @augments UniformNode
  8081. */
  8082. class TextureNode extends UniformNode {
  8083. static get type() {
  8084. return 'TextureNode';
  8085. }
  8086. /**
  8087. * Constructs a new texture node.
  8088. *
  8089. * @param {Texture} [value=EmptyTexture] - The texture.
  8090. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8091. * @param {?Node<int>} [levelNode=null] - The level node.
  8092. * @param {?Node<float>} [biasNode=null] - The bias node.
  8093. */
  8094. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  8095. super( value );
  8096. /**
  8097. * This flag can be used for type testing.
  8098. *
  8099. * @type {boolean}
  8100. * @readonly
  8101. * @default true
  8102. */
  8103. this.isTextureNode = true;
  8104. /**
  8105. * Represents the texture coordinates.
  8106. *
  8107. * @type {?Node<vec2|vec3>}
  8108. * @default null
  8109. */
  8110. this.uvNode = uvNode;
  8111. /**
  8112. * Represents the mip level that should be selected.
  8113. *
  8114. * @type {?Node<int>}
  8115. * @default null
  8116. */
  8117. this.levelNode = levelNode;
  8118. /**
  8119. * Represents the bias to be applied during level-of-detail computation.
  8120. *
  8121. * @type {?Node<float>}
  8122. * @default null
  8123. */
  8124. this.biasNode = biasNode;
  8125. /**
  8126. * Represents a reference value a texture sample is compared to.
  8127. *
  8128. * @type {?Node<float>}
  8129. * @default null
  8130. */
  8131. this.compareNode = null;
  8132. /**
  8133. * When using texture arrays, the depth node defines the layer to select.
  8134. *
  8135. * @type {?Node<int>}
  8136. * @default null
  8137. */
  8138. this.depthNode = null;
  8139. /**
  8140. * When defined, a texture is sampled using explicit gradients.
  8141. *
  8142. * @type {?Array<Node<vec2>>}
  8143. * @default null
  8144. */
  8145. this.gradNode = null;
  8146. /**
  8147. * Represents the optional texel offset applied to the unnormalized texture
  8148. * coordinate before sampling the texture.
  8149. *
  8150. * @type {?Node<ivec2|ivec3>}
  8151. * @default null
  8152. */
  8153. this.offsetNode = null;
  8154. /**
  8155. * Whether texture values should be sampled or fetched.
  8156. *
  8157. * @type {boolean}
  8158. * @default true
  8159. */
  8160. this.sampler = true;
  8161. /**
  8162. * Whether the uv transformation matrix should be
  8163. * automatically updated or not. Use `setUpdateMatrix()`
  8164. * if you want to change the value of the property.
  8165. *
  8166. * @type {boolean}
  8167. * @default false
  8168. */
  8169. this.updateMatrix = false;
  8170. /**
  8171. * By default the `update()` method is not executed. Depending on
  8172. * whether a uv transformation matrix and/or flipY is applied, `update()`
  8173. * is executed per object.
  8174. *
  8175. * @type {string}
  8176. * @default 'none'
  8177. */
  8178. this.updateType = NodeUpdateType.NONE;
  8179. /**
  8180. * The reference node.
  8181. *
  8182. * @type {?Node}
  8183. * @default null
  8184. */
  8185. this.referenceNode = null;
  8186. /**
  8187. * The texture value is stored in a private property.
  8188. *
  8189. * @private
  8190. * @type {Texture}
  8191. */
  8192. this._value = value;
  8193. /**
  8194. * The uniform node that represents the uv transformation matrix.
  8195. *
  8196. * @private
  8197. * @type {?UniformNode<mat3>}
  8198. * @default null
  8199. */
  8200. this._matrixUniform = null;
  8201. /**
  8202. * The uniform node that represents the y-flip. Only required for WebGL.
  8203. *
  8204. * @private
  8205. * @type {?UniformNode<bool>}
  8206. * @default null
  8207. */
  8208. this._flipYUniform = null;
  8209. this.setUpdateMatrix( uvNode === null );
  8210. }
  8211. set value( value ) {
  8212. if ( this.referenceNode ) {
  8213. this.referenceNode.value = value;
  8214. } else {
  8215. this._value = value;
  8216. }
  8217. }
  8218. /**
  8219. * The texture value.
  8220. *
  8221. * @type {Texture}
  8222. */
  8223. get value() {
  8224. return this.referenceNode ? this.referenceNode.value : this._value;
  8225. }
  8226. /**
  8227. * Overwritten since the uniform hash is defined by the texture's UUID.
  8228. *
  8229. * @param {NodeBuilder} builder - The current node builder.
  8230. * @return {string} The uniform hash.
  8231. */
  8232. getUniformHash( /*builder*/ ) {
  8233. return this.value.uuid;
  8234. }
  8235. /**
  8236. * Overwritten since the node type is inferred from the texture type.
  8237. *
  8238. * @param {NodeBuilder} builder - The current node builder.
  8239. * @return {string} The node type.
  8240. */
  8241. getNodeType( /*builder*/ ) {
  8242. if ( this.value.isDepthTexture === true ) return 'float';
  8243. if ( this.value.type === UnsignedIntType ) {
  8244. return 'uvec4';
  8245. } else if ( this.value.type === IntType ) {
  8246. return 'ivec4';
  8247. }
  8248. return 'vec4';
  8249. }
  8250. /**
  8251. * Overwrites the default implementation to return a fixed value `'texture'`.
  8252. *
  8253. * @param {NodeBuilder} builder - The current node builder.
  8254. * @return {string} The input type.
  8255. */
  8256. getInputType( /*builder*/ ) {
  8257. return 'texture';
  8258. }
  8259. /**
  8260. * Returns a default uvs based on the current texture's channel.
  8261. *
  8262. * @return {AttributeNode<vec2>} The default uvs.
  8263. */
  8264. getDefaultUV() {
  8265. return uv$1( this.value.channel );
  8266. }
  8267. /**
  8268. * Overwritten to always return the texture reference of the node.
  8269. *
  8270. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  8271. * @return {Texture} The texture reference.
  8272. */
  8273. updateReference( /*state*/ ) {
  8274. return this.value;
  8275. }
  8276. /**
  8277. * Transforms the given uv node with the texture transformation matrix.
  8278. *
  8279. * @param {Node} uvNode - The uv node to transform.
  8280. * @return {Node} The transformed uv node.
  8281. */
  8282. getTransformedUV( uvNode ) {
  8283. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  8284. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  8285. }
  8286. /**
  8287. * Defines whether the uv transformation matrix should automatically be updated or not.
  8288. *
  8289. * @param {boolean} value - The update toggle.
  8290. * @return {TextureNode} A reference to this node.
  8291. */
  8292. setUpdateMatrix( value ) {
  8293. this.updateMatrix = value;
  8294. return this;
  8295. }
  8296. /**
  8297. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  8298. * to modify the uv node for correct sampling.
  8299. *
  8300. * @param {NodeBuilder} builder - The current node builder.
  8301. * @param {Node} uvNode - The uv node to setup.
  8302. * @return {Node} The updated uv node.
  8303. */
  8304. setupUV( builder, uvNode ) {
  8305. if ( builder.isFlipY() ) {
  8306. if ( this._flipYUniform === null ) this._flipYUniform = uniform( false );
  8307. uvNode = uvNode.toVar();
  8308. if ( this.sampler ) {
  8309. uvNode = this._flipYUniform.select( uvNode.flipY(), uvNode );
  8310. } else {
  8311. uvNode = this._flipYUniform.select( uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) ), uvNode );
  8312. }
  8313. }
  8314. return uvNode;
  8315. }
  8316. /**
  8317. * Setups texture node by preparing the internal nodes for code generation.
  8318. *
  8319. * @param {NodeBuilder} builder - The current node builder.
  8320. */
  8321. setup( builder ) {
  8322. const properties = builder.getNodeProperties( this );
  8323. properties.referenceNode = this.referenceNode;
  8324. //
  8325. const texture = this.value;
  8326. if ( ! texture || texture.isTexture !== true ) {
  8327. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  8328. }
  8329. //
  8330. const uvNode = Fn( () => {
  8331. let uvNode = this.uvNode;
  8332. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  8333. uvNode = builder.context.getUV( this, builder );
  8334. }
  8335. if ( ! uvNode ) uvNode = this.getDefaultUV();
  8336. if ( this.updateMatrix === true ) {
  8337. uvNode = this.getTransformedUV( uvNode );
  8338. }
  8339. uvNode = this.setupUV( builder, uvNode );
  8340. //
  8341. this.updateType = ( this._matrixUniform !== null || this._flipYUniform !== null ) ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  8342. //
  8343. return uvNode;
  8344. } )();
  8345. //
  8346. let levelNode = this.levelNode;
  8347. if ( levelNode === null && builder.context.getTextureLevel ) {
  8348. levelNode = builder.context.getTextureLevel( this );
  8349. }
  8350. //
  8351. properties.uvNode = uvNode;
  8352. properties.levelNode = levelNode;
  8353. properties.biasNode = this.biasNode;
  8354. properties.compareNode = this.compareNode;
  8355. properties.gradNode = this.gradNode;
  8356. properties.depthNode = this.depthNode;
  8357. properties.offsetNode = this.offsetNode;
  8358. }
  8359. /**
  8360. * Generates the uv code snippet.
  8361. *
  8362. * @param {NodeBuilder} builder - The current node builder.
  8363. * @param {Node} uvNode - The uv node to generate code for.
  8364. * @return {string} The generated code snippet.
  8365. */
  8366. generateUV( builder, uvNode ) {
  8367. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  8368. }
  8369. /**
  8370. * Generates the offset code snippet.
  8371. *
  8372. * @param {NodeBuilder} builder - The current node builder.
  8373. * @param {Node} offsetNode - The offset node to generate code for.
  8374. * @return {string} The generated code snippet.
  8375. */
  8376. generateOffset( builder, offsetNode ) {
  8377. return offsetNode.build( builder, 'ivec2' );
  8378. }
  8379. /**
  8380. * Generates the snippet for the texture sampling.
  8381. *
  8382. * @param {NodeBuilder} builder - The current node builder.
  8383. * @param {string} textureProperty - The texture property.
  8384. * @param {string} uvSnippet - The uv snippet.
  8385. * @param {?string} levelSnippet - The level snippet.
  8386. * @param {?string} biasSnippet - The bias snippet.
  8387. * @param {?string} depthSnippet - The depth snippet.
  8388. * @param {?string} compareSnippet - The compare snippet.
  8389. * @param {?Array<string>} gradSnippet - The grad snippet.
  8390. * @param {?string} offsetSnippet - The offset snippet.
  8391. * @return {string} The generated code snippet.
  8392. */
  8393. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet ) {
  8394. const texture = this.value;
  8395. let snippet;
  8396. if ( biasSnippet ) {
  8397. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet );
  8398. } else if ( gradSnippet ) {
  8399. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet );
  8400. } else if ( compareSnippet ) {
  8401. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet );
  8402. } else if ( this.sampler === false ) {
  8403. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8404. } else if ( levelSnippet ) {
  8405. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8406. } else {
  8407. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet );
  8408. }
  8409. return snippet;
  8410. }
  8411. /**
  8412. * Generates the code snippet of the texture node.
  8413. *
  8414. * @param {NodeBuilder} builder - The current node builder.
  8415. * @param {string} output - The current output.
  8416. * @return {string} The generated code snippet.
  8417. */
  8418. generate( builder, output ) {
  8419. const texture = this.value;
  8420. const properties = builder.getNodeProperties( this );
  8421. const textureProperty = super.generate( builder, 'property' );
  8422. if ( /^sampler/.test( output ) ) {
  8423. return textureProperty + '_sampler';
  8424. } else if ( builder.isReference( output ) ) {
  8425. return textureProperty;
  8426. } else {
  8427. const nodeData = builder.getDataFromNode( this );
  8428. let propertyName = nodeData.propertyName;
  8429. if ( propertyName === undefined ) {
  8430. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode, offsetNode } = properties;
  8431. const uvSnippet = this.generateUV( builder, uvNode );
  8432. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  8433. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  8434. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  8435. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  8436. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  8437. const offsetSnippet = offsetNode ? this.generateOffset( builder, offsetNode ) : null;
  8438. const nodeVar = builder.getVarFromNode( this );
  8439. propertyName = builder.getPropertyName( nodeVar );
  8440. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet );
  8441. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  8442. nodeData.snippet = snippet;
  8443. nodeData.propertyName = propertyName;
  8444. }
  8445. let snippet = propertyName;
  8446. const nodeType = this.getNodeType( builder );
  8447. if ( builder.needsToWorkingColorSpace( texture ) ) {
  8448. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  8449. }
  8450. return builder.format( snippet, nodeType, output );
  8451. }
  8452. }
  8453. /**
  8454. * Sets the sampler value.
  8455. *
  8456. * @param {boolean} value - The sampler value to set.
  8457. * @return {TextureNode} A reference to this texture node.
  8458. */
  8459. setSampler( value ) {
  8460. this.sampler = value;
  8461. return this;
  8462. }
  8463. /**
  8464. * Returns the sampler value.
  8465. *
  8466. * @return {boolean} The sampler value.
  8467. */
  8468. getSampler() {
  8469. return this.sampler;
  8470. }
  8471. // @TODO: Move to TSL
  8472. /**
  8473. * @function
  8474. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  8475. *
  8476. * @param {Node} uvNode - The uv node.
  8477. * @return {TextureNode} A texture node representing the texture sample.
  8478. */
  8479. uv( uvNode ) { // @deprecated, r172
  8480. warn( 'TextureNode: .uv() has been renamed. Use .sample() instead.' );
  8481. return this.sample( uvNode );
  8482. }
  8483. /**
  8484. * Samples the texture with the given uv node.
  8485. *
  8486. * @param {Node} uvNode - The uv node.
  8487. * @return {TextureNode} A texture node representing the texture sample.
  8488. */
  8489. sample( uvNode ) {
  8490. const textureNode = this.clone();
  8491. textureNode.uvNode = nodeObject( uvNode );
  8492. textureNode.referenceNode = this.getBase();
  8493. return nodeObject( textureNode );
  8494. }
  8495. /**
  8496. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8497. *
  8498. * @param {Node<uvec2>} uvNode - The uv node.
  8499. * @returns {TextureNode} A texture node representing the texture load.
  8500. */
  8501. load( uvNode ) {
  8502. return this.sample( uvNode ).setSampler( false );
  8503. }
  8504. /**
  8505. * Samples a blurred version of the texture by defining an internal bias.
  8506. *
  8507. * @param {Node<float>} amountNode - How blurred the texture should be.
  8508. * @return {TextureNode} A texture node representing the texture sample.
  8509. */
  8510. blur( amountNode ) {
  8511. const textureNode = this.clone();
  8512. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  8513. textureNode.referenceNode = this.getBase();
  8514. const map = textureNode.value;
  8515. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  8516. warn( 'TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  8517. textureNode.biasNode = null;
  8518. }
  8519. return nodeObject( textureNode );
  8520. }
  8521. /**
  8522. * Samples a specific mip of the texture.
  8523. *
  8524. * @param {Node<int>} levelNode - The mip level to sample.
  8525. * @return {TextureNode} A texture node representing the texture sample.
  8526. */
  8527. level( levelNode ) {
  8528. const textureNode = this.clone();
  8529. textureNode.levelNode = nodeObject( levelNode );
  8530. textureNode.referenceNode = this.getBase();
  8531. return nodeObject( textureNode );
  8532. }
  8533. /**
  8534. * Returns the texture size of the requested level.
  8535. *
  8536. * @param {Node<int>} levelNode - The level to compute the size for.
  8537. * @return {TextureSizeNode} The texture size.
  8538. */
  8539. size( levelNode ) {
  8540. return textureSize( this, levelNode );
  8541. }
  8542. /**
  8543. * Samples the texture with the given bias.
  8544. *
  8545. * @param {Node<float>} biasNode - The bias node.
  8546. * @return {TextureNode} A texture node representing the texture sample.
  8547. */
  8548. bias( biasNode ) {
  8549. const textureNode = this.clone();
  8550. textureNode.biasNode = nodeObject( biasNode );
  8551. textureNode.referenceNode = this.getBase();
  8552. return nodeObject( textureNode );
  8553. }
  8554. /**
  8555. * Returns the base texture of this node.
  8556. * @return {TextureNode} The base texture node.
  8557. */
  8558. getBase() {
  8559. return this.referenceNode ? this.referenceNode.getBase() : this;
  8560. }
  8561. /**
  8562. * Samples the texture by executing a compare operation.
  8563. *
  8564. * @param {Node<float>} compareNode - The node that defines the compare value.
  8565. * @return {TextureNode} A texture node representing the texture sample.
  8566. */
  8567. compare( compareNode ) {
  8568. const textureNode = this.clone();
  8569. textureNode.compareNode = nodeObject( compareNode );
  8570. textureNode.referenceNode = this.getBase();
  8571. return nodeObject( textureNode );
  8572. }
  8573. /**
  8574. * Samples the texture using an explicit gradient.
  8575. *
  8576. * @param {Node<vec2>} gradNodeX - The gradX node.
  8577. * @param {Node<vec2>} gradNodeY - The gradY node.
  8578. * @return {TextureNode} A texture node representing the texture sample.
  8579. */
  8580. grad( gradNodeX, gradNodeY ) {
  8581. const textureNode = this.clone();
  8582. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  8583. textureNode.referenceNode = this.getBase();
  8584. return nodeObject( textureNode );
  8585. }
  8586. /**
  8587. * Samples the texture by defining a depth node.
  8588. *
  8589. * @param {Node<int>} depthNode - The depth node.
  8590. * @return {TextureNode} A texture node representing the texture sample.
  8591. */
  8592. depth( depthNode ) {
  8593. const textureNode = this.clone();
  8594. textureNode.depthNode = nodeObject( depthNode );
  8595. textureNode.referenceNode = this.getBase();
  8596. return nodeObject( textureNode );
  8597. }
  8598. /**
  8599. * Samples the texture by defining an offset node.
  8600. *
  8601. * @param {Node<ivec2>} offsetNode - The offset node.
  8602. * @return {TextureNode} A texture node representing the texture sample.
  8603. */
  8604. offset( offsetNode ) {
  8605. const textureNode = this.clone();
  8606. textureNode.offsetNode = nodeObject( offsetNode );
  8607. textureNode.referenceNode = this.getBase();
  8608. return nodeObject( textureNode );
  8609. }
  8610. // --
  8611. serialize( data ) {
  8612. super.serialize( data );
  8613. data.value = this.value.toJSON( data.meta ).uuid;
  8614. data.sampler = this.sampler;
  8615. data.updateMatrix = this.updateMatrix;
  8616. data.updateType = this.updateType;
  8617. }
  8618. deserialize( data ) {
  8619. super.deserialize( data );
  8620. this.value = data.meta.textures[ data.value ];
  8621. this.sampler = data.sampler;
  8622. this.updateMatrix = data.updateMatrix;
  8623. this.updateType = data.updateType;
  8624. }
  8625. /**
  8626. * The update is used to implement the update of the uv transformation matrix.
  8627. */
  8628. update() {
  8629. const texture = this.value;
  8630. const matrixUniform = this._matrixUniform;
  8631. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  8632. if ( texture.matrixAutoUpdate === true ) {
  8633. texture.updateMatrix();
  8634. }
  8635. //
  8636. const flipYUniform = this._flipYUniform;
  8637. if ( flipYUniform !== null ) {
  8638. flipYUniform.value = ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true );
  8639. }
  8640. }
  8641. /**
  8642. * Clones the texture node.
  8643. *
  8644. * @return {TextureNode} The cloned texture node.
  8645. */
  8646. clone() {
  8647. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  8648. newNode.sampler = this.sampler;
  8649. newNode.depthNode = this.depthNode;
  8650. newNode.compareNode = this.compareNode;
  8651. newNode.gradNode = this.gradNode;
  8652. newNode.offsetNode = this.offsetNode;
  8653. return newNode;
  8654. }
  8655. }
  8656. /**
  8657. * TSL function for creating a texture node.
  8658. *
  8659. * @tsl
  8660. * @function
  8661. * @param {?Texture} value - The texture.
  8662. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8663. * @param {?Node<int>} [levelNode=null] - The level node.
  8664. * @param {?Node<float>} [biasNode=null] - The bias node.
  8665. * @returns {TextureNode}
  8666. */
  8667. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  8668. /**
  8669. * TSL function for creating a texture node or sample a texture node already existing.
  8670. *
  8671. * @tsl
  8672. * @function
  8673. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8674. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8675. * @param {?Node<int>} [levelNode=null] - The level node.
  8676. * @param {?Node<float>} [biasNode=null] - The bias node.
  8677. * @returns {TextureNode}
  8678. */
  8679. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  8680. let textureNode;
  8681. if ( value && value.isTextureNode === true ) {
  8682. textureNode = nodeObject( value.clone() );
  8683. textureNode.referenceNode = value.getBase(); // Ensure the reference is set to the original node
  8684. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  8685. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  8686. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  8687. } else {
  8688. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  8689. }
  8690. return textureNode;
  8691. };
  8692. /**
  8693. * TSL function for creating a uniform texture node.
  8694. *
  8695. * @tsl
  8696. * @function
  8697. * @param {?Texture} value - The texture.
  8698. * @returns {TextureNode}
  8699. */
  8700. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  8701. /**
  8702. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8703. *
  8704. * @tsl
  8705. * @function
  8706. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8707. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8708. * @param {?Node<int>} [levelNode=null] - The level node.
  8709. * @param {?Node<float>} [biasNode=null] - The bias node.
  8710. * @returns {TextureNode}
  8711. */
  8712. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  8713. const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  8714. /**
  8715. * Converts a texture or texture node to a sampler.
  8716. *
  8717. * @tsl
  8718. * @function
  8719. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8720. * @returns {Node}
  8721. */
  8722. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  8723. /**
  8724. * Converts a texture or texture node to a sampler comparison.
  8725. *
  8726. * @tsl
  8727. * @function
  8728. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8729. * @returns {Node}
  8730. */
  8731. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  8732. /**
  8733. * A special type of uniform node which represents array-like data
  8734. * as uniform buffers. The access usually happens via `element()`
  8735. * which returns an instance of {@link ArrayElementNode}. For example:
  8736. *
  8737. * ```js
  8738. * const bufferNode = buffer( array, 'mat4', count );
  8739. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  8740. * ```
  8741. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  8742. * since it handles more input types and automatically cares about buffer paddings.
  8743. *
  8744. * @augments UniformNode
  8745. */
  8746. class BufferNode extends UniformNode {
  8747. static get type() {
  8748. return 'BufferNode';
  8749. }
  8750. /**
  8751. * Constructs a new buffer node.
  8752. *
  8753. * @param {Array<number>} value - Array-like buffer data.
  8754. * @param {string} bufferType - The data type of the buffer.
  8755. * @param {number} [bufferCount=0] - The count of buffer elements.
  8756. */
  8757. constructor( value, bufferType, bufferCount = 0 ) {
  8758. super( value, bufferType );
  8759. /**
  8760. * This flag can be used for type testing.
  8761. *
  8762. * @type {boolean}
  8763. * @readonly
  8764. * @default true
  8765. */
  8766. this.isBufferNode = true;
  8767. /**
  8768. * The data type of the buffer.
  8769. *
  8770. * @type {string}
  8771. */
  8772. this.bufferType = bufferType;
  8773. /**
  8774. * The uniform node that holds the value of the reference node.
  8775. *
  8776. * @type {number}
  8777. * @default 0
  8778. */
  8779. this.bufferCount = bufferCount;
  8780. /**
  8781. * An array of update ranges.
  8782. *
  8783. * @type {Array<{start: number, count: number}>}
  8784. */
  8785. this.updateRanges = [];
  8786. }
  8787. /**
  8788. * Adds a range of data in the data array to be updated on the GPU.
  8789. *
  8790. * @param {number} start - Position at which to start update.
  8791. * @param {number} count - The number of components to update.
  8792. */
  8793. addUpdateRange( start, count ) {
  8794. this.updateRanges.push( { start, count } );
  8795. }
  8796. /**
  8797. * Clears the update ranges.
  8798. */
  8799. clearUpdateRanges() {
  8800. this.updateRanges.length = 0;
  8801. }
  8802. /**
  8803. * The data type of the buffer elements.
  8804. *
  8805. * @param {NodeBuilder} builder - The current node builder.
  8806. * @return {string} The element type.
  8807. */
  8808. getElementType( builder ) {
  8809. return this.getNodeType( builder );
  8810. }
  8811. /**
  8812. * Overwrites the default implementation to return a fixed value `'buffer'`.
  8813. *
  8814. * @param {NodeBuilder} builder - The current node builder.
  8815. * @return {string} The input type.
  8816. */
  8817. getInputType( /*builder*/ ) {
  8818. return 'buffer';
  8819. }
  8820. }
  8821. /**
  8822. * TSL function for creating a buffer node.
  8823. *
  8824. * @tsl
  8825. * @function
  8826. * @param {Array<number>} value - Array-like buffer data.
  8827. * @param {string} type - The data type of a buffer element.
  8828. * @param {number} count - The count of buffer elements.
  8829. * @returns {BufferNode}
  8830. */
  8831. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  8832. /**
  8833. * Represents the element access on uniform array nodes.
  8834. *
  8835. * @augments ArrayElementNode
  8836. */
  8837. class UniformArrayElementNode extends ArrayElementNode {
  8838. static get type() {
  8839. return 'UniformArrayElementNode';
  8840. }
  8841. /**
  8842. * Constructs a new buffer node.
  8843. *
  8844. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  8845. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  8846. */
  8847. constructor( uniformArrayNode, indexNode ) {
  8848. super( uniformArrayNode, indexNode );
  8849. /**
  8850. * This flag can be used for type testing.
  8851. *
  8852. * @type {boolean}
  8853. * @readonly
  8854. * @default true
  8855. */
  8856. this.isArrayBufferElementNode = true;
  8857. }
  8858. generate( builder ) {
  8859. const snippet = super.generate( builder );
  8860. const type = this.getNodeType();
  8861. const paddedType = this.node.getPaddedType();
  8862. return builder.format( snippet, paddedType, type );
  8863. }
  8864. }
  8865. /**
  8866. * Similar to {@link BufferNode} this module represents array-like data as
  8867. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  8868. * data types in the array (e.g `three.js` primitives) and automatically
  8869. * manage buffer padding. It should be the first choice when working with
  8870. * uniforms buffers.
  8871. * ```js
  8872. * const tintColors = uniformArray( [
  8873. * new Color( 1, 0, 0 ),
  8874. * new Color( 0, 1, 0 ),
  8875. * new Color( 0, 0, 1 )
  8876. * ], 'color' );
  8877. *
  8878. * const redColor = tintColors.element( 0 );
  8879. *
  8880. * @augments BufferNode
  8881. */
  8882. class UniformArrayNode extends BufferNode {
  8883. static get type() {
  8884. return 'UniformArrayNode';
  8885. }
  8886. /**
  8887. * Constructs a new uniform array node.
  8888. *
  8889. * @param {Array<any>} value - Array holding the buffer data.
  8890. * @param {?string} [elementType=null] - The data type of a buffer element.
  8891. */
  8892. constructor( value, elementType = null ) {
  8893. super( null );
  8894. /**
  8895. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  8896. * hold number primitives as well as three.js objects like vectors, matrices
  8897. * or colors.
  8898. *
  8899. * @type {Array<any>}
  8900. */
  8901. this.array = value;
  8902. /**
  8903. * The data type of an array element.
  8904. *
  8905. * @type {string}
  8906. */
  8907. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  8908. /**
  8909. * The padded type. Uniform buffers must conform to a certain buffer layout
  8910. * so a separate type is computed to ensure correct buffer size.
  8911. *
  8912. * @type {string}
  8913. */
  8914. this.paddedType = this.getPaddedType();
  8915. /**
  8916. * Overwritten since uniform array nodes are updated per render.
  8917. *
  8918. * @type {string}
  8919. * @default 'render'
  8920. */
  8921. this.updateType = NodeUpdateType.RENDER;
  8922. /**
  8923. * This flag can be used for type testing.
  8924. *
  8925. * @type {boolean}
  8926. * @readonly
  8927. * @default true
  8928. */
  8929. this.isArrayBufferNode = true;
  8930. }
  8931. /**
  8932. * This method is overwritten since the node type is inferred from the
  8933. * {@link UniformArrayNode#paddedType}.
  8934. *
  8935. * @param {NodeBuilder} builder - The current node builder.
  8936. * @return {string} The node type.
  8937. */
  8938. getNodeType( /*builder*/ ) {
  8939. return this.paddedType;
  8940. }
  8941. /**
  8942. * The data type of the array elements.
  8943. *
  8944. * @param {NodeBuilder} builder - The current node builder.
  8945. * @return {string} The element type.
  8946. */
  8947. getElementType() {
  8948. return this.elementType;
  8949. }
  8950. /**
  8951. * Returns the padded type based on the element type.
  8952. *
  8953. * @return {string} The padded type.
  8954. */
  8955. getPaddedType() {
  8956. const elementType = this.elementType;
  8957. let paddedType = 'vec4';
  8958. if ( elementType === 'mat2' ) {
  8959. paddedType = 'mat2';
  8960. } else if ( /mat/.test( elementType ) === true ) {
  8961. paddedType = 'mat4';
  8962. } else if ( elementType.charAt( 0 ) === 'i' ) {
  8963. paddedType = 'ivec4';
  8964. } else if ( elementType.charAt( 0 ) === 'u' ) {
  8965. paddedType = 'uvec4';
  8966. }
  8967. return paddedType;
  8968. }
  8969. /**
  8970. * The update makes sure to correctly transfer the data from the (complex) objects
  8971. * in the array to the internal, correctly padded value buffer.
  8972. *
  8973. * @param {NodeFrame} frame - A reference to the current node frame.
  8974. */
  8975. update( /*frame*/ ) {
  8976. const { array, value } = this;
  8977. const elementType = this.elementType;
  8978. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  8979. for ( let i = 0; i < array.length; i ++ ) {
  8980. const index = i * 4;
  8981. value[ index ] = array[ i ];
  8982. }
  8983. } else if ( elementType === 'color' ) {
  8984. for ( let i = 0; i < array.length; i ++ ) {
  8985. const index = i * 4;
  8986. const vector = array[ i ];
  8987. value[ index ] = vector.r;
  8988. value[ index + 1 ] = vector.g;
  8989. value[ index + 2 ] = vector.b || 0;
  8990. //value[ index + 3 ] = vector.a || 0;
  8991. }
  8992. } else if ( elementType === 'mat2' ) {
  8993. for ( let i = 0; i < array.length; i ++ ) {
  8994. const index = i * 4;
  8995. const matrix = array[ i ];
  8996. value[ index ] = matrix.elements[ 0 ];
  8997. value[ index + 1 ] = matrix.elements[ 1 ];
  8998. value[ index + 2 ] = matrix.elements[ 2 ];
  8999. value[ index + 3 ] = matrix.elements[ 3 ];
  9000. }
  9001. } else if ( elementType === 'mat3' ) {
  9002. for ( let i = 0; i < array.length; i ++ ) {
  9003. const index = i * 16;
  9004. const matrix = array[ i ];
  9005. value[ index ] = matrix.elements[ 0 ];
  9006. value[ index + 1 ] = matrix.elements[ 1 ];
  9007. value[ index + 2 ] = matrix.elements[ 2 ];
  9008. value[ index + 4 ] = matrix.elements[ 3 ];
  9009. value[ index + 5 ] = matrix.elements[ 4 ];
  9010. value[ index + 6 ] = matrix.elements[ 5 ];
  9011. value[ index + 8 ] = matrix.elements[ 6 ];
  9012. value[ index + 9 ] = matrix.elements[ 7 ];
  9013. value[ index + 10 ] = matrix.elements[ 8 ];
  9014. value[ index + 15 ] = 1;
  9015. }
  9016. } else if ( elementType === 'mat4' ) {
  9017. for ( let i = 0; i < array.length; i ++ ) {
  9018. const index = i * 16;
  9019. const matrix = array[ i ];
  9020. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  9021. value[ index + i ] = matrix.elements[ i ];
  9022. }
  9023. }
  9024. } else {
  9025. for ( let i = 0; i < array.length; i ++ ) {
  9026. const index = i * 4;
  9027. const vector = array[ i ];
  9028. value[ index ] = vector.x;
  9029. value[ index + 1 ] = vector.y;
  9030. value[ index + 2 ] = vector.z || 0;
  9031. value[ index + 3 ] = vector.w || 0;
  9032. }
  9033. }
  9034. }
  9035. /**
  9036. * Implement the value buffer creation based on the array data.
  9037. *
  9038. * @param {NodeBuilder} builder - A reference to the current node builder.
  9039. * @return {null}
  9040. */
  9041. setup( builder ) {
  9042. const length = this.array.length;
  9043. const elementType = this.elementType;
  9044. let arrayType = Float32Array;
  9045. const paddedType = this.paddedType;
  9046. const paddedElementLength = builder.getTypeLength( paddedType );
  9047. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  9048. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  9049. this.value = new arrayType( length * paddedElementLength );
  9050. this.bufferCount = length;
  9051. this.bufferType = paddedType;
  9052. return super.setup( builder );
  9053. }
  9054. /**
  9055. * Overwrites the default `element()` method to provide element access
  9056. * based on {@link UniformArrayNode}.
  9057. *
  9058. * @param {IndexNode} indexNode - The index node.
  9059. * @return {UniformArrayElementNode}
  9060. */
  9061. element( indexNode ) {
  9062. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  9063. }
  9064. }
  9065. /**
  9066. * TSL function for creating an uniform array node.
  9067. *
  9068. * @tsl
  9069. * @function
  9070. * @param {Array<any>} values - Array-like data.
  9071. * @param {?string} [nodeType] - The data type of the array elements.
  9072. * @returns {UniformArrayNode}
  9073. */
  9074. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  9075. /**
  9076. * The node allows to set values for built-in shader variables. That is
  9077. * required for features like hardware-accelerated vertex clipping.
  9078. *
  9079. * @augments Node
  9080. */
  9081. class BuiltinNode extends Node {
  9082. /**
  9083. * Constructs a new builtin node.
  9084. *
  9085. * @param {string} name - The name of the built-in shader variable.
  9086. */
  9087. constructor( name ) {
  9088. super( 'float' );
  9089. /**
  9090. * The name of the built-in shader variable.
  9091. *
  9092. * @type {string}
  9093. */
  9094. this.name = name;
  9095. /**
  9096. * This flag can be used for type testing.
  9097. *
  9098. * @type {boolean}
  9099. * @readonly
  9100. * @default true
  9101. */
  9102. this.isBuiltinNode = true;
  9103. }
  9104. /**
  9105. * Generates the code snippet of the builtin node.
  9106. *
  9107. * @param {NodeBuilder} builder - The current node builder.
  9108. * @return {string} The generated code snippet.
  9109. */
  9110. generate( /* builder */ ) {
  9111. return this.name;
  9112. }
  9113. }
  9114. /**
  9115. * TSL function for creating a builtin node.
  9116. *
  9117. * @tsl
  9118. * @function
  9119. * @param {string} name - The name of the built-in shader variable.
  9120. * @returns {BuiltinNode}
  9121. */
  9122. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  9123. let _screenSizeVec, _viewportVec;
  9124. /**
  9125. * This node provides a collection of screen related metrics.
  9126. * Depending on {@link ScreenNode#scope}, the nodes can represent
  9127. * resolution or viewport data as well as fragment or uv coordinates.
  9128. *
  9129. * @augments Node
  9130. */
  9131. class ScreenNode extends Node {
  9132. static get type() {
  9133. return 'ScreenNode';
  9134. }
  9135. /**
  9136. * Constructs a new screen node.
  9137. *
  9138. * @param {('coordinate'|'viewport'|'size'|'uv'|'dpr')} scope - The node's scope.
  9139. */
  9140. constructor( scope ) {
  9141. super();
  9142. /**
  9143. * The node represents different metric depending on which scope is selected.
  9144. *
  9145. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  9146. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  9147. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  9148. * - `ScreenNode.UV`: Normalized coordinates.
  9149. * - `ScreenNode.DPR`: Device pixel ratio.
  9150. *
  9151. * @type {('coordinate'|'viewport'|'size'|'uv'|'dpr')}
  9152. */
  9153. this.scope = scope;
  9154. /**
  9155. * This output node.
  9156. *
  9157. * @private
  9158. * @type {?Node}
  9159. * @default null
  9160. */
  9161. this._output = null;
  9162. /**
  9163. * This flag can be used for type testing.
  9164. *
  9165. * @type {boolean}
  9166. * @readonly
  9167. * @default true
  9168. */
  9169. this.isViewportNode = true;
  9170. }
  9171. /**
  9172. * This method is overwritten since the node type depends on the selected scope.
  9173. *
  9174. * @return {('float'|'vec2'|'vec4')} The node type.
  9175. */
  9176. getNodeType() {
  9177. if ( this.scope === ScreenNode.DPR ) return 'float';
  9178. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  9179. else return 'vec2';
  9180. }
  9181. /**
  9182. * This method is overwritten since the node's update type depends on the selected scope.
  9183. *
  9184. * @return {NodeUpdateType} The update type.
  9185. */
  9186. getUpdateType() {
  9187. let updateType = NodeUpdateType.NONE;
  9188. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT || this.scope === ScreenNode.DPR ) {
  9189. updateType = NodeUpdateType.RENDER;
  9190. }
  9191. this.updateType = updateType;
  9192. return updateType;
  9193. }
  9194. /**
  9195. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  9196. * from the current renderer.
  9197. *
  9198. * @param {NodeFrame} frame - A reference to the current node frame.
  9199. */
  9200. update( { renderer } ) {
  9201. const renderTarget = renderer.getRenderTarget();
  9202. if ( this.scope === ScreenNode.VIEWPORT ) {
  9203. if ( renderTarget !== null ) {
  9204. _viewportVec.copy( renderTarget.viewport );
  9205. } else {
  9206. renderer.getViewport( _viewportVec );
  9207. _viewportVec.multiplyScalar( renderer.getPixelRatio() );
  9208. }
  9209. } else if ( this.scope === ScreenNode.DPR ) {
  9210. this._output.value = renderer.getPixelRatio();
  9211. } else {
  9212. if ( renderTarget !== null ) {
  9213. _screenSizeVec.width = renderTarget.width;
  9214. _screenSizeVec.height = renderTarget.height;
  9215. } else {
  9216. renderer.getDrawingBufferSize( _screenSizeVec );
  9217. }
  9218. }
  9219. }
  9220. setup( /*builder*/ ) {
  9221. const scope = this.scope;
  9222. let output = null;
  9223. if ( scope === ScreenNode.SIZE ) {
  9224. output = uniform( _screenSizeVec || ( _screenSizeVec = new Vector2() ) );
  9225. } else if ( scope === ScreenNode.VIEWPORT ) {
  9226. output = uniform( _viewportVec || ( _viewportVec = new Vector4() ) );
  9227. } else if ( scope === ScreenNode.DPR ) {
  9228. output = uniform( 1 );
  9229. } else {
  9230. output = vec2( screenCoordinate.div( screenSize ) );
  9231. }
  9232. this._output = output;
  9233. return output;
  9234. }
  9235. generate( builder ) {
  9236. if ( this.scope === ScreenNode.COORDINATE ) {
  9237. let coord = builder.getFragCoord();
  9238. if ( builder.isFlipY() ) {
  9239. // follow webgpu standards
  9240. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  9241. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  9242. }
  9243. return coord;
  9244. }
  9245. return super.generate( builder );
  9246. }
  9247. }
  9248. ScreenNode.COORDINATE = 'coordinate';
  9249. ScreenNode.VIEWPORT = 'viewport';
  9250. ScreenNode.SIZE = 'size';
  9251. ScreenNode.UV = 'uv';
  9252. ScreenNode.DPR = 'dpr';
  9253. // Screen
  9254. /**
  9255. * TSL object that represents the current DPR.
  9256. *
  9257. * @tsl
  9258. * @type {ScreenNode<float>}
  9259. */
  9260. const screenDPR = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.DPR );
  9261. /**
  9262. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  9263. *
  9264. * @tsl
  9265. * @type {ScreenNode<vec2>}
  9266. */
  9267. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  9268. /**
  9269. * TSL object that represents the screen resolution in physical pixel units.
  9270. *
  9271. * @tsl
  9272. * @type {ScreenNode<vec2>}
  9273. */
  9274. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  9275. /**
  9276. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  9277. *
  9278. * @tsl
  9279. * @type {ScreenNode<vec2>}
  9280. */
  9281. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  9282. // Viewport
  9283. /**
  9284. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  9285. *
  9286. * @tsl
  9287. * @type {ScreenNode<vec4>}
  9288. */
  9289. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  9290. /**
  9291. * TSL object that represents the viewport resolution in physical pixel units.
  9292. *
  9293. * @tsl
  9294. * @type {ScreenNode<vec2>}
  9295. */
  9296. const viewportSize = viewport.zw;
  9297. /**
  9298. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  9299. *
  9300. * @tsl
  9301. * @type {ScreenNode<vec2>}
  9302. */
  9303. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  9304. /**
  9305. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  9306. *
  9307. * @tsl
  9308. * @type {ScreenNode<vec2>}
  9309. */
  9310. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  9311. // Deprecated
  9312. /**
  9313. * @deprecated since r169. Use {@link screenSize} instead.
  9314. */
  9315. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  9316. warn( 'TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  9317. return screenSize;
  9318. }, 'vec2' ).once() )();
  9319. /**
  9320. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  9321. *
  9322. * @tsl
  9323. * @type {UniformNode<uint>}
  9324. */
  9325. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  9326. /**
  9327. * TSL object that represents the `near` value of the camera used for the current render.
  9328. *
  9329. * @tsl
  9330. * @type {UniformNode<float>}
  9331. */
  9332. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  9333. /**
  9334. * TSL object that represents the `far` value of the camera used for the current render.
  9335. *
  9336. * @tsl
  9337. * @type {UniformNode<float>}
  9338. */
  9339. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  9340. /**
  9341. * TSL object that represents the projection matrix of the camera used for the current render.
  9342. *
  9343. * @tsl
  9344. * @type {UniformNode<mat4>}
  9345. */
  9346. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9347. let cameraProjectionMatrix;
  9348. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9349. const matrices = [];
  9350. for ( const subCamera of camera.cameras ) {
  9351. matrices.push( subCamera.projectionMatrix );
  9352. }
  9353. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  9354. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrix' );
  9355. } else {
  9356. cameraProjectionMatrix = uniform( 'mat4' ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  9357. }
  9358. return cameraProjectionMatrix;
  9359. } ).once() )();
  9360. /**
  9361. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  9362. *
  9363. * @tsl
  9364. * @type {UniformNode<mat4>}
  9365. */
  9366. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9367. let cameraProjectionMatrixInverse;
  9368. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9369. const matrices = [];
  9370. for ( const subCamera of camera.cameras ) {
  9371. matrices.push( subCamera.projectionMatrixInverse );
  9372. }
  9373. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  9374. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrixInverse' );
  9375. } else {
  9376. cameraProjectionMatrixInverse = uniform( 'mat4' ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  9377. }
  9378. return cameraProjectionMatrixInverse;
  9379. } ).once() )();
  9380. /**
  9381. * TSL object that represents the view matrix of the camera used for the current render.
  9382. *
  9383. * @tsl
  9384. * @type {UniformNode<mat4>}
  9385. */
  9386. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9387. let cameraViewMatrix;
  9388. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9389. const matrices = [];
  9390. for ( const subCamera of camera.cameras ) {
  9391. matrices.push( subCamera.matrixWorldInverse );
  9392. }
  9393. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  9394. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraViewMatrix' );
  9395. } else {
  9396. cameraViewMatrix = uniform( 'mat4' ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  9397. }
  9398. return cameraViewMatrix;
  9399. } ).once() )();
  9400. /**
  9401. * TSL object that represents the world matrix of the camera used for the current render.
  9402. *
  9403. * @tsl
  9404. * @type {UniformNode<mat4>}
  9405. */
  9406. const cameraWorldMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9407. let cameraWorldMatrix;
  9408. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9409. const matrices = [];
  9410. for ( const subCamera of camera.cameras ) {
  9411. matrices.push( subCamera.matrixWorld );
  9412. }
  9413. const cameraWorldMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraWorldMatrices' );
  9414. cameraWorldMatrix = cameraWorldMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraWorldMatrix' );
  9415. } else {
  9416. cameraWorldMatrix = uniform( 'mat4' ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  9417. }
  9418. return cameraWorldMatrix;
  9419. } ).once() )();
  9420. /**
  9421. * TSL object that represents the normal matrix of the camera used for the current render.
  9422. *
  9423. * @tsl
  9424. * @type {UniformNode<mat3>}
  9425. */
  9426. const cameraNormalMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9427. let cameraNormalMatrix;
  9428. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9429. const matrices = [];
  9430. for ( const subCamera of camera.cameras ) {
  9431. matrices.push( subCamera.normalMatrix );
  9432. }
  9433. const cameraNormalMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraNormalMatrices' );
  9434. cameraNormalMatrix = cameraNormalMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraNormalMatrix' );
  9435. } else {
  9436. cameraNormalMatrix = uniform( 'mat3' ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  9437. }
  9438. return cameraNormalMatrix;
  9439. } ).once() )();
  9440. /**
  9441. * TSL object that represents the position in world space of the camera used for the current render.
  9442. *
  9443. * @tsl
  9444. * @type {UniformNode<vec3>}
  9445. */
  9446. const cameraPosition = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9447. let cameraPosition;
  9448. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9449. const positions = [];
  9450. for ( let i = 0, l = camera.cameras.length; i < l; i ++ ) {
  9451. positions.push( new Vector3() );
  9452. }
  9453. const cameraPositions = uniformArray( positions ).setGroup( renderGroup ).setName( 'cameraPositions' ).onRenderUpdate( ( { camera }, self ) => {
  9454. const subCameras = camera.cameras;
  9455. const array = self.array;
  9456. for ( let i = 0, l = subCameras.length; i < l; i ++ ) {
  9457. array[ i ].setFromMatrixPosition( subCameras[ i ].matrixWorld );
  9458. }
  9459. } );
  9460. cameraPosition = cameraPositions.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraPosition' );
  9461. } else {
  9462. cameraPosition = uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  9463. }
  9464. return cameraPosition;
  9465. } ).once() )();
  9466. /**
  9467. * TSL object that represents the viewport of the camera used for the current render.
  9468. *
  9469. * @tsl
  9470. * @type {UniformNode<vec4>}
  9471. */
  9472. const cameraViewport = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9473. let cameraViewport;
  9474. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9475. const viewports = [];
  9476. for ( const subCamera of camera.cameras ) {
  9477. viewports.push( subCamera.viewport );
  9478. }
  9479. const cameraViewports = uniformArray( viewports, 'vec4' ).setGroup( renderGroup ).setName( 'cameraViewports' );
  9480. cameraViewport = cameraViewports.element( cameraIndex ).toConst( 'cameraViewport' );
  9481. } else {
  9482. // Fallback for single camera
  9483. cameraViewport = vec4( 0, 0, screenSize.x, screenSize.y ).toConst( 'cameraViewport' );
  9484. }
  9485. return cameraViewport;
  9486. } ).once() )();
  9487. const _sphere = /*@__PURE__*/ new Sphere();
  9488. /**
  9489. * This node can be used to access transformation related metrics of 3D objects.
  9490. * Depending on the selected scope, a different metric is represented as a uniform
  9491. * in the shader. The following scopes are supported:
  9492. *
  9493. * - `POSITION`: The object's position in world space.
  9494. * - `VIEW_POSITION`: The object's position in view/camera space.
  9495. * - `DIRECTION`: The object's direction in world space.
  9496. * - `SCALE`: The object's scale in world space.
  9497. * - `WORLD_MATRIX`: The object's matrix in world space.
  9498. *
  9499. * @augments Node
  9500. */
  9501. class Object3DNode extends Node {
  9502. static get type() {
  9503. return 'Object3DNode';
  9504. }
  9505. /**
  9506. * Constructs a new object 3D node.
  9507. *
  9508. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9509. * @param {?Object3D} [object3d=null] - The 3D object.
  9510. */
  9511. constructor( scope, object3d = null ) {
  9512. super();
  9513. /**
  9514. * The node reports a different type of transformation depending on the scope.
  9515. *
  9516. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  9517. */
  9518. this.scope = scope;
  9519. /**
  9520. * The 3D object.
  9521. *
  9522. * @type {?Object3D}
  9523. * @default null
  9524. */
  9525. this.object3d = object3d;
  9526. /**
  9527. * Overwritten since this type of node is updated per object.
  9528. *
  9529. * @type {string}
  9530. * @default 'object'
  9531. */
  9532. this.updateType = NodeUpdateType.OBJECT;
  9533. /**
  9534. * Holds the value of the node as a uniform.
  9535. *
  9536. * @type {UniformNode}
  9537. */
  9538. this.uniformNode = new UniformNode( null );
  9539. }
  9540. /**
  9541. * Overwritten since the node type is inferred from the scope.
  9542. *
  9543. * @return {('mat4'|'vec3'|'float')} The node type.
  9544. */
  9545. getNodeType() {
  9546. const scope = this.scope;
  9547. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9548. return 'mat4';
  9549. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9550. return 'vec3';
  9551. } else if ( scope === Object3DNode.RADIUS ) {
  9552. return 'float';
  9553. }
  9554. }
  9555. /**
  9556. * Updates the uniform value depending on the scope.
  9557. *
  9558. * @param {NodeFrame} frame - The current node frame.
  9559. */
  9560. update( frame ) {
  9561. const object = this.object3d;
  9562. const uniformNode = this.uniformNode;
  9563. const scope = this.scope;
  9564. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9565. uniformNode.value = object.matrixWorld;
  9566. } else if ( scope === Object3DNode.POSITION ) {
  9567. uniformNode.value = uniformNode.value || new Vector3();
  9568. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9569. } else if ( scope === Object3DNode.SCALE ) {
  9570. uniformNode.value = uniformNode.value || new Vector3();
  9571. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  9572. } else if ( scope === Object3DNode.DIRECTION ) {
  9573. uniformNode.value = uniformNode.value || new Vector3();
  9574. object.getWorldDirection( uniformNode.value );
  9575. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  9576. const camera = frame.camera;
  9577. uniformNode.value = uniformNode.value || new Vector3();
  9578. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9579. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  9580. } else if ( scope === Object3DNode.RADIUS ) {
  9581. const geometry = frame.object.geometry;
  9582. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9583. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  9584. uniformNode.value = _sphere.radius;
  9585. }
  9586. }
  9587. /**
  9588. * Generates the code snippet of the uniform node. The node type of the uniform
  9589. * node also depends on the selected scope.
  9590. *
  9591. * @param {NodeBuilder} builder - The current node builder.
  9592. * @return {string} The generated code snippet.
  9593. */
  9594. generate( builder ) {
  9595. const scope = this.scope;
  9596. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9597. this.uniformNode.nodeType = 'mat4';
  9598. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9599. this.uniformNode.nodeType = 'vec3';
  9600. } else if ( scope === Object3DNode.RADIUS ) {
  9601. this.uniformNode.nodeType = 'float';
  9602. }
  9603. return this.uniformNode.build( builder );
  9604. }
  9605. serialize( data ) {
  9606. super.serialize( data );
  9607. data.scope = this.scope;
  9608. }
  9609. deserialize( data ) {
  9610. super.deserialize( data );
  9611. this.scope = data.scope;
  9612. }
  9613. }
  9614. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  9615. Object3DNode.POSITION = 'position';
  9616. Object3DNode.SCALE = 'scale';
  9617. Object3DNode.VIEW_POSITION = 'viewPosition';
  9618. Object3DNode.DIRECTION = 'direction';
  9619. Object3DNode.RADIUS = 'radius';
  9620. /**
  9621. * TSL function for creating an object 3D node that represents the object's direction in world space.
  9622. *
  9623. * @tsl
  9624. * @function
  9625. * @param {?Object3D} [object3d] - The 3D object.
  9626. * @returns {Object3DNode<vec3>}
  9627. */
  9628. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  9629. /**
  9630. * TSL function for creating an object 3D node that represents the object's world matrix.
  9631. *
  9632. * @tsl
  9633. * @function
  9634. * @param {?Object3D} [object3d] - The 3D object.
  9635. * @returns {Object3DNode<mat4>}
  9636. */
  9637. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  9638. /**
  9639. * TSL function for creating an object 3D node that represents the object's position in world space.
  9640. *
  9641. * @tsl
  9642. * @function
  9643. * @param {?Object3D} [object3d] - The 3D object.
  9644. * @returns {Object3DNode<vec3>}
  9645. */
  9646. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  9647. /**
  9648. * TSL function for creating an object 3D node that represents the object's scale in world space.
  9649. *
  9650. * @tsl
  9651. * @function
  9652. * @param {?Object3D} [object3d] - The 3D object.
  9653. * @returns {Object3DNode<vec3>}
  9654. */
  9655. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  9656. /**
  9657. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  9658. *
  9659. * @tsl
  9660. * @function
  9661. * @param {?Object3D} [object3d] - The 3D object.
  9662. * @returns {Object3DNode<vec3>}
  9663. */
  9664. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  9665. /**
  9666. * TSL function for creating an object 3D node that represents the object's radius.
  9667. *
  9668. * @tsl
  9669. * @function
  9670. * @param {?Object3D} [object3d] - The 3D object.
  9671. * @returns {Object3DNode<float>}
  9672. */
  9673. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  9674. /**
  9675. * This type of node is a specialized version of `Object3DNode`
  9676. * with larger set of model related metrics. Unlike `Object3DNode`,
  9677. * `ModelNode` extracts the reference to the 3D object from the
  9678. * current node frame state.
  9679. *
  9680. * @augments Object3DNode
  9681. */
  9682. class ModelNode extends Object3DNode {
  9683. static get type() {
  9684. return 'ModelNode';
  9685. }
  9686. /**
  9687. * Constructs a new object model node.
  9688. *
  9689. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9690. */
  9691. constructor( scope ) {
  9692. super( scope );
  9693. }
  9694. /**
  9695. * Extracts the model reference from the frame state and then
  9696. * updates the uniform value depending on the scope.
  9697. *
  9698. * @param {NodeFrame} frame - The current node frame.
  9699. */
  9700. update( frame ) {
  9701. this.object3d = frame.object;
  9702. super.update( frame );
  9703. }
  9704. }
  9705. /**
  9706. * TSL object that represents the object's direction in world space.
  9707. *
  9708. * @tsl
  9709. * @type {ModelNode<vec3>}
  9710. */
  9711. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  9712. /**
  9713. * TSL object that represents the object's world matrix.
  9714. *
  9715. * @tsl
  9716. * @type {ModelNode<mat4>}
  9717. */
  9718. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  9719. /**
  9720. * TSL object that represents the object's position in world space.
  9721. *
  9722. * @tsl
  9723. * @type {ModelNode<vec3>}
  9724. */
  9725. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  9726. /**
  9727. * TSL object that represents the object's scale in world space.
  9728. *
  9729. * @tsl
  9730. * @type {ModelNode<vec3>}
  9731. */
  9732. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  9733. /**
  9734. * TSL object that represents the object's position in view/camera space.
  9735. *
  9736. * @tsl
  9737. * @type {ModelNode<vec3>}
  9738. */
  9739. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  9740. /**
  9741. * TSL object that represents the object's radius.
  9742. *
  9743. * @tsl
  9744. * @type {ModelNode<float>}
  9745. */
  9746. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  9747. /**
  9748. * TSL object that represents the object's normal matrix.
  9749. *
  9750. * @tsl
  9751. * @type {UniformNode<mat3>}
  9752. */
  9753. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  9754. /**
  9755. * TSL object that represents the object's inverse world matrix.
  9756. *
  9757. * @tsl
  9758. * @type {UniformNode<mat4>}
  9759. */
  9760. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  9761. /**
  9762. * TSL object that represents the object's model view matrix.
  9763. *
  9764. * @tsl
  9765. * @type {Node<mat4>}
  9766. */
  9767. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9768. return builder.context.modelViewMatrix || mediumpModelViewMatrix;
  9769. } ).once() )().toVar( 'modelViewMatrix' );
  9770. // GPU Precision
  9771. /**
  9772. * TSL object that represents the object's model view in `mediump` precision.
  9773. *
  9774. * @tsl
  9775. * @type {Node<mat4>}
  9776. */
  9777. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  9778. // CPU Precision
  9779. /**
  9780. * TSL object that represents the object's model view in `highp` precision
  9781. * which is achieved by computing the matrix in JS and not in the shader.
  9782. *
  9783. * @tsl
  9784. * @type {Node<mat4>}
  9785. */
  9786. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9787. builder.context.isHighPrecisionModelViewMatrix = true;
  9788. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  9789. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9790. } );
  9791. } ).once() )().toVar( 'highpModelViewMatrix' );
  9792. /**
  9793. * TSL object that represents the object's model normal view in `highp` precision
  9794. * which is achieved by computing the matrix in JS and not in the shader.
  9795. *
  9796. * @tsl
  9797. * @type {Node<mat3>}
  9798. */
  9799. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9800. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  9801. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  9802. if ( isHighPrecisionModelViewMatrix !== true ) {
  9803. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9804. }
  9805. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  9806. } );
  9807. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  9808. /**
  9809. * TSL object that represents the position attribute of the current rendered object.
  9810. *
  9811. * @tsl
  9812. * @type {AttributeNode<vec3>}
  9813. */
  9814. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  9815. /**
  9816. * TSL object that represents the vertex position in local space of the current rendered object.
  9817. *
  9818. * @tsl
  9819. * @type {AttributeNode<vec3>}
  9820. */
  9821. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  9822. /**
  9823. * TSL object that represents the previous vertex position in local space of the current rendered object.
  9824. * Used in context of {@link VelocityNode} for rendering motion vectors.
  9825. *
  9826. * @tsl
  9827. * @type {AttributeNode<vec3>}
  9828. */
  9829. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  9830. /**
  9831. * TSL object that represents the vertex position in world space of the current rendered object.
  9832. *
  9833. * @tsl
  9834. * @type {VaryingNode<vec3>}
  9835. */
  9836. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  9837. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  9838. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9839. /**
  9840. * TSL object that represents the position world direction of the current rendered object.
  9841. *
  9842. * @tsl
  9843. * @type {Node<vec3>}
  9844. */
  9845. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  9846. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  9847. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  9848. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9849. /**
  9850. * TSL object that represents the vertex position in view space of the current rendered object.
  9851. *
  9852. * @tsl
  9853. * @type {VaryingNode<vec3>}
  9854. */
  9855. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  9856. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  9857. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9858. /**
  9859. * TSL object that represents the position view direction of the current rendered object.
  9860. *
  9861. * @tsl
  9862. * @type {VaryingNode<vec3>}
  9863. */
  9864. const positionViewDirection = /*@__PURE__*/ ( Fn( ( builder ) => {
  9865. let output;
  9866. if ( builder.camera.isOrthographicCamera ) {
  9867. output = vec3( 0, 0, 1 );
  9868. } else {
  9869. output = positionView.negate().toVarying( 'v_positionViewDirection' ).normalize();
  9870. }
  9871. return output.toVar( 'positionViewDirection' );
  9872. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9873. /**
  9874. * This node can be used to evaluate whether a primitive is front or back facing.
  9875. *
  9876. * @augments Node
  9877. */
  9878. class FrontFacingNode extends Node {
  9879. static get type() {
  9880. return 'FrontFacingNode';
  9881. }
  9882. /**
  9883. * Constructs a new front facing node.
  9884. */
  9885. constructor() {
  9886. super( 'bool' );
  9887. /**
  9888. * This flag can be used for type testing.
  9889. *
  9890. * @type {boolean}
  9891. * @readonly
  9892. * @default true
  9893. */
  9894. this.isFrontFacingNode = true;
  9895. }
  9896. generate( builder ) {
  9897. if ( builder.shaderStage !== 'fragment' ) return 'true';
  9898. //
  9899. const { material } = builder;
  9900. if ( material.side === BackSide ) {
  9901. return 'false';
  9902. }
  9903. return builder.getFrontFacing();
  9904. }
  9905. }
  9906. /**
  9907. * TSL object that represents whether a primitive is front or back facing
  9908. *
  9909. * @tsl
  9910. * @type {FrontFacingNode<bool>}
  9911. */
  9912. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  9913. /**
  9914. * TSL object that represents the front facing status as a number instead of a bool.
  9915. * `1` means front facing, `-1` means back facing.
  9916. *
  9917. * @tsl
  9918. * @type {Node<float>}
  9919. */
  9920. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  9921. /**
  9922. * Converts a direction vector to a face direction vector based on the material's side.
  9923. *
  9924. * If the material is set to `BackSide`, the direction is inverted.
  9925. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  9926. *
  9927. * @tsl
  9928. * @param {Node<vec3>} direction - The direction vector to convert.
  9929. * @returns {Node<vec3>} The converted direction vector.
  9930. */
  9931. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  9932. const side = material.side;
  9933. if ( side === BackSide ) {
  9934. direction = direction.mul( -1 );
  9935. } else if ( side === DoubleSide ) {
  9936. direction = direction.mul( faceDirection );
  9937. }
  9938. return direction;
  9939. } );
  9940. /**
  9941. * TSL object that represents the normal attribute of the current rendered object in local space.
  9942. *
  9943. * @tsl
  9944. * @type {Node<vec3>}
  9945. */
  9946. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  9947. /**
  9948. * TSL object that represents the vertex normal of the current rendered object in local space.
  9949. *
  9950. * @tsl
  9951. * @type {Node<vec3>}
  9952. */
  9953. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  9954. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  9955. warn( 'TSL: Vertex attribute "normal" not found on geometry.' );
  9956. return vec3( 0, 1, 0 );
  9957. }
  9958. return normalGeometry;
  9959. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  9960. /**
  9961. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  9962. *
  9963. * @tsl
  9964. * @type {Node<vec3>}
  9965. */
  9966. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  9967. /**
  9968. * TSL object that represents the vertex normal of the current rendered object in view space.
  9969. *
  9970. * @tsl
  9971. * @type {Node<vec3>}
  9972. */
  9973. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9974. let node;
  9975. if ( builder.material.flatShading === true ) {
  9976. node = normalFlat;
  9977. } else {
  9978. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  9979. }
  9980. return node;
  9981. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  9982. /**
  9983. * TSL object that represents the vertex normal of the current rendered object in world space.
  9984. *
  9985. * @tsl
  9986. * @type {Node<vec3>}
  9987. */
  9988. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9989. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  9990. if ( builder.material.flatShading !== true ) {
  9991. normal = normal.toVarying( 'v_normalWorldGeometry' );
  9992. }
  9993. return normal.normalize().toVar( 'normalWorldGeometry' );
  9994. }, 'vec3' ).once() )();
  9995. /**
  9996. * TSL object that represents the vertex normal of the current rendered object in view space.
  9997. *
  9998. * @tsl
  9999. * @type {Node<vec3>}
  10000. */
  10001. const normalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, material, context } ) => {
  10002. let node;
  10003. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  10004. node = normalViewGeometry;
  10005. if ( material.flatShading !== true ) {
  10006. node = directionToFaceDirection( node );
  10007. }
  10008. } else {
  10009. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  10010. node = context.setupNormal().context( { getUV: null } );
  10011. }
  10012. return node;
  10013. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  10014. /**
  10015. * TSL object that represents the vertex normal of the current rendered object in world space.
  10016. *
  10017. * @tsl
  10018. * @type {Node<vec3>}
  10019. */
  10020. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  10021. /**
  10022. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  10023. *
  10024. * @tsl
  10025. * @type {Node<vec3>}
  10026. */
  10027. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  10028. let node;
  10029. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  10030. node = normalView;
  10031. } else {
  10032. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  10033. node = context.setupClearcoatNormal().context( { getUV: null } );
  10034. }
  10035. return node;
  10036. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  10037. /**
  10038. * Transforms the normal with the given matrix.
  10039. *
  10040. * @tsl
  10041. * @function
  10042. * @param {Node<vec3>} normal - The normal.
  10043. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  10044. * @return {Node<vec3>} The transformed normal.
  10045. */
  10046. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  10047. const m = mat3( matrix );
  10048. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  10049. return m.mul( transformedNormal ).xyz;
  10050. } );
  10051. /**
  10052. * Transforms the given normal from local to view space.
  10053. *
  10054. * @tsl
  10055. * @function
  10056. * @param {Node<vec3>} normal - The normal.
  10057. * @param {NodeBuilder} builder - The current node builder.
  10058. * @return {Node<vec3>} The transformed normal.
  10059. */
  10060. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  10061. const modelNormalViewMatrix = builder.context.modelNormalViewMatrix;
  10062. if ( modelNormalViewMatrix ) {
  10063. return modelNormalViewMatrix.transformDirection( normal );
  10064. }
  10065. //
  10066. const transformedNormal = modelNormalMatrix.mul( normal );
  10067. return cameraViewMatrix.transformDirection( transformedNormal );
  10068. } );
  10069. // Deprecated
  10070. /**
  10071. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  10072. *
  10073. * @tsl
  10074. * @type {Node<vec3>}
  10075. * @deprecated since r178. Use `normalView` instead.
  10076. */
  10077. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  10078. warn( 'TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  10079. return normalView;
  10080. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10081. /**
  10082. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  10083. *
  10084. * @tsl
  10085. * @type {Node<vec3>}
  10086. * @deprecated since r178. Use `normalWorld` instead.
  10087. */
  10088. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  10089. warn( 'TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  10090. return normalWorld;
  10091. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10092. /**
  10093. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  10094. *
  10095. * @tsl
  10096. * @type {Node<vec3>}
  10097. * @deprecated since r178. Use `clearcoatNormalView` instead.
  10098. */
  10099. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  10100. warn( 'TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  10101. return clearcoatNormalView;
  10102. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10103. const _e1$1 = /*@__PURE__*/ new Euler();
  10104. const _m1$1 = /*@__PURE__*/ new Matrix4();
  10105. /**
  10106. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  10107. *
  10108. * @tsl
  10109. * @type {UniformNode<float>}
  10110. */
  10111. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  10112. /**
  10113. * TSL object that represents the intensity of environment maps of PBR materials.
  10114. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  10115. *
  10116. * @tsl
  10117. * @type {Node<float>}
  10118. */
  10119. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  10120. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  10121. } );
  10122. /**
  10123. * TSL object that represents the rotation of environment maps.
  10124. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  10125. * rotation of `scene.environment` instead.
  10126. *
  10127. * @tsl
  10128. * @type {Node<mat4>}
  10129. */
  10130. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  10131. return frame.material;
  10132. } ).onObjectUpdate( function ( { material, scene } ) {
  10133. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  10134. if ( rotation ) {
  10135. _e1$1.copy( rotation );
  10136. _m1$1.makeRotationFromEuler( _e1$1 );
  10137. } else {
  10138. _m1$1.identity();
  10139. }
  10140. return _m1$1;
  10141. } );
  10142. /**
  10143. * The reflect vector in view space.
  10144. *
  10145. * @tsl
  10146. * @type {Node<vec3>}
  10147. */
  10148. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  10149. /**
  10150. * The refract vector in view space.
  10151. *
  10152. * @tsl
  10153. * @type {Node<vec3>}
  10154. */
  10155. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  10156. /**
  10157. * Used for sampling cube maps when using cube reflection mapping.
  10158. *
  10159. * @tsl
  10160. * @type {Node<vec3>}
  10161. */
  10162. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10163. /**
  10164. * Used for sampling cube maps when using cube refraction mapping.
  10165. *
  10166. * @tsl
  10167. * @type {Node<vec3>}
  10168. */
  10169. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10170. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  10171. /**
  10172. * This type of uniform node represents a cube texture.
  10173. *
  10174. * @augments TextureNode
  10175. */
  10176. class CubeTextureNode extends TextureNode {
  10177. static get type() {
  10178. return 'CubeTextureNode';
  10179. }
  10180. /**
  10181. * Constructs a new cube texture node.
  10182. *
  10183. * @param {CubeTexture} value - The cube texture.
  10184. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10185. * @param {?Node<int>} [levelNode=null] - The level node.
  10186. * @param {?Node<float>} [biasNode=null] - The bias node.
  10187. */
  10188. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  10189. super( value, uvNode, levelNode, biasNode );
  10190. /**
  10191. * This flag can be used for type testing.
  10192. *
  10193. * @type {boolean}
  10194. * @readonly
  10195. * @default true
  10196. */
  10197. this.isCubeTextureNode = true;
  10198. }
  10199. /**
  10200. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  10201. *
  10202. * @param {NodeBuilder} builder - The current node builder.
  10203. * @return {string} The input type.
  10204. */
  10205. getInputType( /*builder*/ ) {
  10206. return 'cubeTexture';
  10207. }
  10208. /**
  10209. * Returns a default uvs based on the mapping type of the cube texture.
  10210. *
  10211. * @return {Node<vec3>} The default uv attribute.
  10212. */
  10213. getDefaultUV() {
  10214. const texture = this.value;
  10215. if ( texture.mapping === CubeReflectionMapping ) {
  10216. return reflectVector;
  10217. } else if ( texture.mapping === CubeRefractionMapping ) {
  10218. return refractVector;
  10219. } else {
  10220. error( 'CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  10221. return vec3( 0, 0, 0 );
  10222. }
  10223. }
  10224. /**
  10225. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  10226. * for cube textures. The uv transformation matrix is not applied to cube textures.
  10227. *
  10228. * @param {boolean} value - The update toggle.
  10229. */
  10230. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  10231. /**
  10232. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  10233. * to modify the uv node for correct sampling.
  10234. *
  10235. * @param {NodeBuilder} builder - The current node builder.
  10236. * @param {Node} uvNode - The uv node to setup.
  10237. * @return {Node} The updated uv node.
  10238. */
  10239. setupUV( builder, uvNode ) {
  10240. const texture = this.value;
  10241. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  10242. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  10243. }
  10244. return materialEnvRotation.mul( uvNode );
  10245. }
  10246. /**
  10247. * Generates the uv code snippet.
  10248. *
  10249. * @param {NodeBuilder} builder - The current node builder.
  10250. * @param {Node} cubeUV - The uv node to generate code for.
  10251. * @return {string} The generated code snippet.
  10252. */
  10253. generateUV( builder, cubeUV ) {
  10254. return cubeUV.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  10255. }
  10256. }
  10257. /**
  10258. * TSL function for creating a cube texture node.
  10259. *
  10260. * @tsl
  10261. * @function
  10262. * @param {CubeTexture} value - The cube texture.
  10263. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10264. * @param {?Node<int>} [levelNode=null] - The level node.
  10265. * @param {?Node<float>} [biasNode=null] - The bias node.
  10266. * @returns {CubeTextureNode}
  10267. */
  10268. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  10269. /**
  10270. * TSL function for creating a cube texture uniform node.
  10271. *
  10272. * @tsl
  10273. * @function
  10274. * @param {?(CubeTexture|CubeTextureNode)} [value=EmptyTexture] - The cube texture.
  10275. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10276. * @param {?Node<int>} [levelNode=null] - The level node.
  10277. * @param {?Node<float>} [biasNode=null] - The bias node.
  10278. * @returns {CubeTextureNode}
  10279. */
  10280. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  10281. let textureNode;
  10282. if ( value && value.isCubeTextureNode === true ) {
  10283. textureNode = nodeObject( value.clone() );
  10284. textureNode.referenceNode = value; // Ensure the reference is set to the original node
  10285. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  10286. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  10287. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  10288. } else {
  10289. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  10290. }
  10291. return textureNode;
  10292. };
  10293. /**
  10294. * TSL function for creating a uniform cube texture node.
  10295. *
  10296. * @tsl
  10297. * @function
  10298. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  10299. * @returns {CubeTextureNode}
  10300. */
  10301. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  10302. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  10303. /**
  10304. * This class is only relevant if the referenced property is array-like.
  10305. * In this case, `ReferenceElementNode` allows to refer to a specific
  10306. * element inside the data structure via an index.
  10307. *
  10308. * @augments ArrayElementNode
  10309. */
  10310. class ReferenceElementNode extends ArrayElementNode {
  10311. static get type() {
  10312. return 'ReferenceElementNode';
  10313. }
  10314. /**
  10315. * Constructs a new reference element node.
  10316. *
  10317. * @param {?ReferenceNode} referenceNode - The reference node.
  10318. * @param {Node} indexNode - The index node that defines the element access.
  10319. */
  10320. constructor( referenceNode, indexNode ) {
  10321. super( referenceNode, indexNode );
  10322. /**
  10323. * Similar to {@link ReferenceNode#reference}, an additional
  10324. * property references to the current node.
  10325. *
  10326. * @type {?ReferenceNode}
  10327. * @default null
  10328. */
  10329. this.referenceNode = referenceNode;
  10330. /**
  10331. * This flag can be used for type testing.
  10332. *
  10333. * @type {boolean}
  10334. * @readonly
  10335. * @default true
  10336. */
  10337. this.isReferenceElementNode = true;
  10338. }
  10339. /**
  10340. * This method is overwritten since the node type is inferred from
  10341. * the uniform type of the reference node.
  10342. *
  10343. * @return {string} The node type.
  10344. */
  10345. getNodeType() {
  10346. return this.referenceNode.uniformType;
  10347. }
  10348. generate( builder ) {
  10349. const snippet = super.generate( builder );
  10350. const arrayType = this.referenceNode.getNodeType();
  10351. const elementType = this.getNodeType();
  10352. return builder.format( snippet, arrayType, elementType );
  10353. }
  10354. }
  10355. /**
  10356. * This type of node establishes a reference to a property of another object.
  10357. * In this way, the value of the node is automatically linked to the value of
  10358. * referenced object. Reference nodes internally represent the linked value
  10359. * as a uniform.
  10360. *
  10361. * @augments Node
  10362. */
  10363. class ReferenceNode extends Node {
  10364. static get type() {
  10365. return 'ReferenceNode';
  10366. }
  10367. /**
  10368. * Constructs a new reference node.
  10369. *
  10370. * @param {string} property - The name of the property the node refers to.
  10371. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  10372. * @param {?Object} [object=null] - The object the property belongs to.
  10373. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  10374. */
  10375. constructor( property, uniformType, object = null, count = null ) {
  10376. super();
  10377. /**
  10378. * The name of the property the node refers to.
  10379. *
  10380. * @type {string}
  10381. */
  10382. this.property = property;
  10383. /**
  10384. * The uniform type that should be used to represent the property value.
  10385. *
  10386. * @type {string}
  10387. */
  10388. this.uniformType = uniformType;
  10389. /**
  10390. * The object the property belongs to.
  10391. *
  10392. * @type {?Object}
  10393. * @default null
  10394. */
  10395. this.object = object;
  10396. /**
  10397. * When the linked property is an array, this parameter defines its length.
  10398. *
  10399. * @type {?number}
  10400. * @default null
  10401. */
  10402. this.count = count;
  10403. /**
  10404. * The property name might have dots so nested properties can be referred.
  10405. * The hierarchy of the names is stored inside this array.
  10406. *
  10407. * @type {Array<string>}
  10408. */
  10409. this.properties = property.split( '.' );
  10410. /**
  10411. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  10412. * since the final reference might be updated from calling code.
  10413. *
  10414. * @type {?Object}
  10415. * @default null
  10416. */
  10417. this.reference = object;
  10418. /**
  10419. * The uniform node that holds the value of the reference node.
  10420. *
  10421. * @type {UniformNode}
  10422. * @default null
  10423. */
  10424. this.node = null;
  10425. /**
  10426. * The uniform group of the internal uniform.
  10427. *
  10428. * @type {UniformGroupNode}
  10429. * @default null
  10430. */
  10431. this.group = null;
  10432. /**
  10433. * An optional label of the internal uniform node.
  10434. *
  10435. * @type {?string}
  10436. * @default null
  10437. */
  10438. this.name = null;
  10439. /**
  10440. * Overwritten since reference nodes are updated per object.
  10441. *
  10442. * @type {string}
  10443. * @default 'object'
  10444. */
  10445. this.updateType = NodeUpdateType.OBJECT;
  10446. }
  10447. /**
  10448. * When the referred property is array-like, this method can be used
  10449. * to access elements via an index node.
  10450. *
  10451. * @param {IndexNode} indexNode - indexNode.
  10452. * @return {ReferenceElementNode} A reference to an element.
  10453. */
  10454. element( indexNode ) {
  10455. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  10456. }
  10457. /**
  10458. * Sets the uniform group for this reference node.
  10459. *
  10460. * @param {UniformGroupNode} group - The uniform group to set.
  10461. * @return {ReferenceNode} A reference to this node.
  10462. */
  10463. setGroup( group ) {
  10464. this.group = group;
  10465. return this;
  10466. }
  10467. /**
  10468. * Sets the name for the internal uniform.
  10469. *
  10470. * @param {string} name - The label to set.
  10471. * @return {ReferenceNode} A reference to this node.
  10472. */
  10473. setName( name ) {
  10474. this.name = name;
  10475. return this;
  10476. }
  10477. /**
  10478. * Sets the label for the internal uniform.
  10479. *
  10480. * @deprecated
  10481. * @param {string} name - The label to set.
  10482. * @return {ReferenceNode} A reference to this node.
  10483. */
  10484. label( name ) {
  10485. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  10486. return this.setName( name );
  10487. }
  10488. /**
  10489. * Sets the node type which automatically defines the internal
  10490. * uniform type.
  10491. *
  10492. * @param {string} uniformType - The type to set.
  10493. */
  10494. setNodeType( uniformType ) {
  10495. let node = null;
  10496. if ( this.count !== null ) {
  10497. node = buffer( null, uniformType, this.count );
  10498. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  10499. node = uniformArray( null, uniformType );
  10500. } else if ( uniformType === 'texture' ) {
  10501. node = texture( null );
  10502. } else if ( uniformType === 'cubeTexture' ) {
  10503. node = cubeTexture( null );
  10504. } else {
  10505. node = uniform( null, uniformType );
  10506. }
  10507. if ( this.group !== null ) {
  10508. node.setGroup( this.group );
  10509. }
  10510. if ( this.name !== null ) node.setName( this.name );
  10511. this.node = node;
  10512. }
  10513. /**
  10514. * This method is overwritten since the node type is inferred from
  10515. * the type of the reference node.
  10516. *
  10517. * @param {NodeBuilder} builder - The current node builder.
  10518. * @return {string} The node type.
  10519. */
  10520. getNodeType( builder ) {
  10521. if ( this.node === null ) {
  10522. this.updateReference( builder );
  10523. this.updateValue();
  10524. }
  10525. return this.node.getNodeType( builder );
  10526. }
  10527. /**
  10528. * Returns the property value from the given referred object.
  10529. *
  10530. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  10531. * @return {any} The value.
  10532. */
  10533. getValueFromReference( object = this.reference ) {
  10534. const { properties } = this;
  10535. let value = object[ properties[ 0 ] ];
  10536. for ( let i = 1; i < properties.length; i ++ ) {
  10537. value = value[ properties[ i ] ];
  10538. }
  10539. return value;
  10540. }
  10541. /**
  10542. * Allows to update the reference based on the given state. The state is only
  10543. * evaluated {@link ReferenceNode#object} is not set.
  10544. *
  10545. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10546. * @return {Object} The updated reference.
  10547. */
  10548. updateReference( state ) {
  10549. this.reference = this.object !== null ? this.object : state.object;
  10550. return this.reference;
  10551. }
  10552. /**
  10553. * The output of the reference node is the internal uniform node.
  10554. *
  10555. * @param {NodeBuilder} builder - The current node builder.
  10556. * @return {UniformNode} The output node.
  10557. */
  10558. setup( /* builder */ ) {
  10559. this.updateValue();
  10560. return this.node;
  10561. }
  10562. /**
  10563. * Overwritten to update the internal uniform value.
  10564. *
  10565. * @param {NodeFrame} frame - A reference to the current node frame.
  10566. */
  10567. update( /*frame*/ ) {
  10568. this.updateValue();
  10569. }
  10570. /**
  10571. * Retrieves the value from the referred object property and uses it
  10572. * to updated the internal uniform.
  10573. */
  10574. updateValue() {
  10575. if ( this.node === null ) this.setNodeType( this.uniformType );
  10576. const value = this.getValueFromReference();
  10577. if ( Array.isArray( value ) ) {
  10578. this.node.array = value;
  10579. } else {
  10580. this.node.value = value;
  10581. }
  10582. }
  10583. }
  10584. /**
  10585. * TSL function for creating a reference node.
  10586. *
  10587. * @tsl
  10588. * @function
  10589. * @param {string} name - The name of the property the node refers to.
  10590. * @param {string} type - The uniform type that should be used to represent the property value.
  10591. * @param {?Object} [object] - The object the property belongs to.
  10592. * @returns {ReferenceNode}
  10593. */
  10594. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  10595. /**
  10596. * TSL function for creating a reference node. Use this function if you want need a reference
  10597. * to an array-like property that should be represented as a uniform buffer.
  10598. *
  10599. * @tsl
  10600. * @function
  10601. * @param {string} name - The name of the property the node refers to.
  10602. * @param {string} type - The uniform type that should be used to represent the property value.
  10603. * @param {number} count - The number of value inside the array-like object.
  10604. * @param {Object} object - An array-like object the property belongs to.
  10605. * @returns {ReferenceNode}
  10606. */
  10607. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  10608. /**
  10609. * This node is a special type of reference node which is intended
  10610. * for linking material properties with node values.
  10611. * ```js
  10612. * const opacityNode = materialReference( 'opacity', 'float', material );
  10613. * ```
  10614. * When changing `material.opacity`, the node value of `opacityNode` will
  10615. * automatically be updated.
  10616. *
  10617. * @augments ReferenceNode
  10618. */
  10619. class MaterialReferenceNode extends ReferenceNode {
  10620. static get type() {
  10621. return 'MaterialReferenceNode';
  10622. }
  10623. /**
  10624. * Constructs a new material reference node.
  10625. *
  10626. * @param {string} property - The name of the property the node refers to.
  10627. * @param {string} inputType - The uniform type that should be used to represent the property value.
  10628. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  10629. * the node refers to the material of the current rendered object.
  10630. */
  10631. constructor( property, inputType, material = null ) {
  10632. super( property, inputType, material );
  10633. /**
  10634. * The material the property belongs to. When no material is set,
  10635. * the node refers to the material of the current rendered object.
  10636. *
  10637. * @type {?Material}
  10638. * @default null
  10639. */
  10640. this.material = material;
  10641. /**
  10642. * This flag can be used for type testing.
  10643. *
  10644. * @type {boolean}
  10645. * @readonly
  10646. * @default true
  10647. */
  10648. this.isMaterialReferenceNode = true;
  10649. }
  10650. /**
  10651. * Updates the reference based on the given state. The state is only evaluated
  10652. * {@link MaterialReferenceNode#material} is not set.
  10653. *
  10654. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10655. * @return {Object} The updated reference.
  10656. */
  10657. updateReference( state ) {
  10658. this.reference = this.material !== null ? this.material : state.material;
  10659. return this.reference;
  10660. }
  10661. }
  10662. /**
  10663. * TSL function for creating a material reference node.
  10664. *
  10665. * @tsl
  10666. * @function
  10667. * @param {string} name - The name of the property the node refers to.
  10668. * @param {string} type - The uniform type that should be used to represent the property value.
  10669. * @param {?Material} [material=null] - The material the property belongs to.
  10670. * When no material is set, the node refers to the material of the current rendered object.
  10671. * @returns {MaterialReferenceNode}
  10672. */
  10673. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  10674. // Normal Mapping Without Precomputed Tangents
  10675. // http://www.thetenthplanet.de/archives/1180
  10676. const uv = uv$1();
  10677. const q0 = positionView.dFdx();
  10678. const q1 = positionView.dFdy();
  10679. const st0 = uv.dFdx();
  10680. const st1 = uv.dFdy();
  10681. const N = normalView;
  10682. const q1perp = q1.cross( N );
  10683. const q0perp = N.cross( q0 );
  10684. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  10685. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  10686. const det = T.dot( T ).max( B.dot( B ) );
  10687. const scale$1 = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  10688. /**
  10689. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  10690. * Useful for normal mapping without precomputed tangents.
  10691. *
  10692. * Reference: http://www.thetenthplanet.de/archives/1180
  10693. *
  10694. * @tsl
  10695. * @type {Node<vec3>}
  10696. */
  10697. const tangentViewFrame = /*@__PURE__*/ T.mul( scale$1 ).toVar( 'tangentViewFrame' );
  10698. /**
  10699. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  10700. * Complements the tangentViewFrame for constructing the tangent space basis.
  10701. *
  10702. * Reference: http://www.thetenthplanet.de/archives/1180
  10703. *
  10704. * @tsl
  10705. * @type {Node<vec3>}
  10706. */
  10707. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale$1 ).toVar( 'bitangentViewFrame' );
  10708. /**
  10709. * TSL object that represents the tangent attribute of the current rendered object.
  10710. *
  10711. * @tsl
  10712. * @type {Node<vec4>}
  10713. */
  10714. const tangentGeometry = /*@__PURE__*/ attribute( 'tangent', 'vec4' );
  10715. /**
  10716. * TSL object that represents the vertex tangent in local space of the current rendered object.
  10717. *
  10718. * @tsl
  10719. * @type {Node<vec3>}
  10720. */
  10721. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  10722. /**
  10723. * TSL object that represents the vertex tangent in view space of the current rendered object.
  10724. *
  10725. * @tsl
  10726. * @type {Node<vec3>}
  10727. */
  10728. const tangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10729. let node;
  10730. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10731. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  10732. } else {
  10733. node = tangentViewFrame;
  10734. }
  10735. if ( material.flatShading !== true ) {
  10736. node = directionToFaceDirection( node );
  10737. }
  10738. return node;
  10739. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  10740. /**
  10741. * TSL object that represents the vertex tangent in world space of the current rendered object.
  10742. *
  10743. * @tsl
  10744. * @type {Node<vec3>}
  10745. */
  10746. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  10747. /**
  10748. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  10749. *
  10750. * @tsl
  10751. * @private
  10752. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  10753. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  10754. * @returns {Node<vec3>} The bitangent node.
  10755. */
  10756. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], { subBuildFn, material } ) => {
  10757. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  10758. if ( subBuildFn === 'NORMAL' && material.flatShading !== true ) {
  10759. bitangent = bitangent.toVarying( varyingName );
  10760. }
  10761. return bitangent;
  10762. } ).once( [ 'NORMAL' ] );
  10763. /**
  10764. * TSL object that represents the bitangent attribute of the current rendered object.
  10765. *
  10766. * @tsl
  10767. * @type {Node<vec3>}
  10768. */
  10769. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  10770. /**
  10771. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  10772. *
  10773. * @tsl
  10774. * @type {Node<vec3>}
  10775. */
  10776. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  10777. /**
  10778. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  10779. *
  10780. * @tsl
  10781. * @type {Node<vec3>}
  10782. */
  10783. const bitangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10784. let node;
  10785. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10786. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  10787. } else {
  10788. node = bitangentViewFrame;
  10789. }
  10790. if ( material.flatShading !== true ) {
  10791. node = directionToFaceDirection( node );
  10792. }
  10793. return node;
  10794. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  10795. /**
  10796. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  10797. *
  10798. * @tsl
  10799. * @type {Node<vec3>}
  10800. */
  10801. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  10802. /**
  10803. * TSL object that represents the TBN matrix in view space.
  10804. *
  10805. * @tsl
  10806. * @type {Node<mat3>}
  10807. */
  10808. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  10809. /**
  10810. * TSL object that represents the parallax direction.
  10811. *
  10812. * @tsl
  10813. * @type {Node<mat3>}
  10814. */
  10815. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  10816. /**
  10817. * TSL function for computing parallax uv coordinates.
  10818. *
  10819. * @tsl
  10820. * @function
  10821. * @param {Node<vec2>} uv - A uv node.
  10822. * @param {Node<vec2>} scale - A scale node.
  10823. * @returns {Node<vec2>} Parallax uv coordinates.
  10824. */
  10825. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  10826. /**
  10827. * TSL function for computing bent normals.
  10828. *
  10829. * @tsl
  10830. * @function
  10831. * @returns {Node<vec3>} Bent normals.
  10832. */
  10833. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  10834. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  10835. let bentNormal = anisotropyB.cross( positionViewDirection );
  10836. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  10837. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  10838. return bentNormal;
  10839. } ).once() )();
  10840. /**
  10841. * Packs a direction vector into a color value.
  10842. *
  10843. * @tsl
  10844. * @function
  10845. * @param {Node<vec3>} node - The direction to pack.
  10846. * @return {Node<vec3>} The color.
  10847. */
  10848. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  10849. /**
  10850. * Unpacks a color value into a direction vector.
  10851. *
  10852. * @tsl
  10853. * @function
  10854. * @param {Node<vec3>} node - The color to unpack.
  10855. * @return {Node<vec3>} The direction.
  10856. */
  10857. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  10858. /**
  10859. * Unpacks a tangent space normal, reconstructing the Z component by projecting the X,Y coordinates onto the hemisphere.
  10860. * The X,Y coordinates are expected to be in the [-1, 1] range.
  10861. *
  10862. * @tsl
  10863. * @function
  10864. * @param {Node<vec2>} xy - The X,Y coordinates of the normal.
  10865. * @return {Node<vec3>} The resulting normal.
  10866. */
  10867. const unpackNormal = ( xy ) => vec3( xy, sqrt( saturate( float( 1.0 ).sub( dot( xy, xy ) ) ) ) );
  10868. /**
  10869. * This class can be used for applying normals maps to materials.
  10870. *
  10871. * ```js
  10872. * material.normalNode = normalMap( texture( normalTex ) );
  10873. * ```
  10874. *
  10875. * @augments TempNode
  10876. */
  10877. class NormalMapNode extends TempNode {
  10878. static get type() {
  10879. return 'NormalMapNode';
  10880. }
  10881. /**
  10882. * Constructs a new normal map node.
  10883. *
  10884. * @param {Node<vec3>} node - Represents the normal map data.
  10885. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10886. */
  10887. constructor( node, scaleNode = null ) {
  10888. super( 'vec3' );
  10889. /**
  10890. * Represents the normal map data.
  10891. *
  10892. * @type {Node<vec3>}
  10893. */
  10894. this.node = node;
  10895. /**
  10896. * Controls the intensity of the effect.
  10897. *
  10898. * @type {?Node<vec2>}
  10899. * @default null
  10900. */
  10901. this.scaleNode = scaleNode;
  10902. /**
  10903. * The normal map type.
  10904. *
  10905. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  10906. * @default TangentSpaceNormalMap
  10907. */
  10908. this.normalMapType = TangentSpaceNormalMap;
  10909. /**
  10910. * Controls how to unpack the sampled normal map values.
  10911. *
  10912. * @type {string}
  10913. * @default NoNormalPacking
  10914. */
  10915. this.unpackNormalMode = NoNormalPacking;
  10916. }
  10917. setup( { material } ) {
  10918. const { normalMapType, scaleNode, unpackNormalMode } = this;
  10919. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  10920. if ( normalMapType === TangentSpaceNormalMap ) {
  10921. if ( unpackNormalMode === NormalRGPacking ) {
  10922. normalMap = unpackNormal( normalMap.xy );
  10923. } else if ( unpackNormalMode === NormalGAPacking ) {
  10924. normalMap = unpackNormal( normalMap.yw );
  10925. } else if ( unpackNormalMode !== NoNormalPacking ) {
  10926. console.error( `THREE.NodeMaterial: Unexpected unpack normal mode: ${ unpackNormalMode }` );
  10927. }
  10928. } else {
  10929. if ( unpackNormalMode !== NoNormalPacking ) {
  10930. console.error( `THREE.NodeMaterial: Normal map type '${ normalMapType }' is not compatible with unpack normal mode '${ unpackNormalMode }'` );
  10931. }
  10932. }
  10933. if ( scaleNode !== null ) {
  10934. let scale = scaleNode;
  10935. if ( material.flatShading === true ) {
  10936. scale = directionToFaceDirection( scale );
  10937. }
  10938. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  10939. }
  10940. let output = null;
  10941. if ( normalMapType === ObjectSpaceNormalMap ) {
  10942. output = transformNormalToView( normalMap );
  10943. } else if ( normalMapType === TangentSpaceNormalMap ) {
  10944. output = TBNViewMatrix.mul( normalMap ).normalize();
  10945. } else {
  10946. error( `NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  10947. output = normalView; // Fallback to default normal view
  10948. }
  10949. return output;
  10950. }
  10951. }
  10952. /**
  10953. * TSL function for creating a normal map node.
  10954. *
  10955. * @tsl
  10956. * @function
  10957. * @param {Node<vec3>} node - Represents the normal map data.
  10958. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10959. * @returns {NormalMapNode}
  10960. */
  10961. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  10962. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  10963. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  10964. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  10965. // It's used to preserve the same TextureNode instance
  10966. const sampleTexture = ( callback ) => textureNode.isolate().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  10967. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  10968. return vec2(
  10969. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  10970. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  10971. ).mul( bumpScale );
  10972. } );
  10973. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10974. const perturbNormalArb = Fn( ( inputs ) => {
  10975. const { surf_pos, surf_norm, dHdxy } = inputs;
  10976. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  10977. const vSigmaX = surf_pos.dFdx().normalize();
  10978. const vSigmaY = surf_pos.dFdy().normalize();
  10979. const vN = surf_norm; // normalized
  10980. const R1 = vSigmaY.cross( vN );
  10981. const R2 = vN.cross( vSigmaX );
  10982. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  10983. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  10984. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  10985. } );
  10986. /**
  10987. * This class can be used for applying bump maps to materials.
  10988. *
  10989. * ```js
  10990. * material.normalNode = bumpMap( texture( bumpTex ) );
  10991. * ```
  10992. *
  10993. * @augments TempNode
  10994. */
  10995. class BumpMapNode extends TempNode {
  10996. static get type() {
  10997. return 'BumpMapNode';
  10998. }
  10999. /**
  11000. * Constructs a new bump map node.
  11001. *
  11002. * @param {Node<float>} textureNode - Represents the bump map data.
  11003. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11004. */
  11005. constructor( textureNode, scaleNode = null ) {
  11006. super( 'vec3' );
  11007. /**
  11008. * Represents the bump map data.
  11009. *
  11010. * @type {Node<float>}
  11011. */
  11012. this.textureNode = textureNode;
  11013. /**
  11014. * Controls the intensity of the bump effect.
  11015. *
  11016. * @type {?Node<float>}
  11017. * @default null
  11018. */
  11019. this.scaleNode = scaleNode;
  11020. }
  11021. setup() {
  11022. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  11023. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  11024. return perturbNormalArb( {
  11025. surf_pos: positionView,
  11026. surf_norm: normalView,
  11027. dHdxy
  11028. } );
  11029. }
  11030. }
  11031. /**
  11032. * TSL function for creating a bump map node.
  11033. *
  11034. * @tsl
  11035. * @function
  11036. * @param {Node<float>} textureNode - Represents the bump map data.
  11037. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11038. * @returns {BumpMapNode}
  11039. */
  11040. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  11041. const _propertyCache = new Map();
  11042. /**
  11043. * This class should simplify the node access to material properties.
  11044. * It internal uses reference nodes to make sure changes to material
  11045. * properties are automatically reflected to predefined TSL objects
  11046. * like e.g. `materialColor`.
  11047. *
  11048. * @augments Node
  11049. */
  11050. class MaterialNode extends Node {
  11051. static get type() {
  11052. return 'MaterialNode';
  11053. }
  11054. /**
  11055. * Constructs a new material node.
  11056. *
  11057. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  11058. */
  11059. constructor( scope ) {
  11060. super();
  11061. /**
  11062. * The scope defines what material property is referred by the node.
  11063. *
  11064. * @type {string}
  11065. */
  11066. this.scope = scope;
  11067. }
  11068. /**
  11069. * Returns a cached reference node for the given property and type.
  11070. *
  11071. * @param {string} property - The name of the material property.
  11072. * @param {string} type - The uniform type of the property.
  11073. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11074. */
  11075. getCache( property, type ) {
  11076. let node = _propertyCache.get( property );
  11077. if ( node === undefined ) {
  11078. node = materialReference( property, type );
  11079. _propertyCache.set( property, node );
  11080. }
  11081. return node;
  11082. }
  11083. /**
  11084. * Returns a float-typed material reference node for the given property name.
  11085. *
  11086. * @param {string} property - The name of the material property.
  11087. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  11088. */
  11089. getFloat( property ) {
  11090. return this.getCache( property, 'float' );
  11091. }
  11092. /**
  11093. * Returns a color-typed material reference node for the given property name.
  11094. *
  11095. * @param {string} property - The name of the material property.
  11096. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  11097. */
  11098. getColor( property ) {
  11099. return this.getCache( property, 'color' );
  11100. }
  11101. /**
  11102. * Returns a texture-typed material reference node for the given property name.
  11103. *
  11104. * @param {string} property - The name of the material property.
  11105. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11106. */
  11107. getTexture( property ) {
  11108. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  11109. }
  11110. /**
  11111. * The node setup is done depending on the selected scope. Multiple material properties
  11112. * might be grouped into a single node composition if they logically belong together.
  11113. *
  11114. * @param {NodeBuilder} builder - The current node builder.
  11115. * @return {Node} The node representing the selected scope.
  11116. */
  11117. setup( builder ) {
  11118. const material = builder.context.material;
  11119. const scope = this.scope;
  11120. let node = null;
  11121. if ( scope === MaterialNode.COLOR ) {
  11122. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  11123. if ( material.map && material.map.isTexture === true ) {
  11124. node = colorNode.mul( this.getTexture( 'map' ) );
  11125. } else {
  11126. node = colorNode;
  11127. }
  11128. } else if ( scope === MaterialNode.OPACITY ) {
  11129. const opacityNode = this.getFloat( scope );
  11130. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  11131. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  11132. } else {
  11133. node = opacityNode;
  11134. }
  11135. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  11136. if ( material.specularMap && material.specularMap.isTexture === true ) {
  11137. node = this.getTexture( 'specular' ).r;
  11138. } else {
  11139. node = float( 1 );
  11140. }
  11141. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  11142. const specularIntensityNode = this.getFloat( scope );
  11143. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  11144. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  11145. } else {
  11146. node = specularIntensityNode;
  11147. }
  11148. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  11149. const specularColorNode = this.getColor( scope );
  11150. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  11151. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  11152. } else {
  11153. node = specularColorNode;
  11154. }
  11155. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  11156. const roughnessNode = this.getFloat( scope );
  11157. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  11158. node = roughnessNode.mul( this.getTexture( scope ).g );
  11159. } else {
  11160. node = roughnessNode;
  11161. }
  11162. } else if ( scope === MaterialNode.METALNESS ) {
  11163. const metalnessNode = this.getFloat( scope );
  11164. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  11165. node = metalnessNode.mul( this.getTexture( scope ).b );
  11166. } else {
  11167. node = metalnessNode;
  11168. }
  11169. } else if ( scope === MaterialNode.EMISSIVE ) {
  11170. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  11171. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  11172. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  11173. node = emissiveNode.mul( this.getTexture( scope ) );
  11174. } else {
  11175. node = emissiveNode;
  11176. }
  11177. } else if ( scope === MaterialNode.NORMAL ) {
  11178. if ( material.normalMap ) {
  11179. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  11180. node.normalMapType = material.normalMapType;
  11181. if ( material.normalMap.format == RGFormat || material.normalMap.format == RED_GREEN_RGTC2_Format || material.normalMap.format == RG11_EAC_Format ) {
  11182. node.unpackNormalMode = NormalRGPacking;
  11183. }
  11184. } else if ( material.bumpMap ) {
  11185. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  11186. } else {
  11187. node = normalView;
  11188. }
  11189. } else if ( scope === MaterialNode.CLEARCOAT ) {
  11190. const clearcoatNode = this.getFloat( scope );
  11191. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  11192. node = clearcoatNode.mul( this.getTexture( scope ).r );
  11193. } else {
  11194. node = clearcoatNode;
  11195. }
  11196. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  11197. const clearcoatRoughnessNode = this.getFloat( scope );
  11198. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  11199. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  11200. } else {
  11201. node = clearcoatRoughnessNode;
  11202. }
  11203. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  11204. if ( material.clearcoatNormalMap ) {
  11205. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  11206. } else {
  11207. node = normalView;
  11208. }
  11209. } else if ( scope === MaterialNode.SHEEN ) {
  11210. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  11211. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  11212. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  11213. } else {
  11214. node = sheenNode;
  11215. }
  11216. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  11217. const sheenRoughnessNode = this.getFloat( scope );
  11218. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  11219. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  11220. } else {
  11221. node = sheenRoughnessNode;
  11222. }
  11223. node = node.clamp( 0.07, 1.0 );
  11224. } else if ( scope === MaterialNode.ANISOTROPY ) {
  11225. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  11226. const anisotropyPolar = this.getTexture( scope );
  11227. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  11228. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  11229. } else {
  11230. node = materialAnisotropyVector;
  11231. }
  11232. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  11233. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  11234. if ( material.iridescenceThicknessMap ) {
  11235. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  11236. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  11237. } else {
  11238. node = iridescenceThicknessMaximum;
  11239. }
  11240. } else if ( scope === MaterialNode.TRANSMISSION ) {
  11241. const transmissionNode = this.getFloat( scope );
  11242. if ( material.transmissionMap ) {
  11243. node = transmissionNode.mul( this.getTexture( scope ).r );
  11244. } else {
  11245. node = transmissionNode;
  11246. }
  11247. } else if ( scope === MaterialNode.THICKNESS ) {
  11248. const thicknessNode = this.getFloat( scope );
  11249. if ( material.thicknessMap ) {
  11250. node = thicknessNode.mul( this.getTexture( scope ).g );
  11251. } else {
  11252. node = thicknessNode;
  11253. }
  11254. } else if ( scope === MaterialNode.IOR ) {
  11255. node = this.getFloat( scope );
  11256. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  11257. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  11258. } else if ( scope === MaterialNode.AO ) {
  11259. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  11260. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  11261. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  11262. } else {
  11263. const outputType = this.getNodeType( builder );
  11264. node = this.getCache( scope, outputType );
  11265. }
  11266. return node;
  11267. }
  11268. }
  11269. MaterialNode.ALPHA_TEST = 'alphaTest';
  11270. MaterialNode.COLOR = 'color';
  11271. MaterialNode.OPACITY = 'opacity';
  11272. MaterialNode.SHININESS = 'shininess';
  11273. MaterialNode.SPECULAR = 'specular';
  11274. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  11275. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  11276. MaterialNode.SPECULAR_COLOR = 'specularColor';
  11277. MaterialNode.REFLECTIVITY = 'reflectivity';
  11278. MaterialNode.ROUGHNESS = 'roughness';
  11279. MaterialNode.METALNESS = 'metalness';
  11280. MaterialNode.NORMAL = 'normal';
  11281. MaterialNode.CLEARCOAT = 'clearcoat';
  11282. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  11283. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  11284. MaterialNode.EMISSIVE = 'emissive';
  11285. MaterialNode.ROTATION = 'rotation';
  11286. MaterialNode.SHEEN = 'sheen';
  11287. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  11288. MaterialNode.ANISOTROPY = 'anisotropy';
  11289. MaterialNode.IRIDESCENCE = 'iridescence';
  11290. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  11291. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  11292. MaterialNode.IOR = 'ior';
  11293. MaterialNode.TRANSMISSION = 'transmission';
  11294. MaterialNode.THICKNESS = 'thickness';
  11295. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  11296. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  11297. MaterialNode.LINE_SCALE = 'scale';
  11298. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  11299. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  11300. MaterialNode.LINE_WIDTH = 'linewidth';
  11301. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  11302. MaterialNode.POINT_SIZE = 'size';
  11303. MaterialNode.DISPERSION = 'dispersion';
  11304. MaterialNode.LIGHT_MAP = 'light';
  11305. MaterialNode.AO = 'ao';
  11306. /**
  11307. * TSL object that represents alpha test of the current material.
  11308. *
  11309. * @tsl
  11310. * @type {Node<float>}
  11311. */
  11312. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  11313. /**
  11314. * TSL object that represents the diffuse color of the current material.
  11315. * The value is composed via `color` * `map`.
  11316. *
  11317. * @tsl
  11318. * @type {Node<vec3>}
  11319. */
  11320. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  11321. /**
  11322. * TSL object that represents the shininess of the current material.
  11323. *
  11324. * @tsl
  11325. * @type {Node<float>}
  11326. */
  11327. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  11328. /**
  11329. * TSL object that represents the emissive color of the current material.
  11330. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  11331. *
  11332. * @tsl
  11333. * @type {Node<vec3>}
  11334. */
  11335. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  11336. /**
  11337. * TSL object that represents the opacity of the current material.
  11338. * The value is composed via `opacity` * `alphaMap`.
  11339. *
  11340. * @tsl
  11341. * @type {Node<float>}
  11342. */
  11343. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  11344. /**
  11345. * TSL object that represents the specular of the current material.
  11346. *
  11347. * @tsl
  11348. * @type {Node<vec3>}
  11349. */
  11350. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  11351. /**
  11352. * TSL object that represents the specular intensity of the current material.
  11353. * The value is composed via `specularIntensity` * `specularMap.a`.
  11354. *
  11355. * @tsl
  11356. * @type {Node<float>}
  11357. */
  11358. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  11359. /**
  11360. * TSL object that represents the specular color of the current material.
  11361. * The value is composed via `specularColor` * `specularMap.rgb`.
  11362. *
  11363. * @tsl
  11364. * @type {Node<vec3>}
  11365. */
  11366. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  11367. /**
  11368. * TSL object that represents the specular strength of the current material.
  11369. * The value is composed via `specularMap.r`.
  11370. *
  11371. * @tsl
  11372. * @type {Node<float>}
  11373. */
  11374. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  11375. /**
  11376. * TSL object that represents the reflectivity of the current material.
  11377. *
  11378. * @tsl
  11379. * @type {Node<float>}
  11380. */
  11381. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  11382. /**
  11383. * TSL object that represents the roughness of the current material.
  11384. * The value is composed via `roughness` * `roughnessMap.g`.
  11385. *
  11386. * @tsl
  11387. * @type {Node<float>}
  11388. */
  11389. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  11390. /**
  11391. * TSL object that represents the metalness of the current material.
  11392. * The value is composed via `metalness` * `metalnessMap.b`.
  11393. *
  11394. * @tsl
  11395. * @type {Node<float>}
  11396. */
  11397. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  11398. /**
  11399. * TSL object that represents the normal of the current material.
  11400. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  11401. *
  11402. * @tsl
  11403. * @type {Node<vec3>}
  11404. */
  11405. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  11406. /**
  11407. * TSL object that represents the clearcoat of the current material.
  11408. * The value is composed via `clearcoat` * `clearcoatMap.r`
  11409. *
  11410. * @tsl
  11411. * @type {Node<float>}
  11412. */
  11413. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  11414. /**
  11415. * TSL object that represents the clearcoat roughness of the current material.
  11416. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  11417. *
  11418. * @tsl
  11419. * @type {Node<float>}
  11420. */
  11421. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  11422. /**
  11423. * TSL object that represents the clearcoat normal of the current material.
  11424. * The value will be either `clearcoatNormalMap` or `normalView`.
  11425. *
  11426. * @tsl
  11427. * @type {Node<vec3>}
  11428. */
  11429. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  11430. /**
  11431. * TSL object that represents the rotation of the current sprite material.
  11432. *
  11433. * @tsl
  11434. * @type {Node<float>}
  11435. */
  11436. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  11437. /**
  11438. * TSL object that represents the sheen color of the current material.
  11439. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  11440. *
  11441. * @tsl
  11442. * @type {Node<vec3>}
  11443. */
  11444. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  11445. /**
  11446. * TSL object that represents the sheen roughness of the current material.
  11447. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  11448. *
  11449. * @tsl
  11450. * @type {Node<float>}
  11451. */
  11452. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  11453. /**
  11454. * TSL object that represents the anisotropy of the current material.
  11455. *
  11456. * @tsl
  11457. * @type {Node<vec2>}
  11458. */
  11459. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  11460. /**
  11461. * TSL object that represents the iridescence of the current material.
  11462. *
  11463. * @tsl
  11464. * @type {Node<float>}
  11465. */
  11466. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  11467. /**
  11468. * TSL object that represents the iridescence IOR of the current material.
  11469. *
  11470. * @tsl
  11471. * @type {Node<float>}
  11472. */
  11473. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  11474. /**
  11475. * TSL object that represents the iridescence thickness of the current material.
  11476. *
  11477. * @tsl
  11478. * @type {Node<float>}
  11479. */
  11480. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  11481. /**
  11482. * TSL object that represents the transmission of the current material.
  11483. * The value is composed via `transmission` * `transmissionMap.r`.
  11484. *
  11485. * @tsl
  11486. * @type {Node<float>}
  11487. */
  11488. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  11489. /**
  11490. * TSL object that represents the thickness of the current material.
  11491. * The value is composed via `thickness` * `thicknessMap.g`.
  11492. *
  11493. * @tsl
  11494. * @type {Node<float>}
  11495. */
  11496. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  11497. /**
  11498. * TSL object that represents the IOR of the current material.
  11499. *
  11500. * @tsl
  11501. * @type {Node<float>}
  11502. */
  11503. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  11504. /**
  11505. * TSL object that represents the attenuation distance of the current material.
  11506. *
  11507. * @tsl
  11508. * @type {Node<float>}
  11509. */
  11510. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  11511. /**
  11512. * TSL object that represents the attenuation color of the current material.
  11513. *
  11514. * @tsl
  11515. * @type {Node<vec3>}
  11516. */
  11517. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  11518. /**
  11519. * TSL object that represents the scale of the current dashed line material.
  11520. *
  11521. * @tsl
  11522. * @type {Node<float>}
  11523. */
  11524. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  11525. /**
  11526. * TSL object that represents the dash size of the current dashed line material.
  11527. *
  11528. * @tsl
  11529. * @type {Node<float>}
  11530. */
  11531. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  11532. /**
  11533. * TSL object that represents the gap size of the current dashed line material.
  11534. *
  11535. * @tsl
  11536. * @type {Node<float>}
  11537. */
  11538. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  11539. /**
  11540. * TSL object that represents the line width of the current line material.
  11541. *
  11542. * @tsl
  11543. * @type {Node<float>}
  11544. */
  11545. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  11546. /**
  11547. * TSL object that represents the dash offset of the current line material.
  11548. *
  11549. * @tsl
  11550. * @type {Node<float>}
  11551. */
  11552. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  11553. /**
  11554. * TSL object that represents the point size of the current points material.
  11555. *
  11556. * @tsl
  11557. * @type {Node<float>}
  11558. */
  11559. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  11560. /**
  11561. * TSL object that represents the dispersion of the current material.
  11562. *
  11563. * @tsl
  11564. * @type {Node<float>}
  11565. */
  11566. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  11567. /**
  11568. * TSL object that represents the light map of the current material.
  11569. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  11570. *
  11571. * @tsl
  11572. * @type {Node<vec3>}
  11573. */
  11574. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  11575. /**
  11576. * TSL object that represents the ambient occlusion map of the current material.
  11577. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  11578. *
  11579. * @tsl
  11580. * @type {Node<float>}
  11581. */
  11582. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  11583. /**
  11584. * TSL object that represents the anisotropy vector of the current material.
  11585. *
  11586. * @tsl
  11587. * @type {Node<vec2>}
  11588. */
  11589. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  11590. return frame.material;
  11591. } ).onRenderUpdate( function ( { material } ) {
  11592. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  11593. } );
  11594. /**
  11595. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  11596. *
  11597. * @tsl
  11598. * @type {VaryingNode<vec4>}
  11599. */
  11600. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  11601. return builder.context.setupModelViewProjection();
  11602. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  11603. /**
  11604. * This class enables element access on instances of {@link StorageBufferNode}.
  11605. * In most cases, it is indirectly used when accessing elements with the
  11606. * {@link StorageBufferNode#element} method.
  11607. *
  11608. * ```js
  11609. * const position = positionStorage.element( instanceIndex );
  11610. * ```
  11611. *
  11612. * @augments ArrayElementNode
  11613. */
  11614. class StorageArrayElementNode extends ArrayElementNode {
  11615. static get type() {
  11616. return 'StorageArrayElementNode';
  11617. }
  11618. /**
  11619. * Constructs storage buffer element node.
  11620. *
  11621. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11622. * @param {Node} indexNode - The index node that defines the element access.
  11623. */
  11624. constructor( storageBufferNode, indexNode ) {
  11625. super( storageBufferNode, indexNode );
  11626. /**
  11627. * This flag can be used for type testing.
  11628. *
  11629. * @type {boolean}
  11630. * @readonly
  11631. * @default true
  11632. */
  11633. this.isStorageArrayElementNode = true;
  11634. }
  11635. /**
  11636. * The storage buffer node.
  11637. *
  11638. * @param {Node} value
  11639. * @type {StorageBufferNode}
  11640. */
  11641. set storageBufferNode( value ) {
  11642. this.node = value;
  11643. }
  11644. get storageBufferNode() {
  11645. return this.node;
  11646. }
  11647. getMemberType( builder, name ) {
  11648. const structTypeNode = this.storageBufferNode.structTypeNode;
  11649. if ( structTypeNode ) {
  11650. return structTypeNode.getMemberType( builder, name );
  11651. }
  11652. return 'void';
  11653. }
  11654. setup( builder ) {
  11655. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11656. if ( this.node.isPBO === true ) {
  11657. builder.setupPBO( this.node );
  11658. }
  11659. }
  11660. return super.setup( builder );
  11661. }
  11662. generate( builder, output ) {
  11663. let snippet;
  11664. const isAssignContext = builder.context.assign;
  11665. //
  11666. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11667. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  11668. snippet = builder.generatePBO( this );
  11669. } else {
  11670. snippet = this.node.build( builder );
  11671. }
  11672. } else {
  11673. snippet = super.generate( builder );
  11674. }
  11675. if ( isAssignContext !== true ) {
  11676. const type = this.getNodeType( builder );
  11677. snippet = builder.format( snippet, type, output );
  11678. }
  11679. return snippet;
  11680. }
  11681. }
  11682. /**
  11683. * TSL function for creating a storage element node.
  11684. *
  11685. * @tsl
  11686. * @function
  11687. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11688. * @param {Node} indexNode - The index node that defines the element access.
  11689. * @returns {StorageArrayElementNode}
  11690. */
  11691. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  11692. /**
  11693. * This node is used in context of compute shaders and allows to define a
  11694. * storage buffer for data. A typical workflow is to create instances of
  11695. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  11696. * setup up a compute shader that writes into the buffers and then convert
  11697. * the storage buffers to attribute nodes for rendering.
  11698. *
  11699. * ```js
  11700. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  11701. *
  11702. * const computeInit = Fn( () => { // the compute shader
  11703. *
  11704. * const position = positionBuffer.element( instanceIndex );
  11705. *
  11706. * // compute position data
  11707. *
  11708. * position.x = 1;
  11709. * position.y = 1;
  11710. * position.z = 1;
  11711. *
  11712. * } )().compute( particleCount );
  11713. *
  11714. * const particleMaterial = new THREE.SpriteNodeMaterial();
  11715. * particleMaterial.positionNode = positionBuffer.toAttribute();
  11716. *
  11717. * renderer.computeAsync( computeInit );
  11718. *
  11719. * ```
  11720. *
  11721. * @augments BufferNode
  11722. */
  11723. class StorageBufferNode extends BufferNode {
  11724. static get type() {
  11725. return 'StorageBufferNode';
  11726. }
  11727. /**
  11728. * Constructs a new storage buffer node.
  11729. *
  11730. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11731. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  11732. * @param {number} [bufferCount=0] - The buffer count.
  11733. */
  11734. constructor( value, bufferType = null, bufferCount = 0 ) {
  11735. let nodeType, structTypeNode = null;
  11736. if ( bufferType && bufferType.isStruct ) {
  11737. nodeType = 'struct';
  11738. structTypeNode = bufferType.layout;
  11739. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  11740. bufferCount = value.count;
  11741. }
  11742. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  11743. nodeType = getTypeFromLength( value.itemSize );
  11744. bufferCount = value.count;
  11745. } else {
  11746. nodeType = bufferType;
  11747. }
  11748. super( value, nodeType, bufferCount );
  11749. /**
  11750. * This flag can be used for type testing.
  11751. *
  11752. * @type {boolean}
  11753. * @readonly
  11754. * @default true
  11755. */
  11756. this.isStorageBufferNode = true;
  11757. /**
  11758. * The buffer struct type.
  11759. *
  11760. * @type {?StructTypeNode}
  11761. * @default null
  11762. */
  11763. this.structTypeNode = structTypeNode;
  11764. /**
  11765. * The access type of the texture node.
  11766. *
  11767. * @type {string}
  11768. * @default 'readWrite'
  11769. */
  11770. this.access = NodeAccess.READ_WRITE;
  11771. /**
  11772. * Whether the node is atomic or not.
  11773. *
  11774. * @type {boolean}
  11775. * @default false
  11776. */
  11777. this.isAtomic = false;
  11778. /**
  11779. * Whether the node represents a PBO or not.
  11780. * Only relevant for WebGL.
  11781. *
  11782. * @type {boolean}
  11783. * @default false
  11784. */
  11785. this.isPBO = false;
  11786. /**
  11787. * A reference to the internal buffer attribute node.
  11788. *
  11789. * @private
  11790. * @type {?BufferAttributeNode}
  11791. * @default null
  11792. */
  11793. this._attribute = null;
  11794. /**
  11795. * A reference to the internal varying node.
  11796. *
  11797. * @private
  11798. * @type {?VaryingNode}
  11799. * @default null
  11800. */
  11801. this._varying = null;
  11802. /**
  11803. * `StorageBufferNode` sets this property to `true` by default.
  11804. *
  11805. * @type {boolean}
  11806. * @default true
  11807. */
  11808. this.global = true;
  11809. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  11810. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  11811. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  11812. else value.isStorageBufferAttribute = true;
  11813. }
  11814. }
  11815. /**
  11816. * This method is overwritten since the buffer data might be shared
  11817. * and thus the hash should be shared as well.
  11818. *
  11819. * @param {NodeBuilder} builder - The current node builder.
  11820. * @return {string} The hash.
  11821. */
  11822. getHash( builder ) {
  11823. if ( this.bufferCount === 0 ) {
  11824. let bufferData = builder.globalCache.getData( this.value );
  11825. if ( bufferData === undefined ) {
  11826. bufferData = {
  11827. node: this
  11828. };
  11829. builder.globalCache.setData( this.value, bufferData );
  11830. }
  11831. return bufferData.node.uuid;
  11832. }
  11833. return this.uuid;
  11834. }
  11835. /**
  11836. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  11837. *
  11838. * @param {NodeBuilder} builder - The current node builder.
  11839. * @return {string} The input type.
  11840. */
  11841. getInputType( /*builder*/ ) {
  11842. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  11843. }
  11844. /**
  11845. * Enables element access with the given index node.
  11846. *
  11847. * @param {IndexNode} indexNode - The index node.
  11848. * @return {StorageArrayElementNode} A node representing the element access.
  11849. */
  11850. element( indexNode ) {
  11851. return storageElement( this, indexNode );
  11852. }
  11853. /**
  11854. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  11855. *
  11856. * @param {boolean} value - The value so set.
  11857. * @return {StorageBufferNode} A reference to this node.
  11858. */
  11859. setPBO( value ) {
  11860. this.isPBO = value;
  11861. return this;
  11862. }
  11863. /**
  11864. * Returns the `isPBO` value.
  11865. *
  11866. * @return {boolean} Whether the node represents a PBO or not.
  11867. */
  11868. getPBO() {
  11869. return this.isPBO;
  11870. }
  11871. /**
  11872. * Defines the node access.
  11873. *
  11874. * @param {string} value - The node access.
  11875. * @return {StorageBufferNode} A reference to this node.
  11876. */
  11877. setAccess( value ) {
  11878. this.access = value;
  11879. return this;
  11880. }
  11881. /**
  11882. * Convenience method for configuring a read-only node access.
  11883. *
  11884. * @return {StorageBufferNode} A reference to this node.
  11885. */
  11886. toReadOnly() {
  11887. return this.setAccess( NodeAccess.READ_ONLY );
  11888. }
  11889. /**
  11890. * Defines whether the node is atomic or not.
  11891. *
  11892. * @param {boolean} value - The atomic flag.
  11893. * @return {StorageBufferNode} A reference to this node.
  11894. */
  11895. setAtomic( value ) {
  11896. this.isAtomic = value;
  11897. return this;
  11898. }
  11899. /**
  11900. * Convenience method for making this node atomic.
  11901. *
  11902. * @return {StorageBufferNode} A reference to this node.
  11903. */
  11904. toAtomic() {
  11905. return this.setAtomic( true );
  11906. }
  11907. /**
  11908. * Returns attribute data for this storage buffer node.
  11909. *
  11910. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  11911. */
  11912. getAttributeData() {
  11913. if ( this._attribute === null ) {
  11914. this._attribute = bufferAttribute( this.value );
  11915. this._varying = varying( this._attribute );
  11916. }
  11917. return {
  11918. attribute: this._attribute,
  11919. varying: this._varying
  11920. };
  11921. }
  11922. /**
  11923. * This method is overwritten since the node type from the availability of storage buffers
  11924. * and the attribute data.
  11925. *
  11926. * @param {NodeBuilder} builder - The current node builder.
  11927. * @return {string} The node type.
  11928. */
  11929. getNodeType( builder ) {
  11930. if ( this.structTypeNode !== null ) {
  11931. return this.structTypeNode.getNodeType( builder );
  11932. }
  11933. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11934. return super.getNodeType( builder );
  11935. }
  11936. const { attribute } = this.getAttributeData();
  11937. return attribute.getNodeType( builder );
  11938. }
  11939. /**
  11940. * Returns the type of a member of the struct.
  11941. *
  11942. * @param {NodeBuilder} builder - The current node builder.
  11943. * @param {string} name - The name of the member.
  11944. * @return {string} The type of the member.
  11945. */
  11946. getMemberType( builder, name ) {
  11947. if ( this.structTypeNode !== null ) {
  11948. return this.structTypeNode.getMemberType( builder, name );
  11949. }
  11950. return 'void';
  11951. }
  11952. /**
  11953. * Generates the code snippet of the storage buffer node.
  11954. *
  11955. * @param {NodeBuilder} builder - The current node builder.
  11956. * @return {string} The generated code snippet.
  11957. */
  11958. generate( builder ) {
  11959. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  11960. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11961. return super.generate( builder );
  11962. }
  11963. const { attribute, varying } = this.getAttributeData();
  11964. const output = varying.build( builder );
  11965. builder.registerTransform( output, attribute );
  11966. return output;
  11967. }
  11968. }
  11969. /**
  11970. * TSL function for creating a storage buffer node.
  11971. *
  11972. * @tsl
  11973. * @function
  11974. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11975. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  11976. * @param {number} [count=0] - The buffer count.
  11977. * @returns {StorageBufferNode}
  11978. */
  11979. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  11980. /**
  11981. * @tsl
  11982. * @function
  11983. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  11984. *
  11985. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11986. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  11987. * @param {number} count - The buffer count.
  11988. * @returns {StorageBufferNode}
  11989. */
  11990. const storageObject = ( value, type, count ) => { // @deprecated, r171
  11991. warn( 'TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  11992. return storage( value, type, count ).setPBO( true );
  11993. };
  11994. /**
  11995. * This class represents shader indices of different types. The following predefined node
  11996. * objects cover frequent use cases:
  11997. *
  11998. * - `vertexIndex`: The index of a vertex within a mesh.
  11999. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  12000. * - `drawIndex`: The index of a draw call.
  12001. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  12002. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  12003. * - `subgroupIndex`: The index of a compute invocation's subgroup within its workgroup.
  12004. *
  12005. * @augments Node
  12006. */
  12007. class IndexNode extends Node {
  12008. static get type() {
  12009. return 'IndexNode';
  12010. }
  12011. /**
  12012. * Constructs a new index node.
  12013. *
  12014. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationGlobal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  12015. */
  12016. constructor( scope ) {
  12017. super( 'uint' );
  12018. /**
  12019. * The scope of the index node.
  12020. *
  12021. * @type {string}
  12022. */
  12023. this.scope = scope;
  12024. /**
  12025. * This flag can be used for type testing.
  12026. *
  12027. * @type {boolean}
  12028. * @readonly
  12029. * @default true
  12030. */
  12031. this.isIndexNode = true;
  12032. }
  12033. generate( builder ) {
  12034. const nodeType = this.getNodeType( builder );
  12035. const scope = this.scope;
  12036. let propertyName;
  12037. if ( scope === IndexNode.VERTEX ) {
  12038. propertyName = builder.getVertexIndex();
  12039. } else if ( scope === IndexNode.INSTANCE ) {
  12040. propertyName = builder.getInstanceIndex();
  12041. } else if ( scope === IndexNode.DRAW ) {
  12042. propertyName = builder.getDrawIndex();
  12043. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  12044. propertyName = builder.getInvocationLocalIndex();
  12045. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  12046. propertyName = builder.getInvocationSubgroupIndex();
  12047. } else if ( scope === IndexNode.SUBGROUP ) {
  12048. propertyName = builder.getSubgroupIndex();
  12049. } else {
  12050. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  12051. }
  12052. let output;
  12053. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  12054. output = propertyName;
  12055. } else {
  12056. const nodeVarying = varying( this );
  12057. output = nodeVarying.build( builder, nodeType );
  12058. }
  12059. return output;
  12060. }
  12061. }
  12062. IndexNode.VERTEX = 'vertex';
  12063. IndexNode.INSTANCE = 'instance';
  12064. IndexNode.SUBGROUP = 'subgroup';
  12065. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  12066. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  12067. IndexNode.DRAW = 'draw';
  12068. /**
  12069. * TSL object that represents the index of a vertex within a mesh.
  12070. *
  12071. * @tsl
  12072. * @type {IndexNode}
  12073. */
  12074. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  12075. /**
  12076. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  12077. *
  12078. * @tsl
  12079. * @type {IndexNode}
  12080. */
  12081. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  12082. /**
  12083. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  12084. *
  12085. * @tsl
  12086. * @type {IndexNode}
  12087. */
  12088. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  12089. /**
  12090. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  12091. *
  12092. * @tsl
  12093. * @type {IndexNode}
  12094. */
  12095. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  12096. /**
  12097. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  12098. *
  12099. * @tsl
  12100. * @type {IndexNode}
  12101. */
  12102. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  12103. /**
  12104. * TSL object that represents the index of a draw call.
  12105. *
  12106. * @tsl
  12107. * @type {IndexNode}
  12108. */
  12109. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  12110. /**
  12111. * This node implements the vertex shader logic which is required
  12112. * when rendering 3D objects via instancing. The code makes sure
  12113. * vertex positions, normals and colors can be modified via instanced
  12114. * data.
  12115. *
  12116. * @augments Node
  12117. */
  12118. class InstanceNode extends Node {
  12119. static get type() {
  12120. return 'InstanceNode';
  12121. }
  12122. /**
  12123. * Constructs a new instance node.
  12124. *
  12125. * @param {number} count - The number of instances.
  12126. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  12127. * @param {?InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  12128. */
  12129. constructor( count, instanceMatrix, instanceColor = null ) {
  12130. super( 'void' );
  12131. /**
  12132. * The number of instances.
  12133. *
  12134. * @type {number}
  12135. */
  12136. this.count = count;
  12137. /**
  12138. * Instanced buffer attribute representing the transformation of instances.
  12139. *
  12140. * @type {InstancedBufferAttribute}
  12141. */
  12142. this.instanceMatrix = instanceMatrix;
  12143. /**
  12144. * Instanced buffer attribute representing the color of instances.
  12145. *
  12146. * @type {InstancedBufferAttribute}
  12147. */
  12148. this.instanceColor = instanceColor;
  12149. /**
  12150. * The node that represents the instance matrix data.
  12151. *
  12152. * @type {?Node}
  12153. */
  12154. this.instanceMatrixNode = null;
  12155. /**
  12156. * The node that represents the instance color data.
  12157. *
  12158. * @type {?Node}
  12159. * @default null
  12160. */
  12161. this.instanceColorNode = null;
  12162. /**
  12163. * The update type is set to `frame` since an update
  12164. * of instanced buffer data must be checked per frame.
  12165. *
  12166. * @type {string}
  12167. * @default 'frame'
  12168. */
  12169. this.updateType = NodeUpdateType.FRAME;
  12170. /**
  12171. * A reference to a buffer that is used by `instanceMatrixNode`.
  12172. *
  12173. * @type {?InstancedInterleavedBuffer}
  12174. */
  12175. this.buffer = null;
  12176. /**
  12177. * A reference to a buffer that is used by `instanceColorNode`.
  12178. *
  12179. * @type {?InstancedBufferAttribute}
  12180. */
  12181. this.bufferColor = null;
  12182. }
  12183. /**
  12184. * Tracks whether the matrix data is provided via a storage buffer.
  12185. *
  12186. * @type {boolean}
  12187. */
  12188. get isStorageMatrix() {
  12189. const { instanceMatrix } = this;
  12190. return instanceMatrix && instanceMatrix.isStorageInstancedBufferAttribute === true;
  12191. }
  12192. /**
  12193. * Tracks whether the color data is provided via a storage buffer.
  12194. *
  12195. * @type {boolean}
  12196. */
  12197. get isStorageColor() {
  12198. const { instanceColor } = this;
  12199. return instanceColor && instanceColor.isStorageInstancedBufferAttribute === true;
  12200. }
  12201. /**
  12202. * Setups the internal buffers and nodes and assigns the transformed vertex data
  12203. * to predefined node variables for accumulation. That follows the same patterns
  12204. * like with morph and skinning nodes.
  12205. *
  12206. * @param {NodeBuilder} builder - The current node builder.
  12207. */
  12208. setup( builder ) {
  12209. const { instanceMatrix, instanceColor, isStorageMatrix, isStorageColor } = this;
  12210. const { count } = instanceMatrix;
  12211. let { instanceMatrixNode, instanceColorNode } = this;
  12212. if ( instanceMatrixNode === null ) {
  12213. if ( isStorageMatrix ) {
  12214. instanceMatrixNode = storage( instanceMatrix, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  12215. } else {
  12216. // Both backends have ~64kb UBO limit; fallback to attributes above 1000 matrices.
  12217. if ( count <= 1000 ) {
  12218. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  12219. } else {
  12220. const interleaved = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  12221. this.buffer = interleaved;
  12222. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  12223. const instanceBuffers = [
  12224. bufferFn( interleaved, 'vec4', 16, 0 ),
  12225. bufferFn( interleaved, 'vec4', 16, 4 ),
  12226. bufferFn( interleaved, 'vec4', 16, 8 ),
  12227. bufferFn( interleaved, 'vec4', 16, 12 )
  12228. ];
  12229. instanceMatrixNode = mat4( ...instanceBuffers );
  12230. }
  12231. }
  12232. this.instanceMatrixNode = instanceMatrixNode;
  12233. }
  12234. if ( instanceColor && instanceColorNode === null ) {
  12235. if ( isStorageColor ) {
  12236. instanceColorNode = storage( instanceColor, 'vec3', Math.max( instanceColor.count, 1 ) ).element( instanceIndex );
  12237. } else {
  12238. const bufferAttribute = new InstancedBufferAttribute( instanceColor.array, 3 );
  12239. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  12240. this.bufferColor = bufferAttribute;
  12241. instanceColorNode = vec3( bufferFn( bufferAttribute, 'vec3', 3, 0 ) );
  12242. }
  12243. this.instanceColorNode = instanceColorNode;
  12244. }
  12245. // POSITION
  12246. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  12247. positionLocal.assign( instancePosition );
  12248. // NORMAL
  12249. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12250. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  12251. // ASSIGNS
  12252. normalLocal.assign( instanceNormal );
  12253. }
  12254. // COLOR
  12255. if ( this.instanceColorNode !== null ) {
  12256. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  12257. }
  12258. }
  12259. /**
  12260. * Checks if the internal buffers require an update.
  12261. *
  12262. * @param {NodeFrame} frame - The current node frame.
  12263. */
  12264. update( /*frame*/ ) {
  12265. if ( this.buffer !== null && this.isStorageMatrix !== true ) {
  12266. this.buffer.clearUpdateRanges();
  12267. this.buffer.updateRanges.push( ... this.instanceMatrix.updateRanges );
  12268. // update version if necessary
  12269. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.instanceMatrix.version !== this.buffer.version ) {
  12270. this.buffer.version = this.instanceMatrix.version;
  12271. }
  12272. }
  12273. if ( this.instanceColor && this.bufferColor !== null && this.isStorageColor !== true ) {
  12274. this.bufferColor.clearUpdateRanges();
  12275. this.bufferColor.updateRanges.push( ... this.instanceColor.updateRanges );
  12276. if ( this.instanceColor.usage !== DynamicDrawUsage && this.instanceColor.version !== this.bufferColor.version ) {
  12277. this.bufferColor.version = this.instanceColor.version;
  12278. }
  12279. }
  12280. }
  12281. }
  12282. /**
  12283. * TSL function for creating an instance node.
  12284. *
  12285. * @tsl
  12286. * @function
  12287. * @param {number} count - The number of instances.
  12288. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  12289. * @param {?InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  12290. * @returns {InstanceNode}
  12291. */
  12292. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  12293. /**
  12294. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  12295. * It allows an easier setup of the instance node.
  12296. *
  12297. * @augments InstanceNode
  12298. */
  12299. class InstancedMeshNode extends InstanceNode {
  12300. static get type() {
  12301. return 'InstancedMeshNode';
  12302. }
  12303. /**
  12304. * Constructs a new instanced mesh node.
  12305. *
  12306. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  12307. */
  12308. constructor( instancedMesh ) {
  12309. const { count, instanceMatrix, instanceColor } = instancedMesh;
  12310. super( count, instanceMatrix, instanceColor );
  12311. /**
  12312. * A reference to the instanced mesh.
  12313. *
  12314. * @type {InstancedMesh}
  12315. */
  12316. this.instancedMesh = instancedMesh;
  12317. }
  12318. }
  12319. /**
  12320. * TSL function for creating an instanced mesh node.
  12321. *
  12322. * @tsl
  12323. * @function
  12324. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  12325. * @returns {InstancedMeshNode}
  12326. */
  12327. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  12328. /**
  12329. * This node implements the vertex shader logic which is required
  12330. * when rendering 3D objects via batching. `BatchNode` must be used
  12331. * with instances of {@link BatchedMesh}.
  12332. *
  12333. * @augments Node
  12334. */
  12335. class BatchNode extends Node {
  12336. static get type() {
  12337. return 'BatchNode';
  12338. }
  12339. /**
  12340. * Constructs a new batch node.
  12341. *
  12342. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  12343. */
  12344. constructor( batchMesh ) {
  12345. super( 'void' );
  12346. /**
  12347. * A reference to batched mesh.
  12348. *
  12349. * @type {BatchedMesh}
  12350. */
  12351. this.batchMesh = batchMesh;
  12352. /**
  12353. * The batching index node.
  12354. *
  12355. * @type {?IndexNode}
  12356. * @default null
  12357. */
  12358. this.batchingIdNode = null;
  12359. }
  12360. /**
  12361. * Setups the internal buffers and nodes and assigns the transformed vertex data
  12362. * to predefined node variables for accumulation. That follows the same patterns
  12363. * like with morph and skinning nodes.
  12364. *
  12365. * @param {NodeBuilder} builder - The current node builder.
  12366. */
  12367. setup( builder ) {
  12368. if ( this.batchingIdNode === null ) {
  12369. if ( builder.getDrawIndex() === null ) {
  12370. this.batchingIdNode = instanceIndex;
  12371. } else {
  12372. this.batchingIdNode = drawIndex;
  12373. }
  12374. }
  12375. const getIndirectIndex = Fn( ( [ id ] ) => {
  12376. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x ).toConst();
  12377. const x = int( id ).mod( size ).toConst();
  12378. const y = int( id ).div( size ).toConst();
  12379. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  12380. } ).setLayout( {
  12381. name: 'getIndirectIndex',
  12382. type: 'uint',
  12383. inputs: [
  12384. { name: 'id', type: 'int' }
  12385. ]
  12386. } );
  12387. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  12388. const matricesTexture = this.batchMesh._matricesTexture;
  12389. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x ).toConst();
  12390. const j = float( indirectId ).mul( 4 ).toInt().toConst();
  12391. const x = j.mod( size ).toConst();
  12392. const y = j.div( size ).toConst();
  12393. const batchingMatrix = mat4(
  12394. textureLoad( matricesTexture, ivec2( x, y ) ),
  12395. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  12396. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  12397. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  12398. );
  12399. const colorsTexture = this.batchMesh._colorsTexture;
  12400. if ( colorsTexture !== null ) {
  12401. const getBatchingColor = Fn( ( [ id ] ) => {
  12402. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x ).toConst();
  12403. const j = id;
  12404. const x = j.mod( size ).toConst();
  12405. const y = j.div( size ).toConst();
  12406. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  12407. } ).setLayout( {
  12408. name: 'getBatchingColor',
  12409. type: 'vec3',
  12410. inputs: [
  12411. { name: 'id', type: 'int' }
  12412. ]
  12413. } );
  12414. const color = getBatchingColor( indirectId );
  12415. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  12416. }
  12417. const bm = mat3( batchingMatrix );
  12418. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  12419. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  12420. const batchingNormal = bm.mul( transformedNormal ).xyz;
  12421. normalLocal.assign( batchingNormal );
  12422. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12423. tangentLocal.mulAssign( bm );
  12424. }
  12425. }
  12426. }
  12427. /**
  12428. * TSL function for creating a batch node.
  12429. *
  12430. * @tsl
  12431. * @function
  12432. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  12433. * @returns {BatchNode}
  12434. */
  12435. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  12436. const _frameId = new WeakMap();
  12437. /**
  12438. * This node implements the vertex transformation shader logic which is required
  12439. * for skinning/skeletal animation.
  12440. *
  12441. * @augments Node
  12442. */
  12443. class SkinningNode extends Node {
  12444. static get type() {
  12445. return 'SkinningNode';
  12446. }
  12447. /**
  12448. * Constructs a new skinning node.
  12449. *
  12450. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12451. */
  12452. constructor( skinnedMesh ) {
  12453. super( 'void' );
  12454. /**
  12455. * The skinned mesh.
  12456. *
  12457. * @type {SkinnedMesh}
  12458. */
  12459. this.skinnedMesh = skinnedMesh;
  12460. /**
  12461. * The update type overwritten since skinning nodes are updated per object.
  12462. *
  12463. * @type {string}
  12464. */
  12465. this.updateType = NodeUpdateType.OBJECT;
  12466. //
  12467. /**
  12468. * The skin index attribute.
  12469. *
  12470. * @type {AttributeNode}
  12471. */
  12472. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  12473. /**
  12474. * The skin weight attribute.
  12475. *
  12476. * @type {AttributeNode}
  12477. */
  12478. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  12479. /**
  12480. * The bind matrix node.
  12481. *
  12482. * @type {Node<mat4>}
  12483. */
  12484. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  12485. /**
  12486. * The bind matrix inverse node.
  12487. *
  12488. * @type {Node<mat4>}
  12489. */
  12490. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  12491. /**
  12492. * The bind matrices as a uniform buffer node.
  12493. *
  12494. * @type {Node}
  12495. */
  12496. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12497. /**
  12498. * The current vertex position in local space.
  12499. *
  12500. * @type {Node<vec3>}
  12501. */
  12502. this.positionNode = positionLocal;
  12503. /**
  12504. * The result of vertex position in local space.
  12505. *
  12506. * @type {Node<vec3>}
  12507. */
  12508. this.toPositionNode = positionLocal;
  12509. /**
  12510. * The previous bind matrices as a uniform buffer node.
  12511. * Required for computing motion vectors.
  12512. *
  12513. * @type {?Node}
  12514. * @default null
  12515. */
  12516. this.previousBoneMatricesNode = null;
  12517. }
  12518. /**
  12519. * Transforms the given vertex position via skinning.
  12520. *
  12521. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12522. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  12523. * @return {Node<vec3>} The transformed vertex position.
  12524. */
  12525. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  12526. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12527. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12528. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12529. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12530. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12531. // POSITION
  12532. const skinVertex = bindMatrixNode.mul( position );
  12533. const skinned = add(
  12534. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  12535. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  12536. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  12537. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  12538. );
  12539. return bindMatrixInverseNode.mul( skinned ).xyz;
  12540. }
  12541. /**
  12542. * Transforms the given vertex normal via skinning.
  12543. *
  12544. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12545. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  12546. * @return {Node<vec3>} The transformed vertex normal.
  12547. */
  12548. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  12549. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12550. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12551. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12552. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12553. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12554. // NORMAL
  12555. let skinMatrix = add(
  12556. skinWeightNode.x.mul( boneMatX ),
  12557. skinWeightNode.y.mul( boneMatY ),
  12558. skinWeightNode.z.mul( boneMatZ ),
  12559. skinWeightNode.w.mul( boneMatW )
  12560. );
  12561. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  12562. return skinMatrix.transformDirection( normal ).xyz;
  12563. }
  12564. /**
  12565. * Computes the transformed/skinned vertex position of the previous frame.
  12566. *
  12567. * @param {NodeBuilder} builder - The current node builder.
  12568. * @return {Node<vec3>} The skinned position from the previous frame.
  12569. */
  12570. getPreviousSkinnedPosition( builder ) {
  12571. const skinnedMesh = builder.object;
  12572. if ( this.previousBoneMatricesNode === null ) {
  12573. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  12574. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12575. }
  12576. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  12577. }
  12578. /**
  12579. * Returns `true` if bone matrices from the previous frame are required. Relevant
  12580. * when computing motion vectors with {@link VelocityNode}.
  12581. *
  12582. * @param {NodeBuilder} builder - The current node builder.
  12583. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  12584. */
  12585. needsPreviousBoneMatrices( builder ) {
  12586. const mrt = builder.renderer.getMRT();
  12587. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  12588. }
  12589. /**
  12590. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  12591. *
  12592. * @param {NodeBuilder} builder - The current node builder.
  12593. * @return {Node<vec3>} The transformed vertex position.
  12594. */
  12595. setup( builder ) {
  12596. if ( this.needsPreviousBoneMatrices( builder ) ) {
  12597. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  12598. }
  12599. const skinPosition = this.getSkinnedPosition();
  12600. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  12601. //
  12602. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12603. const skinNormal = this.getSkinnedNormal();
  12604. normalLocal.assign( skinNormal );
  12605. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12606. tangentLocal.assign( skinNormal );
  12607. }
  12608. }
  12609. return skinPosition;
  12610. }
  12611. /**
  12612. * Generates the code snippet of the skinning node.
  12613. *
  12614. * @param {NodeBuilder} builder - The current node builder.
  12615. * @param {string} output - The current output.
  12616. * @return {string} The generated code snippet.
  12617. */
  12618. generate( builder, output ) {
  12619. if ( output !== 'void' ) {
  12620. return super.generate( builder, output );
  12621. }
  12622. }
  12623. /**
  12624. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  12625. *
  12626. * @param {NodeFrame} frame - The current node frame.
  12627. */
  12628. update( frame ) {
  12629. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  12630. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  12631. _frameId.set( skeleton, frame.frameId );
  12632. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  12633. skeleton.update();
  12634. }
  12635. }
  12636. /**
  12637. * TSL function for creating a skinning node.
  12638. *
  12639. * @tsl
  12640. * @function
  12641. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12642. * @returns {SkinningNode}
  12643. */
  12644. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  12645. /**
  12646. * TSL function for computing skinning.
  12647. *
  12648. * @tsl
  12649. * @function
  12650. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12651. * @param {Node<vec3>} [toPosition=null] - The target position.
  12652. * @returns {SkinningNode}
  12653. */
  12654. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  12655. const node = new SkinningNode( skinnedMesh );
  12656. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12657. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12658. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12659. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  12660. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  12661. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  12662. node.toPositionNode = toPosition;
  12663. return nodeObject( node );
  12664. };
  12665. /**
  12666. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  12667. * ```js
  12668. * Loop( count, ( { i } ) => {
  12669. *
  12670. * } );
  12671. * ```
  12672. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  12673. * ```js
  12674. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  12675. *
  12676. * } );
  12677. *```
  12678. * Nested loops can be defined in a compacted form:
  12679. * ```js
  12680. * Loop( 10, 5, ( { i, j } ) => {
  12681. *
  12682. * } );
  12683. * ```
  12684. * Loops that should run backwards can be defined like so:
  12685. * ```js
  12686. * Loop( { start: 10 }, () => {} );
  12687. * ```
  12688. * It is possible to execute with boolean values, similar to the `while` syntax.
  12689. * ```js
  12690. * const value = float( 0 ).toVar();
  12691. *
  12692. * Loop( value.lessThan( 10 ), () => {
  12693. *
  12694. * value.addAssign( 1 );
  12695. *
  12696. * } );
  12697. * ```
  12698. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  12699. * @augments Node
  12700. */
  12701. class LoopNode extends Node {
  12702. static get type() {
  12703. return 'LoopNode';
  12704. }
  12705. /**
  12706. * Constructs a new loop node.
  12707. *
  12708. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  12709. */
  12710. constructor( params = [] ) {
  12711. super( 'void' );
  12712. this.params = params;
  12713. }
  12714. /**
  12715. * Returns a loop variable name based on an index. The pattern is
  12716. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  12717. *
  12718. * @param {number} index - The index.
  12719. * @return {string} The loop variable name.
  12720. */
  12721. getVarName( index ) {
  12722. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  12723. }
  12724. /**
  12725. * Returns properties about this node.
  12726. *
  12727. * @param {NodeBuilder} builder - The current node builder.
  12728. * @return {Object} The node properties.
  12729. */
  12730. getProperties( builder ) {
  12731. const properties = builder.getNodeProperties( this );
  12732. if ( properties.stackNode !== undefined ) return properties;
  12733. //
  12734. const inputs = {};
  12735. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12736. const param = this.params[ i ];
  12737. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  12738. const type = ( param.isNode !== true && param.type ) || 'int';
  12739. inputs[ name ] = expression( name, type );
  12740. }
  12741. const stack = builder.addStack();
  12742. const fnCall = this.params[ this.params.length - 1 ]( inputs );
  12743. properties.returnsNode = fnCall.context( { nodeLoop: fnCall } );
  12744. properties.stackNode = stack;
  12745. const baseParam = this.params[ 0 ];
  12746. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  12747. const fnUpdateCall = Fn( this.params[ 0 ].update )( inputs );
  12748. properties.updateNode = fnUpdateCall.context( { nodeLoop: fnUpdateCall } );
  12749. }
  12750. builder.removeStack();
  12751. return properties;
  12752. }
  12753. setup( builder ) {
  12754. // setup properties
  12755. this.getProperties( builder );
  12756. if ( builder.fnCall ) {
  12757. const shaderNodeData = builder.getDataFromNode( builder.fnCall.shaderNode );
  12758. shaderNodeData.hasLoop = true;
  12759. }
  12760. }
  12761. generate( builder ) {
  12762. const properties = this.getProperties( builder );
  12763. const params = this.params;
  12764. const stackNode = properties.stackNode;
  12765. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  12766. const param = params[ i ];
  12767. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  12768. if ( param.isNode ) {
  12769. if ( param.getNodeType( builder ) === 'bool' ) {
  12770. isWhile = true;
  12771. type = 'bool';
  12772. end = param.build( builder, type );
  12773. } else {
  12774. type = 'int';
  12775. name = this.getVarName( i );
  12776. start = '0';
  12777. end = param.build( builder, type );
  12778. condition = '<';
  12779. }
  12780. } else {
  12781. type = param.type || 'int';
  12782. name = param.name || this.getVarName( i );
  12783. start = param.start;
  12784. end = param.end;
  12785. condition = param.condition;
  12786. update = param.update;
  12787. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  12788. else if ( start && start.isNode ) start = start.build( builder, type );
  12789. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  12790. else if ( end && end.isNode ) end = end.build( builder, type );
  12791. if ( start !== undefined && end === undefined ) {
  12792. start = start + ' - 1';
  12793. end = '0';
  12794. condition = '>=';
  12795. } else if ( end !== undefined && start === undefined ) {
  12796. start = '0';
  12797. condition = '<';
  12798. }
  12799. if ( condition === undefined ) {
  12800. if ( Number( start ) > Number( end ) ) {
  12801. condition = '>=';
  12802. } else {
  12803. condition = '<';
  12804. }
  12805. }
  12806. }
  12807. let loopSnippet;
  12808. if ( isWhile ) {
  12809. loopSnippet = `while ( ${ end } )`;
  12810. } else {
  12811. const internalParam = { start, end};
  12812. //
  12813. const startSnippet = internalParam.start;
  12814. const endSnippet = internalParam.end;
  12815. let updateSnippet;
  12816. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  12817. if ( update !== undefined && update !== null ) {
  12818. switch ( typeof update ) {
  12819. case 'function':
  12820. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  12821. const snippet = flow.code.replace( /\t|;/g, '' );
  12822. updateSnippet = snippet;
  12823. break;
  12824. case 'number':
  12825. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  12826. break;
  12827. case 'string':
  12828. updateSnippet = name + ' ' + update;
  12829. break;
  12830. default:
  12831. if ( update.isNode ) {
  12832. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  12833. } else {
  12834. error( 'TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  12835. updateSnippet = 'break /* invalid update */';
  12836. }
  12837. }
  12838. } else {
  12839. if ( type === 'int' || type === 'uint' ) {
  12840. update = condition.includes( '<' ) ? '++' : '--';
  12841. } else {
  12842. update = deltaOperator() + ' 1.';
  12843. }
  12844. updateSnippet = name + ' ' + update;
  12845. }
  12846. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  12847. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  12848. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  12849. }
  12850. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  12851. }
  12852. const stackSnippet = stackNode.build( builder, 'void' );
  12853. properties.returnsNode.build( builder, 'void' );
  12854. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  12855. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12856. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  12857. }
  12858. builder.addFlowTab();
  12859. }
  12860. }
  12861. /**
  12862. * TSL function for creating a loop node.
  12863. *
  12864. * @tsl
  12865. * @function
  12866. * @param {...any} params - A list of parameters.
  12867. * @returns {LoopNode}
  12868. */
  12869. const Loop = ( ...params ) => new LoopNode( nodeArray( params, 'int' ) ).toStack();
  12870. /**
  12871. * TSL function for creating a `Continue()` expression.
  12872. *
  12873. * @tsl
  12874. * @function
  12875. * @returns {ExpressionNode}
  12876. */
  12877. const Continue = () => expression( 'continue' ).toStack();
  12878. /**
  12879. * TSL function for creating a `Break()` expression.
  12880. *
  12881. * @tsl
  12882. * @function
  12883. * @returns {ExpressionNode}
  12884. */
  12885. const Break = () => expression( 'break' ).toStack();
  12886. const _morphTextures = /*@__PURE__*/ new WeakMap();
  12887. const _morphVec4 = /*@__PURE__*/ new Vector4();
  12888. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  12889. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  12890. const y = texelIndex.div( width );
  12891. const x = texelIndex.sub( y.mul( width ) );
  12892. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  12893. return bufferAttrib.mul( influence );
  12894. } );
  12895. function getEntry( geometry ) {
  12896. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12897. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  12898. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  12899. // instead of using attributes, the WebGL 2 code path encodes morph targets
  12900. // into an array of data textures. Each layer represents a single morph target.
  12901. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12902. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12903. let entry = _morphTextures.get( geometry );
  12904. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  12905. if ( entry !== undefined ) entry.texture.dispose();
  12906. const morphTargets = geometry.morphAttributes.position || [];
  12907. const morphNormals = geometry.morphAttributes.normal || [];
  12908. const morphColors = geometry.morphAttributes.color || [];
  12909. let vertexDataCount = 0;
  12910. if ( hasMorphPosition === true ) vertexDataCount = 1;
  12911. if ( hasMorphNormals === true ) vertexDataCount = 2;
  12912. if ( hasMorphColors === true ) vertexDataCount = 3;
  12913. let width = geometry.attributes.position.count * vertexDataCount;
  12914. let height = 1;
  12915. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  12916. if ( width > maxTextureSize ) {
  12917. height = Math.ceil( width / maxTextureSize );
  12918. width = maxTextureSize;
  12919. }
  12920. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  12921. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  12922. bufferTexture.type = FloatType;
  12923. bufferTexture.needsUpdate = true;
  12924. // fill buffer
  12925. const vertexDataStride = vertexDataCount * 4;
  12926. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  12927. const morphTarget = morphTargets[ i ];
  12928. const morphNormal = morphNormals[ i ];
  12929. const morphColor = morphColors[ i ];
  12930. const offset = width * height * 4 * i;
  12931. for ( let j = 0; j < morphTarget.count; j ++ ) {
  12932. const stride = j * vertexDataStride;
  12933. if ( hasMorphPosition === true ) {
  12934. _morphVec4.fromBufferAttribute( morphTarget, j );
  12935. buffer[ offset + stride + 0 ] = _morphVec4.x;
  12936. buffer[ offset + stride + 1 ] = _morphVec4.y;
  12937. buffer[ offset + stride + 2 ] = _morphVec4.z;
  12938. buffer[ offset + stride + 3 ] = 0;
  12939. }
  12940. if ( hasMorphNormals === true ) {
  12941. _morphVec4.fromBufferAttribute( morphNormal, j );
  12942. buffer[ offset + stride + 4 ] = _morphVec4.x;
  12943. buffer[ offset + stride + 5 ] = _morphVec4.y;
  12944. buffer[ offset + stride + 6 ] = _morphVec4.z;
  12945. buffer[ offset + stride + 7 ] = 0;
  12946. }
  12947. if ( hasMorphColors === true ) {
  12948. _morphVec4.fromBufferAttribute( morphColor, j );
  12949. buffer[ offset + stride + 8 ] = _morphVec4.x;
  12950. buffer[ offset + stride + 9 ] = _morphVec4.y;
  12951. buffer[ offset + stride + 10 ] = _morphVec4.z;
  12952. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  12953. }
  12954. }
  12955. }
  12956. entry = {
  12957. count: morphTargetsCount,
  12958. texture: bufferTexture,
  12959. stride: vertexDataCount,
  12960. size: new Vector2( width, height )
  12961. };
  12962. _morphTextures.set( geometry, entry );
  12963. function disposeTexture() {
  12964. bufferTexture.dispose();
  12965. _morphTextures.delete( geometry );
  12966. geometry.removeEventListener( 'dispose', disposeTexture );
  12967. }
  12968. geometry.addEventListener( 'dispose', disposeTexture );
  12969. }
  12970. return entry;
  12971. }
  12972. /**
  12973. * This node implements the vertex transformation shader logic which is required
  12974. * for morph target animation.
  12975. *
  12976. * @augments Node
  12977. */
  12978. class MorphNode extends Node {
  12979. static get type() {
  12980. return 'MorphNode';
  12981. }
  12982. /**
  12983. * Constructs a new morph node.
  12984. *
  12985. * @param {Mesh} mesh - The mesh holding the morph targets.
  12986. */
  12987. constructor( mesh ) {
  12988. super( 'void' );
  12989. /**
  12990. * The mesh holding the morph targets.
  12991. *
  12992. * @type {Mesh}
  12993. */
  12994. this.mesh = mesh;
  12995. /**
  12996. * A uniform node which represents the morph base influence value.
  12997. *
  12998. * @type {UniformNode<float>}
  12999. */
  13000. this.morphBaseInfluence = uniform( 1 );
  13001. /**
  13002. * The update type overwritten since morph nodes are updated per object.
  13003. *
  13004. * @type {string}
  13005. */
  13006. this.updateType = NodeUpdateType.OBJECT;
  13007. }
  13008. /**
  13009. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  13010. *
  13011. * @param {NodeBuilder} builder - The current node builder.
  13012. */
  13013. setup( builder ) {
  13014. const { geometry } = builder;
  13015. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  13016. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  13017. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  13018. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  13019. // nodes
  13020. const { texture: bufferMap, stride, size } = getEntry( geometry );
  13021. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  13022. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  13023. const width = int( size.width );
  13024. Loop( morphTargetsCount, ( { i } ) => {
  13025. const influence = float( 0 ).toVar();
  13026. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  13027. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  13028. } else {
  13029. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  13030. }
  13031. If( influence.notEqual( 0 ), () => {
  13032. if ( hasMorphPosition === true ) {
  13033. positionLocal.addAssign( getMorph( {
  13034. bufferMap,
  13035. influence,
  13036. stride,
  13037. width,
  13038. depth: i,
  13039. offset: int( 0 )
  13040. } ) );
  13041. }
  13042. if ( hasMorphNormals === true ) {
  13043. normalLocal.addAssign( getMorph( {
  13044. bufferMap,
  13045. influence,
  13046. stride,
  13047. width,
  13048. depth: i,
  13049. offset: int( 1 )
  13050. } ) );
  13051. }
  13052. } );
  13053. } );
  13054. }
  13055. /**
  13056. * Updates the state of the morphed mesh by updating the base influence.
  13057. *
  13058. * @param {NodeFrame} frame - The current node frame.
  13059. */
  13060. update( /*frame*/ ) {
  13061. const morphBaseInfluence = this.morphBaseInfluence;
  13062. if ( this.mesh.geometry.morphTargetsRelative ) {
  13063. morphBaseInfluence.value = 1;
  13064. } else {
  13065. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  13066. }
  13067. }
  13068. }
  13069. /**
  13070. * TSL function for creating a morph node.
  13071. *
  13072. * @tsl
  13073. * @function
  13074. * @param {Mesh} mesh - The mesh holding the morph targets.
  13075. * @returns {MorphNode}
  13076. */
  13077. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  13078. /**
  13079. * Base class for lighting nodes.
  13080. *
  13081. * @augments Node
  13082. */
  13083. class LightingNode extends Node {
  13084. static get type() {
  13085. return 'LightingNode';
  13086. }
  13087. /**
  13088. * Constructs a new lighting node.
  13089. */
  13090. constructor() {
  13091. super( 'vec3' );
  13092. /**
  13093. * This flag can be used for type testing.
  13094. *
  13095. * @type {boolean}
  13096. * @readonly
  13097. * @default true
  13098. */
  13099. this.isLightingNode = true;
  13100. }
  13101. }
  13102. /**
  13103. * A generic class that can be used by nodes which contribute
  13104. * ambient occlusion to the scene. E.g. an ambient occlusion map
  13105. * node can be used as input for this module. Used in {@link NodeMaterial}.
  13106. *
  13107. * @augments LightingNode
  13108. */
  13109. class AONode extends LightingNode {
  13110. static get type() {
  13111. return 'AONode';
  13112. }
  13113. /**
  13114. * Constructs a new AO node.
  13115. *
  13116. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  13117. */
  13118. constructor( aoNode = null ) {
  13119. super();
  13120. /**
  13121. * The ambient occlusion node.
  13122. *
  13123. * @type {?Node<float>}
  13124. * @default null
  13125. */
  13126. this.aoNode = aoNode;
  13127. }
  13128. setup( builder ) {
  13129. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  13130. }
  13131. }
  13132. /**
  13133. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  13134. * by adding lighting specific context data. It represents the runtime context of
  13135. * {@link LightsNode}.
  13136. *
  13137. * @augments ContextNode
  13138. */
  13139. class LightingContextNode extends ContextNode {
  13140. static get type() {
  13141. return 'LightingContextNode';
  13142. }
  13143. /**
  13144. * Constructs a new lighting context node.
  13145. *
  13146. * @param {LightsNode} lightsNode - The lights node.
  13147. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  13148. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  13149. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  13150. */
  13151. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  13152. super( lightsNode );
  13153. /**
  13154. * The current lighting model.
  13155. *
  13156. * @type {?LightingModel}
  13157. * @default null
  13158. */
  13159. this.lightingModel = lightingModel;
  13160. /**
  13161. * A backdrop node.
  13162. *
  13163. * @type {?Node<vec3>}
  13164. * @default null
  13165. */
  13166. this.backdropNode = backdropNode;
  13167. /**
  13168. * A backdrop alpha node.
  13169. *
  13170. * @type {?Node<float>}
  13171. * @default null
  13172. */
  13173. this.backdropAlphaNode = backdropAlphaNode;
  13174. this._value = null;
  13175. }
  13176. /**
  13177. * Returns a lighting context object.
  13178. *
  13179. * @return {{
  13180. * radiance: Node<vec3>,
  13181. * irradiance: Node<vec3>,
  13182. * iblIrradiance: Node<vec3>,
  13183. * ambientOcclusion: Node<float>,
  13184. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  13185. * backdrop: Node<vec3>,
  13186. * backdropAlpha: Node<float>
  13187. * }} The lighting context object.
  13188. */
  13189. getContext() {
  13190. const { backdropNode, backdropAlphaNode } = this;
  13191. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  13192. directSpecular = vec3().toVar( 'directSpecular' ),
  13193. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  13194. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  13195. const reflectedLight = {
  13196. directDiffuse,
  13197. directSpecular,
  13198. indirectDiffuse,
  13199. indirectSpecular
  13200. };
  13201. const context = {
  13202. radiance: vec3().toVar( 'radiance' ),
  13203. irradiance: vec3().toVar( 'irradiance' ),
  13204. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  13205. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  13206. reflectedLight,
  13207. backdrop: backdropNode,
  13208. backdropAlpha: backdropAlphaNode
  13209. };
  13210. return context;
  13211. }
  13212. setup( builder ) {
  13213. this.value = this._value || ( this._value = this.getContext() );
  13214. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  13215. return super.setup( builder );
  13216. }
  13217. }
  13218. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  13219. /**
  13220. * A generic class that can be used by nodes which contribute
  13221. * irradiance to the scene. E.g. a light map node can be used
  13222. * as input for this module. Used in {@link NodeMaterial}.
  13223. *
  13224. * @augments LightingNode
  13225. */
  13226. class IrradianceNode extends LightingNode {
  13227. static get type() {
  13228. return 'IrradianceNode';
  13229. }
  13230. /**
  13231. * Constructs a new irradiance node.
  13232. *
  13233. * @param {Node<vec3>} node - A node contributing irradiance.
  13234. */
  13235. constructor( node ) {
  13236. super();
  13237. /**
  13238. * A node contributing irradiance.
  13239. *
  13240. * @type {Node<vec3>}
  13241. */
  13242. this.node = node;
  13243. }
  13244. setup( builder ) {
  13245. builder.context.irradiance.addAssign( this.node );
  13246. }
  13247. }
  13248. const _size$5 = /*@__PURE__*/ new Vector2();
  13249. /**
  13250. * A special type of texture node which represents the data of the current viewport
  13251. * as a texture. The module extracts data from the current bound framebuffer with
  13252. * a copy operation so no extra render pass is required to produce the texture data
  13253. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  13254. * variety of effects like refractive or transmissive materials.
  13255. *
  13256. * @augments TextureNode
  13257. */
  13258. class ViewportTextureNode extends TextureNode {
  13259. static get type() {
  13260. return 'ViewportTextureNode';
  13261. }
  13262. /**
  13263. * Constructs a new viewport texture node.
  13264. *
  13265. * @param {Node} [uvNode=screenUV] - The uv node.
  13266. * @param {?Node} [levelNode=null] - The level node.
  13267. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13268. */
  13269. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  13270. let defaultFramebuffer = null;
  13271. if ( framebufferTexture === null ) {
  13272. defaultFramebuffer = new FramebufferTexture();
  13273. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  13274. framebufferTexture = defaultFramebuffer;
  13275. } else {
  13276. defaultFramebuffer = framebufferTexture;
  13277. }
  13278. super( framebufferTexture, uvNode, levelNode );
  13279. /**
  13280. * Whether to generate mipmaps or not.
  13281. *
  13282. * @type {boolean}
  13283. * @default false
  13284. */
  13285. this.generateMipmaps = false;
  13286. /**
  13287. * The reference framebuffer texture. This is used to store the framebuffer texture
  13288. * for the current render target. If the render target changes, a new framebuffer texture
  13289. * is created automatically.
  13290. *
  13291. * @type {FramebufferTexture}
  13292. * @default null
  13293. */
  13294. this.defaultFramebuffer = defaultFramebuffer;
  13295. /**
  13296. * This flag can be used for type testing.
  13297. *
  13298. * @type {boolean}
  13299. * @readonly
  13300. * @default true
  13301. */
  13302. this.isOutputTextureNode = true;
  13303. /**
  13304. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  13305. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  13306. *
  13307. * @type {string}
  13308. * @default 'frame'
  13309. */
  13310. this.updateBeforeType = NodeUpdateType.FRAME;
  13311. /**
  13312. * The framebuffer texture for the current renderer context.
  13313. *
  13314. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  13315. * @private
  13316. */
  13317. this._cacheTextures = new WeakMap();
  13318. }
  13319. /**
  13320. * This methods returns a texture for the given render target reference.
  13321. *
  13322. * To avoid rendering errors, `ViewportTextureNode` must use unique framebuffer textures
  13323. * for different render contexts.
  13324. *
  13325. * @param {?RenderTarget} [reference=null] - The render target reference.
  13326. * @return {Texture} The framebuffer texture.
  13327. */
  13328. getTextureForReference( reference = null ) {
  13329. let defaultFramebuffer;
  13330. let cacheTextures;
  13331. if ( this.referenceNode ) {
  13332. defaultFramebuffer = this.referenceNode.defaultFramebuffer;
  13333. cacheTextures = this.referenceNode._cacheTextures;
  13334. } else {
  13335. defaultFramebuffer = this.defaultFramebuffer;
  13336. cacheTextures = this._cacheTextures;
  13337. }
  13338. if ( reference === null ) {
  13339. return defaultFramebuffer;
  13340. }
  13341. if ( cacheTextures.has( reference ) === false ) {
  13342. const framebufferTexture = defaultFramebuffer.clone();
  13343. cacheTextures.set( reference, framebufferTexture );
  13344. }
  13345. return cacheTextures.get( reference );
  13346. }
  13347. updateReference( frame ) {
  13348. const renderTarget = frame.renderer.getRenderTarget();
  13349. this.value = this.getTextureForReference( renderTarget );
  13350. return this.value;
  13351. }
  13352. updateBefore( frame ) {
  13353. const renderer = frame.renderer;
  13354. const renderTarget = renderer.getRenderTarget();
  13355. if ( renderTarget === null ) {
  13356. renderer.getDrawingBufferSize( _size$5 );
  13357. } else {
  13358. _size$5.set( renderTarget.width, renderTarget.height );
  13359. }
  13360. //
  13361. const framebufferTexture = this.getTextureForReference( renderTarget );
  13362. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  13363. framebufferTexture.image.width = _size$5.width;
  13364. framebufferTexture.image.height = _size$5.height;
  13365. framebufferTexture.needsUpdate = true;
  13366. }
  13367. //
  13368. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  13369. framebufferTexture.generateMipmaps = this.generateMipmaps;
  13370. renderer.copyFramebufferToTexture( framebufferTexture );
  13371. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  13372. }
  13373. clone() {
  13374. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  13375. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  13376. return viewportTextureNode;
  13377. }
  13378. }
  13379. /**
  13380. * TSL function for creating a viewport texture node.
  13381. *
  13382. * @tsl
  13383. * @function
  13384. * @param {?Node} [uvNode=screenUV] - The uv node.
  13385. * @param {?Node} [levelNode=null] - The level node.
  13386. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13387. * @returns {ViewportTextureNode}
  13388. */
  13389. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  13390. /**
  13391. * TSL function for creating a viewport texture node with enabled mipmap generation.
  13392. *
  13393. * @tsl
  13394. * @function
  13395. * @param {?Node} [uvNode=screenUV] - The uv node.
  13396. * @param {?Node} [levelNode=null] - The level node.
  13397. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13398. * @returns {ViewportTextureNode}
  13399. */
  13400. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  13401. let _sharedDepthbuffer = null;
  13402. /**
  13403. * Represents the depth of the current viewport as a texture. This module
  13404. * can be used in combination with viewport texture to achieve effects
  13405. * that require depth evaluation.
  13406. *
  13407. * @augments ViewportTextureNode
  13408. */
  13409. class ViewportDepthTextureNode extends ViewportTextureNode {
  13410. static get type() {
  13411. return 'ViewportDepthTextureNode';
  13412. }
  13413. /**
  13414. * Constructs a new viewport depth texture node.
  13415. *
  13416. * @param {Node} [uvNode=screenUV] - The uv node.
  13417. * @param {?Node} [levelNode=null] - The level node.
  13418. */
  13419. constructor( uvNode = screenUV, levelNode = null ) {
  13420. if ( _sharedDepthbuffer === null ) {
  13421. _sharedDepthbuffer = new DepthTexture();
  13422. }
  13423. super( uvNode, levelNode, _sharedDepthbuffer );
  13424. }
  13425. /**
  13426. * Overwritten so the method always returns the unique shared
  13427. * depth texture.
  13428. *
  13429. * @return {DepthTexture} The shared depth texture.
  13430. */
  13431. getTextureForReference() {
  13432. return _sharedDepthbuffer;
  13433. }
  13434. }
  13435. /**
  13436. * TSL function for a viewport depth texture node.
  13437. *
  13438. * @tsl
  13439. * @function
  13440. * @param {?Node} [uvNode=screenUV] - The uv node.
  13441. * @param {?Node} [levelNode=null] - The level node.
  13442. * @returns {ViewportDepthTextureNode}
  13443. */
  13444. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  13445. /**
  13446. * This node offers a collection of features in context of the depth logic in the fragment shader.
  13447. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  13448. * fragment or for depth evaluation purposes.
  13449. *
  13450. * @augments Node
  13451. */
  13452. class ViewportDepthNode extends Node {
  13453. static get type() {
  13454. return 'ViewportDepthNode';
  13455. }
  13456. /**
  13457. * Constructs a new viewport depth node.
  13458. *
  13459. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  13460. * @param {?Node} [valueNode=null] - The value node.
  13461. */
  13462. constructor( scope, valueNode = null ) {
  13463. super( 'float' );
  13464. /**
  13465. * The node behaves differently depending on which scope is selected.
  13466. *
  13467. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  13468. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  13469. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  13470. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  13471. *
  13472. * @type {('depth'|'depthBase'|'linearDepth')}
  13473. */
  13474. this.scope = scope;
  13475. /**
  13476. * Can be used to define a custom depth value.
  13477. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  13478. *
  13479. * @type {?Node}
  13480. * @default null
  13481. */
  13482. this.valueNode = valueNode;
  13483. /**
  13484. * This flag can be used for type testing.
  13485. *
  13486. * @type {boolean}
  13487. * @readonly
  13488. * @default true
  13489. */
  13490. this.isViewportDepthNode = true;
  13491. }
  13492. generate( builder ) {
  13493. const { scope } = this;
  13494. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13495. return builder.getFragDepth();
  13496. }
  13497. return super.generate( builder );
  13498. }
  13499. setup( { camera } ) {
  13500. const { scope } = this;
  13501. const value = this.valueNode;
  13502. let node = null;
  13503. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13504. if ( value !== null ) {
  13505. node = depthBase().assign( value );
  13506. }
  13507. } else if ( scope === ViewportDepthNode.DEPTH ) {
  13508. if ( camera.isPerspectiveCamera ) {
  13509. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  13510. } else {
  13511. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13512. }
  13513. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  13514. if ( value !== null ) {
  13515. if ( camera.isPerspectiveCamera ) {
  13516. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  13517. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  13518. } else {
  13519. node = value;
  13520. }
  13521. } else {
  13522. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13523. }
  13524. }
  13525. return node;
  13526. }
  13527. }
  13528. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  13529. ViewportDepthNode.DEPTH = 'depth';
  13530. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  13531. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  13532. /**
  13533. * TSL function for converting a viewZ value to an orthographic depth value.
  13534. *
  13535. * @tsl
  13536. * @function
  13537. * @param {Node<float>} viewZ - The viewZ node.
  13538. * @param {Node<float>} near - The camera's near value.
  13539. * @param {Node<float>} far - The camera's far value.
  13540. * @returns {Node<float>}
  13541. */
  13542. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  13543. /**
  13544. * TSL function for converting an orthographic depth value to a viewZ value.
  13545. *
  13546. * @tsl
  13547. * @function
  13548. * @param {Node<float>} depth - The orthographic depth.
  13549. * @param {Node<float>} near - The camera's near value.
  13550. * @param {Node<float>} far - The camera's far value.
  13551. * @returns {Node<float>}
  13552. */
  13553. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  13554. /**
  13555. * TSL function for converting a viewZ value to a perspective depth value.
  13556. *
  13557. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  13558. *
  13559. * @tsl
  13560. * @function
  13561. * @param {Node<float>} viewZ - The viewZ node.
  13562. * @param {Node<float>} near - The camera's near value.
  13563. * @param {Node<float>} far - The camera's far value.
  13564. * @returns {Node<float>}
  13565. */
  13566. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  13567. /**
  13568. * TSL function for converting a perspective depth value to a viewZ value.
  13569. *
  13570. * @tsl
  13571. * @function
  13572. * @param {Node<float>} depth - The perspective depth.
  13573. * @param {Node<float>} near - The camera's near value.
  13574. * @param {Node<float>} far - The camera's far value.
  13575. * @returns {Node<float>}
  13576. */
  13577. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  13578. /**
  13579. * TSL function for converting a viewZ value to a logarithmic depth value.
  13580. *
  13581. * @tsl
  13582. * @function
  13583. * @param {Node<float>} viewZ - The viewZ node.
  13584. * @param {Node<float>} near - The camera's near value.
  13585. * @param {Node<float>} far - The camera's far value.
  13586. * @returns {Node<float>}
  13587. */
  13588. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  13589. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  13590. // The final logarithmic depth formula used here is adapted from one described in an
  13591. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  13592. // which was an improvement upon an earlier formula one described in an
  13593. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  13594. // Ulrich's formula is the following:
  13595. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  13596. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  13597. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  13598. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  13599. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  13600. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  13601. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  13602. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  13603. // be used, and ultimately Ulrich's "near plane" version was chosen.
  13604. // Outerra eventually made another improvement to their original "C-constant" variant,
  13605. // but it still does not incorporate the camera near plane (for this version,
  13606. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  13607. // Here we make 4 changes to Ulrich's formula:
  13608. // 1. Clamp the camera near plane so we don't divide by 0.
  13609. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  13610. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  13611. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  13612. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  13613. // so we do the same here, hence the 'viewZ.negate()' call.
  13614. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  13615. near = near.max( 1e-6 ).toVar();
  13616. const numerator = log2( viewZ.negate().div( near ) );
  13617. const denominator = log2( far.div( near ) );
  13618. return numerator.div( denominator );
  13619. };
  13620. /**
  13621. * TSL function for converting a logarithmic depth value to a viewZ value.
  13622. *
  13623. * @tsl
  13624. * @function
  13625. * @param {Node<float>} depth - The logarithmic depth.
  13626. * @param {Node<float>} near - The camera's near value.
  13627. * @param {Node<float>} far - The camera's far value.
  13628. * @returns {Node<float>}
  13629. */
  13630. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  13631. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  13632. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  13633. // a negative viewZ).
  13634. const exponent = depth.mul( log( far.div( near ) ) );
  13635. return float( Math.E ).pow( exponent ).mul( near ).negate();
  13636. };
  13637. /**
  13638. * TSL function for defining a value for the current fragment's depth.
  13639. *
  13640. * @tsl
  13641. * @function
  13642. * @param {Node<float>} value - The depth value to set.
  13643. * @returns {ViewportDepthNode<float>}
  13644. */
  13645. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  13646. /**
  13647. * TSL object that represents the depth value for the current fragment.
  13648. *
  13649. * @tsl
  13650. * @type {ViewportDepthNode}
  13651. */
  13652. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  13653. /**
  13654. * TSL function for converting a perspective depth value to linear depth.
  13655. *
  13656. * @tsl
  13657. * @function
  13658. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  13659. * @returns {ViewportDepthNode<float>}
  13660. */
  13661. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  13662. /**
  13663. * TSL object that represents the linear (orthographic) depth value of the current fragment
  13664. *
  13665. * @tsl
  13666. * @type {ViewportDepthNode}
  13667. */
  13668. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  13669. depth.assign = ( value ) => depthBase( value );
  13670. /**
  13671. * This node is used in {@link NodeMaterial} to setup the clipping
  13672. * which can happen hardware-accelerated (if supported) and optionally
  13673. * use alpha-to-coverage for anti-aliasing clipped edges.
  13674. *
  13675. * @augments Node
  13676. */
  13677. class ClippingNode extends Node {
  13678. static get type() {
  13679. return 'ClippingNode';
  13680. }
  13681. /**
  13682. * Constructs a new clipping node.
  13683. *
  13684. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  13685. * the selected scope influences the behavior of the node and what type of code is generated.
  13686. */
  13687. constructor( scope = ClippingNode.DEFAULT ) {
  13688. super();
  13689. /**
  13690. * The node's scope. Similar to other nodes, the selected scope influences
  13691. * the behavior of the node and what type of code is generated.
  13692. *
  13693. * @type {('default'|'hardware'|'alphaToCoverage')}
  13694. */
  13695. this.scope = scope;
  13696. }
  13697. /**
  13698. * Setups the node depending on the selected scope.
  13699. *
  13700. * @param {NodeBuilder} builder - The current node builder.
  13701. * @return {Node} The result node.
  13702. */
  13703. setup( builder ) {
  13704. super.setup( builder );
  13705. const clippingContext = builder.clippingContext;
  13706. const { intersectionPlanes, unionPlanes } = clippingContext;
  13707. this.hardwareClipping = builder.material.hardwareClipping;
  13708. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  13709. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  13710. } else if ( this.scope === ClippingNode.HARDWARE ) {
  13711. return this.setupHardwareClipping( unionPlanes, builder );
  13712. } else {
  13713. return this.setupDefault( intersectionPlanes, unionPlanes );
  13714. }
  13715. }
  13716. /**
  13717. * Setups alpha to coverage.
  13718. *
  13719. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13720. * @param {Array<Vector4>} unionPlanes - The union planes.
  13721. * @return {Node} The result node.
  13722. */
  13723. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  13724. return Fn( () => {
  13725. const distanceToPlane = float().toVar( 'distanceToPlane' );
  13726. const distanceGradient = float().toVar( 'distanceToGradient' );
  13727. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  13728. const numUnionPlanes = unionPlanes.length;
  13729. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13730. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13731. Loop( numUnionPlanes, ( { i } ) => {
  13732. const plane = clippingPlanes.element( i );
  13733. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13734. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13735. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  13736. } );
  13737. }
  13738. const numIntersectionPlanes = intersectionPlanes.length;
  13739. if ( numIntersectionPlanes > 0 ) {
  13740. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13741. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  13742. Loop( numIntersectionPlanes, ( { i } ) => {
  13743. const plane = clippingPlanes.element( i );
  13744. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13745. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13746. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  13747. } );
  13748. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  13749. }
  13750. diffuseColor.a.mulAssign( clipOpacity );
  13751. diffuseColor.a.equal( 0.0 ).discard();
  13752. } )();
  13753. }
  13754. /**
  13755. * Setups the default clipping.
  13756. *
  13757. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13758. * @param {Array<Vector4>} unionPlanes - The union planes.
  13759. * @return {Node} The result node.
  13760. */
  13761. setupDefault( intersectionPlanes, unionPlanes ) {
  13762. return Fn( () => {
  13763. const numUnionPlanes = unionPlanes.length;
  13764. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13765. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13766. Loop( numUnionPlanes, ( { i } ) => {
  13767. const plane = clippingPlanes.element( i );
  13768. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  13769. } );
  13770. }
  13771. const numIntersectionPlanes = intersectionPlanes.length;
  13772. if ( numIntersectionPlanes > 0 ) {
  13773. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13774. const clipped = bool( true ).toVar( 'clipped' );
  13775. Loop( numIntersectionPlanes, ( { i } ) => {
  13776. const plane = clippingPlanes.element( i );
  13777. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  13778. } );
  13779. clipped.discard();
  13780. }
  13781. } )();
  13782. }
  13783. /**
  13784. * Setups hardware clipping.
  13785. *
  13786. * @param {Array<Vector4>} unionPlanes - The union planes.
  13787. * @param {NodeBuilder} builder - The current node builder.
  13788. * @return {Node} The result node.
  13789. */
  13790. setupHardwareClipping( unionPlanes, builder ) {
  13791. const numUnionPlanes = unionPlanes.length;
  13792. builder.enableHardwareClipping( numUnionPlanes );
  13793. return Fn( () => {
  13794. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13795. const hw_clip_distances = builtin( builder.getClipDistance() );
  13796. Loop( numUnionPlanes, ( { i } ) => {
  13797. const plane = clippingPlanes.element( i );
  13798. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  13799. hw_clip_distances.element( i ).assign( distance );
  13800. } );
  13801. } )();
  13802. }
  13803. }
  13804. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  13805. ClippingNode.DEFAULT = 'default';
  13806. ClippingNode.HARDWARE = 'hardware';
  13807. /**
  13808. * TSL function for setting up the default clipping logic.
  13809. *
  13810. * @tsl
  13811. * @function
  13812. * @returns {ClippingNode}
  13813. */
  13814. const clipping = () => nodeObject( new ClippingNode() );
  13815. /**
  13816. * TSL function for setting up alpha to coverage.
  13817. *
  13818. * @tsl
  13819. * @function
  13820. * @returns {ClippingNode}
  13821. */
  13822. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  13823. /**
  13824. * TSL function for setting up hardware-based clipping.
  13825. *
  13826. * @tsl
  13827. * @function
  13828. * @returns {ClippingNode}
  13829. */
  13830. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  13831. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  13832. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  13833. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13834. 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 ) ) ) ) ) );
  13835. } );
  13836. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13837. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  13838. } );
  13839. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  13840. // Find the discretized derivatives of our coordinates
  13841. const maxDeriv = max$1(
  13842. length( dFdx( position.xyz ) ),
  13843. length( dFdy( position.xyz ) )
  13844. );
  13845. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  13846. // Find two nearest log-discretized noise scales
  13847. const pixScales = vec2(
  13848. exp2( floor( log2( pixScale ) ) ),
  13849. exp2( ceil( log2( pixScale ) ) )
  13850. );
  13851. // Compute alpha thresholds at our two noise scales
  13852. const alpha = vec2(
  13853. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  13854. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  13855. );
  13856. // Factor to interpolate lerp with
  13857. const lerpFactor = fract( log2( pixScale ) );
  13858. // Interpolate alpha threshold from noise at two scales
  13859. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  13860. // Pass into CDF to compute uniformly distrib threshold
  13861. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  13862. const cases = vec3(
  13863. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  13864. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  13865. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  13866. // Find our final, uniformly distributed alpha threshold (ατ)
  13867. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  13868. // Avoids ατ == 0. Could also do ατ =1-ατ
  13869. return clamp( threshold, 1.0e-6, 1.0 );
  13870. } ).setLayout( {
  13871. name: 'getAlphaHashThreshold',
  13872. type: 'float',
  13873. inputs: [
  13874. { name: 'position', type: 'vec3' }
  13875. ]
  13876. } );
  13877. /**
  13878. * An attribute node for representing vertex colors.
  13879. *
  13880. * @augments AttributeNode
  13881. */
  13882. class VertexColorNode extends AttributeNode {
  13883. static get type() {
  13884. return 'VertexColorNode';
  13885. }
  13886. /**
  13887. * Constructs a new vertex color node.
  13888. *
  13889. * @param {number} index - The attribute index.
  13890. */
  13891. constructor( index ) {
  13892. super( null, 'vec4' );
  13893. /**
  13894. * This flag can be used for type testing.
  13895. *
  13896. * @type {boolean}
  13897. * @readonly
  13898. * @default true
  13899. */
  13900. this.isVertexColorNode = true;
  13901. /**
  13902. * The attribute index to enable more than one sets of vertex colors.
  13903. *
  13904. * @type {number}
  13905. * @default 0
  13906. */
  13907. this.index = index;
  13908. }
  13909. /**
  13910. * Overwrites the default implementation by honoring the attribute index.
  13911. *
  13912. * @param {NodeBuilder} builder - The current node builder.
  13913. * @return {string} The attribute name.
  13914. */
  13915. getAttributeName( /*builder*/ ) {
  13916. const index = this.index;
  13917. return 'color' + ( index > 0 ? index : '' );
  13918. }
  13919. generate( builder ) {
  13920. const attributeName = this.getAttributeName( builder );
  13921. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  13922. let result;
  13923. if ( geometryAttribute === true ) {
  13924. result = super.generate( builder );
  13925. } else {
  13926. // Vertex color fallback should be white
  13927. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  13928. }
  13929. return result;
  13930. }
  13931. serialize( data ) {
  13932. super.serialize( data );
  13933. data.index = this.index;
  13934. }
  13935. deserialize( data ) {
  13936. super.deserialize( data );
  13937. this.index = data.index;
  13938. }
  13939. }
  13940. /**
  13941. * TSL function for creating a reference node.
  13942. *
  13943. * @tsl
  13944. * @function
  13945. * @param {number} [index=0] - The attribute index.
  13946. * @returns {VertexColorNode}
  13947. */
  13948. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  13949. /**
  13950. * Represents a "Color Burn" blend mode.
  13951. *
  13952. * It's designed to darken the base layer's colors based on the color of the blend layer.
  13953. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  13954. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  13955. *
  13956. * @tsl
  13957. * @function
  13958. * @param {Node<vec3>} base - The base color.
  13959. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  13960. * @return {Node<vec3>} The result.
  13961. */
  13962. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13963. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  13964. } ).setLayout( {
  13965. name: 'blendBurn',
  13966. type: 'vec3',
  13967. inputs: [
  13968. { name: 'base', type: 'vec3' },
  13969. { name: 'blend', type: 'vec3' }
  13970. ]
  13971. } );
  13972. /**
  13973. * Represents a "Color Dodge" blend mode.
  13974. *
  13975. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  13976. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  13977. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  13978. *
  13979. * @tsl
  13980. * @function
  13981. * @param {Node<vec3>} base - The base color.
  13982. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13983. * @return {Node<vec3>} The result.
  13984. */
  13985. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13986. return min$1( base.div( blend.oneMinus() ), 1.0 );
  13987. } ).setLayout( {
  13988. name: 'blendDodge',
  13989. type: 'vec3',
  13990. inputs: [
  13991. { name: 'base', type: 'vec3' },
  13992. { name: 'blend', type: 'vec3' }
  13993. ]
  13994. } );
  13995. /**
  13996. * Represents a "Screen" blend mode.
  13997. *
  13998. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  13999. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  14000. * effects.
  14001. *
  14002. * @tsl
  14003. * @function
  14004. * @param {Node<vec3>} base - The base color.
  14005. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  14006. * @return {Node<vec3>} The result.
  14007. */
  14008. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14009. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  14010. } ).setLayout( {
  14011. name: 'blendScreen',
  14012. type: 'vec3',
  14013. inputs: [
  14014. { name: 'base', type: 'vec3' },
  14015. { name: 'blend', type: 'vec3' }
  14016. ]
  14017. } );
  14018. /**
  14019. * Represents a "Overlay" blend mode.
  14020. *
  14021. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  14022. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  14023. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  14024. *
  14025. * @tsl
  14026. * @function
  14027. * @param {Node<vec3>} base - The base color.
  14028. * @param {Node<vec3>} blend - The blend color
  14029. * @return {Node<vec3>} The result.
  14030. */
  14031. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14032. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  14033. } ).setLayout( {
  14034. name: 'blendOverlay',
  14035. type: 'vec3',
  14036. inputs: [
  14037. { name: 'base', type: 'vec3' },
  14038. { name: 'blend', type: 'vec3' }
  14039. ]
  14040. } );
  14041. /**
  14042. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  14043. * It assumes both input colors have non-premultiplied alpha.
  14044. *
  14045. * @tsl
  14046. * @function
  14047. * @param {Node<vec4>} base - The base color.
  14048. * @param {Node<vec4>} blend - The blend color
  14049. * @return {Node<vec4>} The result.
  14050. */
  14051. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14052. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  14053. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  14054. } ).setLayout( {
  14055. name: 'blendColor',
  14056. type: 'vec4',
  14057. inputs: [
  14058. { name: 'base', type: 'vec4' },
  14059. { name: 'blend', type: 'vec4' }
  14060. ]
  14061. } );
  14062. /**
  14063. * Premultiplies the RGB channels of a color by its alpha channel.
  14064. *
  14065. * This function is useful for converting a non-premultiplied alpha color
  14066. * into a premultiplied alpha format, where the RGB values are scaled
  14067. * by the alpha value. Premultiplied alpha is often used in graphics
  14068. * rendering for certain operations, such as compositing and image processing.
  14069. *
  14070. * @tsl
  14071. * @function
  14072. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  14073. * @return {Node<vec4>} The color with premultiplied alpha.
  14074. */
  14075. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  14076. return vec4( color.rgb.mul( color.a ), color.a );
  14077. }, { color: 'vec4', return: 'vec4' } );
  14078. /**
  14079. * Unpremultiplies the RGB channels of a color by its alpha channel.
  14080. *
  14081. * This function is useful for converting a premultiplied alpha color
  14082. * back into a non-premultiplied alpha format, where the RGB values are
  14083. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  14084. * rendering for certain operations, such as compositing and image processing.
  14085. *
  14086. * @tsl
  14087. * @function
  14088. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  14089. * @return {Node<vec4>} The color with non-premultiplied alpha.
  14090. */
  14091. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  14092. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  14093. return vec4( color.rgb.div( color.a ), color.a );
  14094. }, { color: 'vec4', return: 'vec4' } );
  14095. // Deprecated
  14096. /**
  14097. * @tsl
  14098. * @function
  14099. * @deprecated since r171. Use {@link blendBurn} instead.
  14100. *
  14101. * @param {...any} params
  14102. * @returns {Function}
  14103. */
  14104. const burn = ( ...params ) => { // @deprecated, r171
  14105. warn( 'TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  14106. return blendBurn( params );
  14107. };
  14108. /**
  14109. * @tsl
  14110. * @function
  14111. * @deprecated since r171. Use {@link blendDodge} instead.
  14112. *
  14113. * @param {...any} params
  14114. * @returns {Function}
  14115. */
  14116. const dodge = ( ...params ) => { // @deprecated, r171
  14117. warn( 'TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  14118. return blendDodge( params );
  14119. };
  14120. /**
  14121. * @tsl
  14122. * @function
  14123. * @deprecated since r171. Use {@link blendScreen} instead.
  14124. *
  14125. * @param {...any} params
  14126. * @returns {Function}
  14127. */
  14128. const screen = ( ...params ) => { // @deprecated, r171
  14129. warn( 'TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  14130. return blendScreen( params );
  14131. };
  14132. /**
  14133. * @tsl
  14134. * @function
  14135. * @deprecated since r171. Use {@link blendOverlay} instead.
  14136. *
  14137. * @param {...any} params
  14138. * @returns {Function}
  14139. */
  14140. const overlay = ( ...params ) => { // @deprecated, r171
  14141. warn( 'TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  14142. return blendOverlay( params );
  14143. };
  14144. /**
  14145. * Base class for all node materials.
  14146. *
  14147. * @augments Material
  14148. */
  14149. class NodeMaterial extends Material {
  14150. static get type() {
  14151. return 'NodeMaterial';
  14152. }
  14153. /**
  14154. * Represents the type of the node material.
  14155. *
  14156. * @type {string}
  14157. */
  14158. get type() {
  14159. return this.constructor.type;
  14160. }
  14161. set type( _value ) { /* */ }
  14162. /**
  14163. * Constructs a new node material.
  14164. */
  14165. constructor() {
  14166. super();
  14167. /**
  14168. * This flag can be used for type testing.
  14169. *
  14170. * @type {boolean}
  14171. * @readonly
  14172. * @default true
  14173. */
  14174. this.isNodeMaterial = true;
  14175. /**
  14176. * Whether this material is affected by fog or not.
  14177. *
  14178. * @type {boolean}
  14179. * @default true
  14180. */
  14181. this.fog = true;
  14182. /**
  14183. * Whether this material is affected by lights or not.
  14184. *
  14185. * @type {boolean}
  14186. * @default false
  14187. */
  14188. this.lights = false;
  14189. /**
  14190. * Whether this material uses hardware clipping or not.
  14191. * This property is managed by the engine and should not be
  14192. * modified by apps.
  14193. *
  14194. * @type {boolean}
  14195. * @default false
  14196. */
  14197. this.hardwareClipping = false;
  14198. /**
  14199. * Node materials which set their `lights` property to `true`
  14200. * are affected by all lights of the scene. Sometimes selective
  14201. * lighting is wanted which means only _some_ lights in the scene
  14202. * affect a material. This can be achieved by creating an instance
  14203. * of {@link LightsNode} with a list of selective
  14204. * lights and assign the node to this property.
  14205. *
  14206. * ```js
  14207. * const customLightsNode = lights( [ light1, light2 ] );
  14208. * material.lightsNode = customLightsNode;
  14209. * ```
  14210. *
  14211. * @type {?LightsNode}
  14212. * @default null
  14213. */
  14214. this.lightsNode = null;
  14215. /**
  14216. * The environment of node materials can be defined by an environment
  14217. * map assigned to the `envMap` property or by `Scene.environment`
  14218. * if the node material is a PBR material. This node property allows to overwrite
  14219. * the default behavior and define the environment with a custom node.
  14220. *
  14221. * ```js
  14222. * material.envNode = pmremTexture( renderTarget.texture );
  14223. * ```
  14224. *
  14225. * @type {?Node<vec3>}
  14226. * @default null
  14227. */
  14228. this.envNode = null;
  14229. /**
  14230. * The lighting of node materials might be influenced by ambient occlusion.
  14231. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  14232. * and the respective `aoMapIntensity`. This node property allows to overwrite
  14233. * the default and define the ambient occlusion with a custom node instead.
  14234. *
  14235. * If you don't want to overwrite the diffuse color but modify the existing
  14236. * values instead, use {@link materialAO}.
  14237. *
  14238. * @type {?Node<float>}
  14239. * @default null
  14240. */
  14241. this.aoNode = null;
  14242. /**
  14243. * The diffuse color of node materials is by default inferred from the
  14244. * `color` and `map` properties. This node property allows to overwrite the default
  14245. * and define the diffuse color with a node instead.
  14246. *
  14247. * ```js
  14248. * material.colorNode = color( 0xff0000 ); // define red color
  14249. * ```
  14250. *
  14251. * If you don't want to overwrite the diffuse color but modify the existing
  14252. * values instead, use {@link materialColor}.
  14253. *
  14254. * ```js
  14255. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  14256. * ```
  14257. *
  14258. * @type {?Node<vec3>}
  14259. * @default null
  14260. */
  14261. this.colorNode = null;
  14262. /**
  14263. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  14264. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  14265. * and define the normals with a node instead.
  14266. *
  14267. * If you don't want to overwrite the normals but modify the existing values instead,
  14268. * use {@link materialNormal}.
  14269. *
  14270. * @type {?Node<vec3>}
  14271. * @default null
  14272. */
  14273. this.normalNode = null;
  14274. /**
  14275. * The opacity of node materials is by default inferred from the `opacity`
  14276. * and `alphaMap` properties. This node property allows to overwrite the default
  14277. * and define the opacity with a node instead.
  14278. *
  14279. * If you don't want to overwrite the opacity but modify the existing
  14280. * value instead, use {@link materialOpacity}.
  14281. *
  14282. * @type {?Node<float>}
  14283. * @default null
  14284. */
  14285. this.opacityNode = null;
  14286. /**
  14287. * This node can be used to implement a variety of filter-like effects. The idea is
  14288. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  14289. * to create an arbitrary effect and then assign the node composition to this property.
  14290. * Everything behind the object using this material will now be affected by a filter.
  14291. *
  14292. * ```js
  14293. * const material = new NodeMaterial()
  14294. * material.transparent = true;
  14295. *
  14296. * // everything behind the object will be monochromatic
  14297. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  14298. * ```
  14299. *
  14300. * Backdrop computations are part of the lighting so only lit materials can use this property.
  14301. *
  14302. * @type {?Node<vec3>}
  14303. * @default null
  14304. */
  14305. this.backdropNode = null;
  14306. /**
  14307. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  14308. *
  14309. * @type {?Node<float>}
  14310. * @default null
  14311. */
  14312. this.backdropAlphaNode = null;
  14313. /**
  14314. * The alpha test of node materials is by default inferred from the `alphaTest`
  14315. * property. This node property allows to overwrite the default and define the
  14316. * alpha test with a node instead.
  14317. *
  14318. * If you don't want to overwrite the alpha test but modify the existing
  14319. * value instead, use {@link materialAlphaTest}.
  14320. *
  14321. * @type {?Node<float>}
  14322. * @default null
  14323. */
  14324. this.alphaTestNode = null;
  14325. /**
  14326. * Discards the fragment if the mask value is `false`.
  14327. *
  14328. * @type {?Node<bool>}
  14329. * @default null
  14330. */
  14331. this.maskNode = null;
  14332. /**
  14333. * The local vertex positions are computed based on multiple factors like the
  14334. * attribute data, morphing or skinning. This node property allows to overwrite
  14335. * the default and define local vertex positions with nodes instead.
  14336. *
  14337. * If you don't want to overwrite the vertex positions but modify the existing
  14338. * values instead, use {@link positionLocal}.
  14339. *
  14340. *```js
  14341. * material.positionNode = positionLocal.add( displace );
  14342. * ```
  14343. *
  14344. * @type {?Node<vec3>}
  14345. * @default null
  14346. */
  14347. this.positionNode = null;
  14348. /**
  14349. * This node property is intended for logic which modifies geometry data once or per animation step.
  14350. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  14351. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  14352. * can be implemented.
  14353. *
  14354. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  14355. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  14356. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  14357. * eventually assigned to `geometryNode`.
  14358. *
  14359. * @type {?Function}
  14360. * @default null
  14361. */
  14362. this.geometryNode = null;
  14363. /**
  14364. * Allows to overwrite depth values in the fragment shader.
  14365. *
  14366. * @type {?Node<float>}
  14367. * @default null
  14368. */
  14369. this.depthNode = null;
  14370. /**
  14371. * Allows to overwrite the position used for shadow map rendering which
  14372. * is by default {@link positionWorld}, the vertex position
  14373. * in world space.
  14374. *
  14375. * @type {?Node<float>}
  14376. * @default null
  14377. */
  14378. this.receivedShadowPositionNode = null;
  14379. /**
  14380. * Allows to overwrite the geometry position used for shadow map projection which
  14381. * is by default {@link positionLocal}, the vertex position in local space.
  14382. *
  14383. * @type {?Node<float>}
  14384. * @default null
  14385. */
  14386. this.castShadowPositionNode = null;
  14387. /**
  14388. * This node can be used to influence how an object using this node material
  14389. * receive shadows.
  14390. *
  14391. * ```js
  14392. * const totalShadows = float( 1 ).toVar();
  14393. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  14394. * totalShadows.mulAssign( shadow );
  14395. * //return float( 1 ); // bypass received shadows
  14396. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  14397. * } );
  14398. *
  14399. * @type {?(Function|FunctionNode<vec4>)}
  14400. * @default null
  14401. */
  14402. this.receivedShadowNode = null;
  14403. /**
  14404. * This node can be used to influence how an object using this node material
  14405. * casts shadows. To apply a color to shadows, you can simply do:
  14406. *
  14407. * ```js
  14408. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  14409. * ```
  14410. *
  14411. * Which can be nice to fake colored shadows of semi-transparent objects. It
  14412. * is also common to use the property with `Fn` function so checks are performed
  14413. * per fragment.
  14414. *
  14415. * ```js
  14416. * materialCustomShadow.castShadowNode = Fn( () => {
  14417. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  14418. * return materialColor;
  14419. * } )();
  14420. * ```
  14421. *
  14422. * @type {?Node<vec4>}
  14423. * @default null
  14424. */
  14425. this.castShadowNode = null;
  14426. /**
  14427. * This node can be used to define the final output of the material.
  14428. *
  14429. * TODO: Explain the differences to `fragmentNode`.
  14430. *
  14431. * @type {?Node<vec4>}
  14432. * @default null
  14433. */
  14434. this.outputNode = null;
  14435. /**
  14436. * MRT configuration is done on renderer or pass level. This node allows to
  14437. * overwrite what values are written into MRT targets on material level. This
  14438. * can be useful for implementing selective FX features that should only affect
  14439. * specific objects.
  14440. *
  14441. * @type {?MRTNode}
  14442. * @default null
  14443. */
  14444. this.mrtNode = null;
  14445. /**
  14446. * This node property can be used if you need complete freedom in implementing
  14447. * the fragment shader. Assigning a node will replace the built-in material
  14448. * logic used in the fragment stage.
  14449. *
  14450. * @type {?Node<vec4>}
  14451. * @default null
  14452. */
  14453. this.fragmentNode = null;
  14454. /**
  14455. * This node property can be used if you need complete freedom in implementing
  14456. * the vertex shader. Assigning a node will replace the built-in material logic
  14457. * used in the vertex stage.
  14458. *
  14459. * @type {?Node<vec4>}
  14460. * @default null
  14461. */
  14462. this.vertexNode = null;
  14463. /**
  14464. * This node can be used as a global context management component for this material.
  14465. *
  14466. * @type {?ContextNode}
  14467. * @default null
  14468. */
  14469. this.contextNode = null;
  14470. // Deprecated properties
  14471. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  14472. get: () => {
  14473. return this.receivedShadowPositionNode;
  14474. },
  14475. set: ( value ) => {
  14476. warn( 'NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  14477. this.receivedShadowPositionNode = value;
  14478. }
  14479. } );
  14480. }
  14481. /**
  14482. * Returns an array of child nodes for this material.
  14483. *
  14484. * @private
  14485. * @returns {Array<{property: string, childNode: Node}>}
  14486. */
  14487. _getNodeChildren() {
  14488. const children = [];
  14489. for ( const property of Object.getOwnPropertyNames( this ) ) {
  14490. if ( property.startsWith( '_' ) === true ) continue;
  14491. const object = this[ property ];
  14492. if ( object && object.isNode === true ) {
  14493. children.push( { property, childNode: object } );
  14494. }
  14495. }
  14496. return children;
  14497. }
  14498. /**
  14499. * Allows to define a custom cache key that influence the material key computation
  14500. * for render objects.
  14501. *
  14502. * @return {string} The custom cache key.
  14503. */
  14504. customProgramCacheKey() {
  14505. const values = [];
  14506. for ( const { property, childNode } of this._getNodeChildren() ) {
  14507. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey() );
  14508. }
  14509. return this.type + hashArray( values );
  14510. }
  14511. /**
  14512. * Builds this material with the given node builder.
  14513. *
  14514. * @param {NodeBuilder} builder - The current node builder.
  14515. */
  14516. build( builder ) {
  14517. this.setup( builder );
  14518. }
  14519. /**
  14520. * Setups a node material observer with the given builder.
  14521. *
  14522. * @param {NodeBuilder} builder - The current node builder.
  14523. * @return {NodeMaterialObserver} The node material observer.
  14524. */
  14525. setupObserver( builder ) {
  14526. return new NodeMaterialObserver( builder );
  14527. }
  14528. /**
  14529. * Setups the vertex and fragment stage of this node material.
  14530. *
  14531. * @param {NodeBuilder} builder - The current node builder.
  14532. */
  14533. setup( builder ) {
  14534. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  14535. builder.context.setupPositionView = () => this.setupPositionView( builder );
  14536. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  14537. const renderer = builder.renderer;
  14538. const renderTarget = renderer.getRenderTarget();
  14539. // < CONTEXT >
  14540. if ( renderer.contextNode.isContextNode === true ) {
  14541. builder.context = { ...builder.context, ...renderer.contextNode.getFlowContextData() };
  14542. } else {
  14543. error( 'NodeMaterial: "renderer.contextNode" must be an instance of `context()`.' );
  14544. }
  14545. if ( this.contextNode !== null ) {
  14546. if ( this.contextNode.isContextNode === true ) {
  14547. builder.context = { ...builder.context, ...this.contextNode.getFlowContextData() };
  14548. } else {
  14549. error( 'NodeMaterial: "material.contextNode" must be an instance of `context()`.' );
  14550. }
  14551. }
  14552. // < VERTEX STAGE >
  14553. builder.addStack();
  14554. const mvp = subBuild( this.setupVertex( builder ), 'VERTEX' );
  14555. const vertexNode = this.vertexNode || mvp;
  14556. builder.stack.outputNode = vertexNode;
  14557. this.setupHardwareClipping( builder );
  14558. if ( this.geometryNode !== null ) {
  14559. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  14560. }
  14561. builder.addFlow( 'vertex', builder.removeStack() );
  14562. // < FRAGMENT STAGE >
  14563. builder.addStack();
  14564. let resultNode;
  14565. const clippingNode = this.setupClipping( builder );
  14566. if ( this.depthWrite === true || this.depthTest === true ) {
  14567. // only write depth if depth buffer is configured
  14568. if ( renderTarget !== null ) {
  14569. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  14570. } else {
  14571. if ( renderer.depth === true ) this.setupDepth( builder );
  14572. }
  14573. }
  14574. if ( this.fragmentNode === null ) {
  14575. this.setupDiffuseColor( builder );
  14576. this.setupVariants( builder );
  14577. const outgoingLightNode = this.setupLighting( builder );
  14578. if ( clippingNode !== null ) builder.stack.addToStack( clippingNode );
  14579. // force unsigned floats - useful for RenderTargets
  14580. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  14581. resultNode = this.setupOutput( builder, basicOutput );
  14582. // OUTPUT NODE
  14583. output.assign( resultNode );
  14584. //
  14585. const isCustomOutput = this.outputNode !== null;
  14586. if ( isCustomOutput ) resultNode = this.outputNode;
  14587. //
  14588. if ( builder.context.getOutput ) {
  14589. resultNode = builder.context.getOutput( resultNode, builder );
  14590. }
  14591. // MRT
  14592. if ( renderTarget !== null ) {
  14593. const mrt = renderer.getMRT();
  14594. const materialMRT = this.mrtNode;
  14595. if ( mrt !== null ) {
  14596. if ( isCustomOutput ) output.assign( resultNode );
  14597. resultNode = mrt;
  14598. if ( materialMRT !== null ) {
  14599. resultNode = mrt.merge( materialMRT );
  14600. }
  14601. } else if ( materialMRT !== null ) {
  14602. resultNode = materialMRT;
  14603. }
  14604. }
  14605. } else {
  14606. let fragmentNode = this.fragmentNode;
  14607. if ( fragmentNode.isOutputStructNode !== true ) {
  14608. fragmentNode = vec4( fragmentNode );
  14609. }
  14610. resultNode = this.setupOutput( builder, fragmentNode );
  14611. }
  14612. builder.stack.outputNode = resultNode;
  14613. builder.addFlow( 'fragment', builder.removeStack() );
  14614. // < OBSERVER >
  14615. builder.observer = this.setupObserver( builder );
  14616. }
  14617. /**
  14618. * Setups the clipping node.
  14619. *
  14620. * @param {NodeBuilder} builder - The current node builder.
  14621. * @return {ClippingNode} The clipping node.
  14622. */
  14623. setupClipping( builder ) {
  14624. if ( builder.clippingContext === null ) return null;
  14625. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  14626. let result = null;
  14627. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  14628. const samples = builder.renderer.currentSamples;
  14629. if ( this.alphaToCoverage && samples > 1 ) {
  14630. // to be added to flow when the color/alpha value has been determined
  14631. result = clippingAlpha();
  14632. } else {
  14633. builder.stack.addToStack( clipping() );
  14634. }
  14635. }
  14636. return result;
  14637. }
  14638. /**
  14639. * Setups the hardware clipping if available on the current device.
  14640. *
  14641. * @param {NodeBuilder} builder - The current node builder.
  14642. */
  14643. setupHardwareClipping( builder ) {
  14644. this.hardwareClipping = false;
  14645. if ( builder.clippingContext === null ) return;
  14646. const candidateCount = builder.clippingContext.unionPlanes.length;
  14647. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  14648. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  14649. builder.stack.addToStack( hardwareClipping() );
  14650. this.hardwareClipping = true;
  14651. }
  14652. return;
  14653. }
  14654. /**
  14655. * Setups the depth of this material.
  14656. *
  14657. * @param {NodeBuilder} builder - The current node builder.
  14658. */
  14659. setupDepth( builder ) {
  14660. const { renderer, camera } = builder;
  14661. // Depth
  14662. let depthNode = this.depthNode;
  14663. if ( depthNode === null ) {
  14664. const mrt = renderer.getMRT();
  14665. if ( mrt && mrt.has( 'depth' ) ) {
  14666. depthNode = mrt.get( 'depth' );
  14667. } else if ( renderer.logarithmicDepthBuffer === true ) {
  14668. if ( camera.isPerspectiveCamera ) {
  14669. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  14670. } else {
  14671. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14672. }
  14673. }
  14674. }
  14675. if ( depthNode !== null ) {
  14676. depth.assign( depthNode ).toStack();
  14677. }
  14678. }
  14679. /**
  14680. * Setups the position node in view space. This method exists
  14681. * so derived node materials can modify the implementation e.g. sprite materials.
  14682. *
  14683. * @param {NodeBuilder} builder - The current node builder.
  14684. * @return {Node<vec3>} The position in view space.
  14685. */
  14686. setupPositionView( /*builder*/ ) {
  14687. return modelViewMatrix.mul( positionLocal ).xyz;
  14688. }
  14689. /**
  14690. * Setups the position in clip space.
  14691. *
  14692. * @param {NodeBuilder} builder - The current node builder.
  14693. * @return {Node<vec4>} The position in view space.
  14694. */
  14695. setupModelViewProjection( /*builder*/ ) {
  14696. return cameraProjectionMatrix.mul( positionView );
  14697. }
  14698. /**
  14699. * Setups the logic for the vertex stage.
  14700. *
  14701. * @param {NodeBuilder} builder - The current node builder.
  14702. * @return {Node<vec4>} The position in clip space.
  14703. */
  14704. setupVertex( builder ) {
  14705. builder.addStack();
  14706. this.setupPosition( builder );
  14707. builder.context.vertex = builder.removeStack();
  14708. return modelViewProjection;
  14709. }
  14710. /**
  14711. * Setups the computation of the position in local space.
  14712. *
  14713. * @param {NodeBuilder} builder - The current node builder.
  14714. * @return {Node<vec3>} The position in local space.
  14715. */
  14716. setupPosition( builder ) {
  14717. const { object, geometry } = builder;
  14718. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  14719. morphReference( object ).toStack();
  14720. }
  14721. if ( object.isSkinnedMesh === true ) {
  14722. skinning( object ).toStack();
  14723. }
  14724. if ( this.displacementMap ) {
  14725. const displacementMap = materialReference( 'displacementMap', 'texture' );
  14726. const displacementScale = materialReference( 'displacementScale', 'float' );
  14727. const displacementBias = materialReference( 'displacementBias', 'float' );
  14728. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  14729. }
  14730. if ( object.isBatchedMesh ) {
  14731. batch( object ).toStack();
  14732. }
  14733. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  14734. instancedMesh( object ).toStack();
  14735. }
  14736. if ( this.positionNode !== null ) {
  14737. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  14738. }
  14739. return positionLocal;
  14740. }
  14741. /**
  14742. * Setups the computation of the material's diffuse color.
  14743. *
  14744. * @param {NodeBuilder} builder - The current node builder.
  14745. * @param {BufferGeometry} geometry - The geometry.
  14746. */
  14747. setupDiffuseColor( builder ) {
  14748. const { object, geometry } = builder;
  14749. // MASK
  14750. if ( this.maskNode !== null ) {
  14751. // Discard if the mask is `false`
  14752. bool( this.maskNode ).not().discard();
  14753. }
  14754. // COLOR
  14755. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  14756. // VERTEX COLORS
  14757. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  14758. colorNode = colorNode.mul( vertexColor() );
  14759. }
  14760. // INSTANCED COLORS
  14761. if ( object.instanceColor ) {
  14762. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  14763. colorNode = instanceColor.mul( colorNode );
  14764. }
  14765. if ( object.isBatchedMesh && object._colorsTexture ) {
  14766. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  14767. colorNode = batchColor.mul( colorNode );
  14768. }
  14769. // DIFFUSE COLOR
  14770. diffuseColor.assign( colorNode );
  14771. // OPACITY
  14772. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14773. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  14774. // ALPHA TEST
  14775. let alphaTestNode = null;
  14776. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  14777. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  14778. if ( this.alphaToCoverage === true ) {
  14779. diffuseColor.a = smoothstep( alphaTestNode, alphaTestNode.add( fwidth( diffuseColor.a ) ), diffuseColor.a );
  14780. diffuseColor.a.lessThanEqual( 0 ).discard();
  14781. } else {
  14782. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  14783. }
  14784. }
  14785. // ALPHA HASH
  14786. if ( this.alphaHash === true ) {
  14787. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  14788. }
  14789. // OPAQUE
  14790. if ( builder.isOpaque() ) {
  14791. diffuseColor.a.assign( 1.0 );
  14792. }
  14793. }
  14794. /**
  14795. * Abstract interface method that can be implemented by derived materials
  14796. * to setup material-specific node variables.
  14797. *
  14798. * @abstract
  14799. * @param {NodeBuilder} builder - The current node builder.
  14800. */
  14801. setupVariants( /*builder*/ ) {
  14802. // Interface function.
  14803. }
  14804. /**
  14805. * Setups the outgoing light node variable
  14806. *
  14807. * @return {Node<vec3>} The outgoing light node.
  14808. */
  14809. setupOutgoingLight() {
  14810. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  14811. }
  14812. /**
  14813. * Setups the normal node from the material.
  14814. *
  14815. * @return {Node<vec3>} The normal node.
  14816. */
  14817. setupNormal() {
  14818. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  14819. }
  14820. /**
  14821. * Setups the environment node from the material.
  14822. *
  14823. * @param {NodeBuilder} builder - The current node builder.
  14824. * @return {Node<vec4>} The environment node.
  14825. */
  14826. setupEnvironment( /*builder*/ ) {
  14827. let node = null;
  14828. if ( this.envNode ) {
  14829. node = this.envNode;
  14830. } else if ( this.envMap ) {
  14831. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  14832. }
  14833. return node;
  14834. }
  14835. /**
  14836. * Setups the light map node from the material.
  14837. *
  14838. * @param {NodeBuilder} builder - The current node builder.
  14839. * @return {Node<vec3>} The light map node.
  14840. */
  14841. setupLightMap( builder ) {
  14842. let node = null;
  14843. if ( builder.material.lightMap ) {
  14844. node = new IrradianceNode( materialLightMap );
  14845. }
  14846. return node;
  14847. }
  14848. /**
  14849. * Setups the lights node based on the scene, environment and material.
  14850. *
  14851. * @param {NodeBuilder} builder - The current node builder.
  14852. * @return {LightsNode} The lights node.
  14853. */
  14854. setupLights( builder ) {
  14855. const materialLightsNode = [];
  14856. //
  14857. const envNode = this.setupEnvironment( builder );
  14858. if ( envNode && envNode.isLightingNode ) {
  14859. materialLightsNode.push( envNode );
  14860. }
  14861. const lightMapNode = this.setupLightMap( builder );
  14862. if ( lightMapNode && lightMapNode.isLightingNode ) {
  14863. materialLightsNode.push( lightMapNode );
  14864. }
  14865. let aoNode = builder.context.ao || null;
  14866. if ( this.aoNode !== null || builder.material.aoMap ) {
  14867. const mtlAO = this.aoNode !== null ? this.aoNode : materialAO;
  14868. aoNode = aoNode !== null ? aoNode.mul( mtlAO ) : mtlAO;
  14869. }
  14870. if ( aoNode !== null ) {
  14871. materialLightsNode.push( new AONode( aoNode ) );
  14872. }
  14873. let lightsN = this.lightsNode || builder.lightsNode;
  14874. if ( materialLightsNode.length > 0 ) {
  14875. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  14876. }
  14877. return lightsN;
  14878. }
  14879. /**
  14880. * This method should be implemented by most derived materials
  14881. * since it defines the material's lighting model.
  14882. *
  14883. * @abstract
  14884. * @param {NodeBuilder} builder - The current node builder.
  14885. * @return {LightingModel} The lighting model.
  14886. */
  14887. setupLightingModel( /*builder*/ ) {
  14888. // Interface function.
  14889. }
  14890. /**
  14891. * Setups the outgoing light node.
  14892. *
  14893. * @param {NodeBuilder} builder - The current node builder.
  14894. * @return {Node<vec3>} The outgoing light node.
  14895. */
  14896. setupLighting( builder ) {
  14897. const { material } = builder;
  14898. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  14899. // OUTGOING LIGHT
  14900. const lights = this.lights === true || this.lightsNode !== null;
  14901. const lightsNode = lights ? this.setupLights( builder ) : null;
  14902. let outgoingLightNode = this.setupOutgoingLight( builder );
  14903. if ( lightsNode && lightsNode.getScope().hasLights ) {
  14904. const lightingModel = this.setupLightingModel( builder ) || null;
  14905. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  14906. } else if ( backdropNode !== null ) {
  14907. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  14908. }
  14909. // EMISSIVE
  14910. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  14911. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  14912. outgoingLightNode = outgoingLightNode.add( emissive );
  14913. }
  14914. return outgoingLightNode;
  14915. }
  14916. /**
  14917. * Setup the fog.
  14918. *
  14919. * @param {NodeBuilder} builder - The current node builder.
  14920. * @param {Node<vec4>} outputNode - The existing output node.
  14921. * @return {Node<vec4>} The output node.
  14922. */
  14923. setupFog( builder, outputNode ) {
  14924. const fogNode = builder.fogNode;
  14925. if ( fogNode ) {
  14926. output.assign( outputNode );
  14927. outputNode = vec4( fogNode.toVar() );
  14928. }
  14929. return outputNode;
  14930. }
  14931. /**
  14932. * Setups premultiplied alpha.
  14933. *
  14934. * @param {NodeBuilder} builder - The current node builder.
  14935. * @param {Node<vec4>} outputNode - The existing output node.
  14936. * @return {Node<vec4>} The output node.
  14937. */
  14938. setupPremultipliedAlpha( builder, outputNode ) {
  14939. return premultiplyAlpha( outputNode );
  14940. }
  14941. /**
  14942. * Setups the output node.
  14943. *
  14944. * @param {NodeBuilder} builder - The current node builder.
  14945. * @param {Node<vec4>} outputNode - The existing output node.
  14946. * @return {Node<vec4>} The output node.
  14947. */
  14948. setupOutput( builder, outputNode ) {
  14949. // FOG
  14950. if ( this.fog === true ) {
  14951. outputNode = this.setupFog( builder, outputNode );
  14952. }
  14953. // PREMULTIPLIED ALPHA
  14954. if ( this.premultipliedAlpha === true ) {
  14955. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  14956. }
  14957. return outputNode;
  14958. }
  14959. /**
  14960. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  14961. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  14962. * defining all material properties of the classic type in the node type.
  14963. *
  14964. * @param {Material} material - The material to copy properties with their values to this node material.
  14965. */
  14966. setDefaultValues( material ) {
  14967. // This approach is to reuse the native refreshUniforms*
  14968. // and turn available the use of features like transmission and environment in core
  14969. for ( const property in material ) {
  14970. const value = material[ property ];
  14971. if ( this[ property ] === undefined ) {
  14972. this[ property ] = value;
  14973. if ( value && value.clone ) this[ property ] = value.clone();
  14974. }
  14975. }
  14976. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  14977. for ( const key in descriptors ) {
  14978. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  14979. descriptors[ key ].get !== undefined ) {
  14980. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  14981. }
  14982. }
  14983. }
  14984. /**
  14985. * Serializes this material to JSON.
  14986. *
  14987. * @param {?(Object|string)} meta - The meta information for serialization.
  14988. * @return {Object} The serialized node.
  14989. */
  14990. toJSON( meta ) {
  14991. const isRoot = ( meta === undefined || typeof meta === 'string' );
  14992. if ( isRoot ) {
  14993. meta = {
  14994. textures: {},
  14995. images: {},
  14996. nodes: {}
  14997. };
  14998. }
  14999. const data = Material.prototype.toJSON.call( this, meta );
  15000. data.inputNodes = {};
  15001. for ( const { property, childNode } of this._getNodeChildren() ) {
  15002. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  15003. }
  15004. // TODO: Copied from Object3D.toJSON
  15005. function extractFromCache( cache ) {
  15006. const values = [];
  15007. for ( const key in cache ) {
  15008. const data = cache[ key ];
  15009. delete data.metadata;
  15010. values.push( data );
  15011. }
  15012. return values;
  15013. }
  15014. if ( isRoot ) {
  15015. const textures = extractFromCache( meta.textures );
  15016. const images = extractFromCache( meta.images );
  15017. const nodes = extractFromCache( meta.nodes );
  15018. if ( textures.length > 0 ) data.textures = textures;
  15019. if ( images.length > 0 ) data.images = images;
  15020. if ( nodes.length > 0 ) data.nodes = nodes;
  15021. }
  15022. return data;
  15023. }
  15024. /**
  15025. * Copies the properties of the given node material to this instance.
  15026. *
  15027. * @param {NodeMaterial} source - The material to copy.
  15028. * @return {NodeMaterial} A reference to this node material.
  15029. */
  15030. copy( source ) {
  15031. this.lightsNode = source.lightsNode;
  15032. this.envNode = source.envNode;
  15033. this.aoNode = source.aoNode;
  15034. this.colorNode = source.colorNode;
  15035. this.normalNode = source.normalNode;
  15036. this.opacityNode = source.opacityNode;
  15037. this.backdropNode = source.backdropNode;
  15038. this.backdropAlphaNode = source.backdropAlphaNode;
  15039. this.alphaTestNode = source.alphaTestNode;
  15040. this.maskNode = source.maskNode;
  15041. this.positionNode = source.positionNode;
  15042. this.geometryNode = source.geometryNode;
  15043. this.depthNode = source.depthNode;
  15044. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  15045. this.castShadowPositionNode = source.castShadowPositionNode;
  15046. this.receivedShadowNode = source.receivedShadowNode;
  15047. this.castShadowNode = source.castShadowNode;
  15048. this.outputNode = source.outputNode;
  15049. this.mrtNode = source.mrtNode;
  15050. this.fragmentNode = source.fragmentNode;
  15051. this.vertexNode = source.vertexNode;
  15052. this.contextNode = source.contextNode;
  15053. return super.copy( source );
  15054. }
  15055. }
  15056. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  15057. /**
  15058. * Node material version of {@link LineBasicMaterial}.
  15059. *
  15060. * @augments NodeMaterial
  15061. */
  15062. class LineBasicNodeMaterial extends NodeMaterial {
  15063. static get type() {
  15064. return 'LineBasicNodeMaterial';
  15065. }
  15066. /**
  15067. * Constructs a new line basic node material.
  15068. *
  15069. * @param {Object} [parameters] - The configuration parameter.
  15070. */
  15071. constructor( parameters ) {
  15072. super();
  15073. /**
  15074. * This flag can be used for type testing.
  15075. *
  15076. * @type {boolean}
  15077. * @readonly
  15078. * @default true
  15079. */
  15080. this.isLineBasicNodeMaterial = true;
  15081. this.setDefaultValues( _defaultValues$d );
  15082. this.setValues( parameters );
  15083. }
  15084. }
  15085. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  15086. /**
  15087. * Node material version of {@link LineDashedMaterial}.
  15088. *
  15089. * @augments NodeMaterial
  15090. */
  15091. class LineDashedNodeMaterial extends NodeMaterial {
  15092. static get type() {
  15093. return 'LineDashedNodeMaterial';
  15094. }
  15095. /**
  15096. * Constructs a new line dashed node material.
  15097. *
  15098. * @param {Object} [parameters] - The configuration parameter.
  15099. */
  15100. constructor( parameters ) {
  15101. super();
  15102. /**
  15103. * This flag can be used for type testing.
  15104. *
  15105. * @type {boolean}
  15106. * @readonly
  15107. * @default true
  15108. */
  15109. this.isLineDashedNodeMaterial = true;
  15110. this.setDefaultValues( _defaultValues$c );
  15111. /**
  15112. * The dash offset.
  15113. *
  15114. * @type {number}
  15115. * @default 0
  15116. */
  15117. this.dashOffset = 0;
  15118. /**
  15119. * The offset of dash materials is by default inferred from the `dashOffset`
  15120. * property. This node property allows to overwrite the default
  15121. * and define the offset with a node instead.
  15122. *
  15123. * If you don't want to overwrite the offset but modify the existing
  15124. * value instead, use {@link materialLineDashOffset}.
  15125. *
  15126. * @type {?Node<float>}
  15127. * @default null
  15128. */
  15129. this.offsetNode = null;
  15130. /**
  15131. * The scale of dash materials is by default inferred from the `scale`
  15132. * property. This node property allows to overwrite the default
  15133. * and define the scale with a node instead.
  15134. *
  15135. * If you don't want to overwrite the scale but modify the existing
  15136. * value instead, use {@link materialLineScale}.
  15137. *
  15138. * @type {?Node<float>}
  15139. * @default null
  15140. */
  15141. this.dashScaleNode = null;
  15142. /**
  15143. * The dash size of dash materials is by default inferred from the `dashSize`
  15144. * property. This node property allows to overwrite the default
  15145. * and define the dash size with a node instead.
  15146. *
  15147. * If you don't want to overwrite the dash size but modify the existing
  15148. * value instead, use {@link materialLineDashSize}.
  15149. *
  15150. * @type {?Node<float>}
  15151. * @default null
  15152. */
  15153. this.dashSizeNode = null;
  15154. /**
  15155. * The gap size of dash materials is by default inferred from the `gapSize`
  15156. * property. This node property allows to overwrite the default
  15157. * and define the gap size with a node instead.
  15158. *
  15159. * If you don't want to overwrite the gap size but modify the existing
  15160. * value instead, use {@link materialLineGapSize}.
  15161. *
  15162. * @type {?Node<float>}
  15163. * @default null
  15164. */
  15165. this.gapSizeNode = null;
  15166. this.setValues( parameters );
  15167. }
  15168. /**
  15169. * Setups the dash specific node variables.
  15170. *
  15171. * @param {NodeBuilder} builder - The current node builder.
  15172. */
  15173. setupVariants( /* builder */ ) {
  15174. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15175. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15176. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15177. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15178. dashSize.assign( dashSizeNode );
  15179. gapSize.assign( gapSizeNode );
  15180. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  15181. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  15182. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  15183. }
  15184. }
  15185. let _sharedFramebuffer = null;
  15186. /**
  15187. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  15188. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  15189. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  15190. *
  15191. * @augments ViewportTextureNode
  15192. */
  15193. class ViewportSharedTextureNode extends ViewportTextureNode {
  15194. static get type() {
  15195. return 'ViewportSharedTextureNode';
  15196. }
  15197. /**
  15198. * Constructs a new viewport shared texture node.
  15199. *
  15200. * @param {Node} [uvNode=screenUV] - The uv node.
  15201. * @param {?Node} [levelNode=null] - The level node.
  15202. */
  15203. constructor( uvNode = screenUV, levelNode = null ) {
  15204. if ( _sharedFramebuffer === null ) {
  15205. _sharedFramebuffer = new FramebufferTexture();
  15206. }
  15207. super( uvNode, levelNode, _sharedFramebuffer );
  15208. }
  15209. /**
  15210. * Overwritten so the method always returns the unique shared
  15211. * framebuffer texture.
  15212. *
  15213. * @return {FramebufferTexture} The shared framebuffer texture.
  15214. */
  15215. getTextureForReference() {
  15216. return _sharedFramebuffer;
  15217. }
  15218. updateReference() {
  15219. return this;
  15220. }
  15221. }
  15222. /**
  15223. * TSL function for creating a shared viewport texture node.
  15224. *
  15225. * @tsl
  15226. * @function
  15227. * @param {?Node} [uvNode=screenUV] - The uv node.
  15228. * @param {?Node} [levelNode=null] - The level node.
  15229. * @returns {ViewportSharedTextureNode}
  15230. */
  15231. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  15232. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  15233. /**
  15234. * This node material can be used to render lines with a size larger than one
  15235. * by representing them as instanced meshes.
  15236. *
  15237. * @augments NodeMaterial
  15238. */
  15239. class Line2NodeMaterial extends NodeMaterial {
  15240. static get type() {
  15241. return 'Line2NodeMaterial';
  15242. }
  15243. /**
  15244. * Constructs a new node material for wide line rendering.
  15245. *
  15246. * @param {Object} [parameters={}] - The configuration parameter.
  15247. */
  15248. constructor( parameters = {} ) {
  15249. super();
  15250. /**
  15251. * This flag can be used for type testing.
  15252. *
  15253. * @type {boolean}
  15254. * @readonly
  15255. * @default true
  15256. */
  15257. this.isLine2NodeMaterial = true;
  15258. this.setDefaultValues( _defaultValues$b );
  15259. /**
  15260. * Whether vertex colors should be used or not.
  15261. *
  15262. * @type {boolean}
  15263. * @default false
  15264. */
  15265. this.useColor = parameters.vertexColors;
  15266. /**
  15267. * The dash offset.
  15268. *
  15269. * @type {number}
  15270. * @default 0
  15271. */
  15272. this.dashOffset = 0;
  15273. /**
  15274. * Defines the lines color.
  15275. *
  15276. * @type {?Node<vec3>}
  15277. * @default null
  15278. */
  15279. this.lineColorNode = null;
  15280. /**
  15281. * Defines the offset.
  15282. *
  15283. * @type {?Node<float>}
  15284. * @default null
  15285. */
  15286. this.offsetNode = null;
  15287. /**
  15288. * Defines the dash scale.
  15289. *
  15290. * @type {?Node<float>}
  15291. * @default null
  15292. */
  15293. this.dashScaleNode = null;
  15294. /**
  15295. * Defines the dash size.
  15296. *
  15297. * @type {?Node<float>}
  15298. * @default null
  15299. */
  15300. this.dashSizeNode = null;
  15301. /**
  15302. * Defines the gap size.
  15303. *
  15304. * @type {?Node<float>}
  15305. * @default null
  15306. */
  15307. this.gapSizeNode = null;
  15308. /**
  15309. * Blending is set to `NoBlending` since transparency
  15310. * is not supported, yet.
  15311. *
  15312. * @type {number}
  15313. * @default 0
  15314. */
  15315. this.blending = NoBlending;
  15316. this._useDash = parameters.dashed;
  15317. this._useAlphaToCoverage = true;
  15318. this._useWorldUnits = false;
  15319. this.setValues( parameters );
  15320. }
  15321. /**
  15322. * Setups the vertex and fragment stage of this node material.
  15323. *
  15324. * @param {NodeBuilder} builder - The current node builder.
  15325. */
  15326. setup( builder ) {
  15327. const { renderer } = builder;
  15328. const useAlphaToCoverage = this._useAlphaToCoverage;
  15329. const useColor = this.useColor;
  15330. const useDash = this._useDash;
  15331. const useWorldUnits = this._useWorldUnits;
  15332. const trimSegment = Fn( ( { start, end } ) => {
  15333. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  15334. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  15335. const nearEstimate = b.mul( -0.5 ).div( a );
  15336. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  15337. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  15338. } ).setLayout( {
  15339. name: 'trimSegment',
  15340. type: 'vec4',
  15341. inputs: [
  15342. { name: 'start', type: 'vec4' },
  15343. { name: 'end', type: 'vec4' }
  15344. ]
  15345. } );
  15346. this.vertexNode = Fn( () => {
  15347. const instanceStart = attribute( 'instanceStart' );
  15348. const instanceEnd = attribute( 'instanceEnd' );
  15349. // camera space
  15350. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  15351. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  15352. if ( useDash ) {
  15353. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15354. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15355. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  15356. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  15357. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  15358. lineDistance = lineDistance.add( offsetNode );
  15359. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  15360. }
  15361. if ( useWorldUnits ) {
  15362. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  15363. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  15364. }
  15365. const aspect = viewport.z.div( viewport.w );
  15366. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  15367. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  15368. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  15369. // perhaps there is a more elegant solution -- WestLangley
  15370. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  15371. If( perspective, () => {
  15372. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  15373. end.assign( trimSegment( { start: start, end: end } ) );
  15374. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  15375. start.assign( trimSegment( { start: end, end: start } ) );
  15376. } );
  15377. } );
  15378. // clip space
  15379. const clipStart = cameraProjectionMatrix.mul( start );
  15380. const clipEnd = cameraProjectionMatrix.mul( end );
  15381. // ndc space
  15382. const ndcStart = clipStart.xyz.div( clipStart.w );
  15383. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  15384. // direction
  15385. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  15386. // account for clip-space aspect ratio
  15387. dir.x.assign( dir.x.mul( aspect ) );
  15388. dir.assign( dir.normalize() );
  15389. const clip = vec4().toVar();
  15390. if ( useWorldUnits ) {
  15391. // get the offset direction as perpendicular to the view vector
  15392. const worldDir = end.xyz.sub( start.xyz ).normalize();
  15393. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  15394. const worldUp = worldDir.cross( tmpFwd ).normalize();
  15395. const worldFwd = worldDir.cross( worldUp );
  15396. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  15397. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  15398. // height offset
  15399. const hw = materialLineWidth.mul( 0.5 );
  15400. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  15401. // don't extend the line if we're rendering dashes because we
  15402. // won't be rendering the endcaps
  15403. if ( ! useDash ) {
  15404. // cap extension
  15405. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  15406. // add width to the box
  15407. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  15408. // endcaps
  15409. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  15410. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  15411. } );
  15412. }
  15413. // project the worldpos
  15414. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  15415. // shift the depth of the projected points so the line
  15416. // segments overlap neatly
  15417. const clipPose = vec3().toVar();
  15418. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  15419. clip.z.assign( clipPose.z.mul( clip.w ) );
  15420. } else {
  15421. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  15422. // undo aspect ratio adjustment
  15423. dir.x.assign( dir.x.div( aspect ) );
  15424. offset.x.assign( offset.x.div( aspect ) );
  15425. // sign flip
  15426. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  15427. // endcaps
  15428. If( positionGeometry.y.lessThan( 0.0 ), () => {
  15429. offset.assign( offset.sub( dir ) );
  15430. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  15431. offset.assign( offset.add( dir ) );
  15432. } );
  15433. // adjust for linewidth
  15434. offset.assign( offset.mul( materialLineWidth ) );
  15435. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  15436. offset.assign( offset.div( viewport.w.div( screenDPR ) ) );
  15437. // select end
  15438. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  15439. // back to clip space
  15440. offset.assign( offset.mul( clip.w ) );
  15441. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  15442. }
  15443. return clip;
  15444. } )();
  15445. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  15446. const p13 = p1.sub( p3 );
  15447. const p43 = p4.sub( p3 );
  15448. const p21 = p2.sub( p1 );
  15449. const d1343 = p13.dot( p43 );
  15450. const d4321 = p43.dot( p21 );
  15451. const d1321 = p13.dot( p21 );
  15452. const d4343 = p43.dot( p43 );
  15453. const d2121 = p21.dot( p21 );
  15454. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  15455. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  15456. const mua = numer.div( denom ).clamp();
  15457. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  15458. return vec2( mua, mub );
  15459. } );
  15460. this.colorNode = Fn( () => {
  15461. const vUv = uv$1();
  15462. if ( useDash ) {
  15463. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15464. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15465. dashSize.assign( dashSizeNode );
  15466. gapSize.assign( gapSizeNode );
  15467. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  15468. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  15469. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  15470. }
  15471. const alpha = float( 1 ).toVar( 'alpha' );
  15472. if ( useWorldUnits ) {
  15473. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  15474. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  15475. // Find the closest points on the view ray and the line segment
  15476. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  15477. const lineDir = worldEnd.sub( worldStart );
  15478. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  15479. const p1 = worldStart.add( lineDir.mul( params.x ) );
  15480. const p2 = rayEnd.mul( params.y );
  15481. const delta = p1.sub( p2 );
  15482. const len = delta.length();
  15483. const norm = len.div( materialLineWidth );
  15484. if ( ! useDash ) {
  15485. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15486. const dnorm = norm.fwidth();
  15487. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  15488. } else {
  15489. norm.greaterThan( 0.5 ).discard();
  15490. }
  15491. }
  15492. } else {
  15493. // round endcaps
  15494. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15495. const a = vUv.x;
  15496. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15497. const len2 = a.mul( a ).add( b.mul( b ) );
  15498. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  15499. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15500. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  15501. } );
  15502. } else {
  15503. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15504. const a = vUv.x;
  15505. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15506. const len2 = a.mul( a ).add( b.mul( b ) );
  15507. len2.greaterThan( 1.0 ).discard();
  15508. } );
  15509. }
  15510. }
  15511. let lineColorNode;
  15512. if ( this.lineColorNode ) {
  15513. lineColorNode = this.lineColorNode;
  15514. } else {
  15515. if ( useColor ) {
  15516. const instanceColorStart = attribute( 'instanceColorStart' );
  15517. const instanceColorEnd = attribute( 'instanceColorEnd' );
  15518. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  15519. lineColorNode = instanceColor.mul( materialColor );
  15520. } else {
  15521. lineColorNode = materialColor;
  15522. }
  15523. }
  15524. return vec4( lineColorNode, alpha );
  15525. } )();
  15526. if ( this.transparent ) {
  15527. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15528. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  15529. }
  15530. super.setup( builder );
  15531. }
  15532. /**
  15533. * Whether the lines should sized in world units or not.
  15534. * When set to `false` the unit is pixel.
  15535. *
  15536. * @type {boolean}
  15537. * @default false
  15538. */
  15539. get worldUnits() {
  15540. return this._useWorldUnits;
  15541. }
  15542. set worldUnits( value ) {
  15543. if ( this._useWorldUnits !== value ) {
  15544. this._useWorldUnits = value;
  15545. this.needsUpdate = true;
  15546. }
  15547. }
  15548. /**
  15549. * Whether the lines should be dashed or not.
  15550. *
  15551. * @type {boolean}
  15552. * @default false
  15553. */
  15554. get dashed() {
  15555. return this._useDash;
  15556. }
  15557. set dashed( value ) {
  15558. if ( this._useDash !== value ) {
  15559. this._useDash = value;
  15560. this.needsUpdate = true;
  15561. }
  15562. }
  15563. /**
  15564. * Whether alpha to coverage should be used or not.
  15565. *
  15566. * @type {boolean}
  15567. * @default true
  15568. */
  15569. get alphaToCoverage() {
  15570. return this._useAlphaToCoverage;
  15571. }
  15572. set alphaToCoverage( value ) {
  15573. if ( this._useAlphaToCoverage !== value ) {
  15574. this._useAlphaToCoverage = value;
  15575. this.needsUpdate = true;
  15576. }
  15577. }
  15578. }
  15579. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  15580. /**
  15581. * Node material version of {@link MeshNormalMaterial}.
  15582. *
  15583. * @augments NodeMaterial
  15584. */
  15585. class MeshNormalNodeMaterial extends NodeMaterial {
  15586. static get type() {
  15587. return 'MeshNormalNodeMaterial';
  15588. }
  15589. /**
  15590. * Constructs a new mesh normal node material.
  15591. *
  15592. * @param {Object} [parameters] - The configuration parameter.
  15593. */
  15594. constructor( parameters ) {
  15595. super();
  15596. /**
  15597. * This flag can be used for type testing.
  15598. *
  15599. * @type {boolean}
  15600. * @readonly
  15601. * @default true
  15602. */
  15603. this.isMeshNormalNodeMaterial = true;
  15604. this.setDefaultValues( _defaultValues$a );
  15605. this.setValues( parameters );
  15606. }
  15607. /**
  15608. * Overwrites the default implementation by computing the diffuse color
  15609. * based on the normal data.
  15610. */
  15611. setupDiffuseColor() {
  15612. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15613. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  15614. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  15615. }
  15616. }
  15617. /**
  15618. * TSL function for creating an equirect uv node.
  15619. *
  15620. * Can be used to compute texture coordinates for projecting an
  15621. * equirectangular texture onto a mesh for using it as the scene's
  15622. * background.
  15623. *
  15624. * ```js
  15625. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  15626. * ```
  15627. *
  15628. * @tsl
  15629. * @function
  15630. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  15631. * @returns {Node<vec2>}
  15632. */
  15633. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  15634. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  15635. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  15636. return vec2( u, v );
  15637. } );
  15638. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  15639. /**
  15640. * This class represents a cube render target. It is a special version
  15641. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  15642. *
  15643. * @augments WebGLCubeRenderTarget
  15644. */
  15645. class CubeRenderTarget extends WebGLCubeRenderTarget {
  15646. /**
  15647. * Constructs a new cube render target.
  15648. *
  15649. * @param {number} [size=1] - The size of the render target.
  15650. * @param {RenderTarget~Options} [options] - The configuration object.
  15651. */
  15652. constructor( size = 1, options = {} ) {
  15653. super( size, options );
  15654. /**
  15655. * This flag can be used for type testing.
  15656. *
  15657. * @type {boolean}
  15658. * @readonly
  15659. * @default true
  15660. */
  15661. this.isCubeRenderTarget = true;
  15662. }
  15663. /**
  15664. * Converts the given equirectangular texture to a cube map.
  15665. *
  15666. * @param {Renderer} renderer - The renderer.
  15667. * @param {Texture} texture - The equirectangular texture.
  15668. * @return {CubeRenderTarget} A reference to this cube render target.
  15669. */
  15670. fromEquirectangularTexture( renderer, texture$1 ) {
  15671. const currentMinFilter = texture$1.minFilter;
  15672. const currentGenerateMipmaps = texture$1.generateMipmaps;
  15673. texture$1.generateMipmaps = true;
  15674. this.texture.type = texture$1.type;
  15675. this.texture.colorSpace = texture$1.colorSpace;
  15676. this.texture.generateMipmaps = texture$1.generateMipmaps;
  15677. this.texture.minFilter = texture$1.minFilter;
  15678. this.texture.magFilter = texture$1.magFilter;
  15679. const geometry = new BoxGeometry( 5, 5, 5 );
  15680. const uvNode = equirectUV( positionWorldDirection );
  15681. const material = new NodeMaterial();
  15682. material.colorNode = texture( texture$1, uvNode, 0 );
  15683. material.side = BackSide;
  15684. material.blending = NoBlending;
  15685. const mesh = new Mesh( geometry, material );
  15686. const scene = new Scene();
  15687. scene.add( mesh );
  15688. // Avoid blurred poles
  15689. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  15690. const camera = new CubeCamera( 1, 10, this );
  15691. const currentMRT = renderer.getMRT();
  15692. renderer.setMRT( null );
  15693. camera.update( renderer, scene );
  15694. renderer.setMRT( currentMRT );
  15695. texture$1.minFilter = currentMinFilter;
  15696. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  15697. mesh.geometry.dispose();
  15698. mesh.material.dispose();
  15699. return this;
  15700. }
  15701. }
  15702. const _cache$1 = new WeakMap();
  15703. /**
  15704. * This node can be used to automatically convert environment maps in the
  15705. * equirectangular format into the cube map format.
  15706. *
  15707. * @augments TempNode
  15708. */
  15709. class CubeMapNode extends TempNode {
  15710. static get type() {
  15711. return 'CubeMapNode';
  15712. }
  15713. /**
  15714. * Constructs a new cube map node.
  15715. *
  15716. * @param {Node} envNode - The node representing the environment map.
  15717. */
  15718. constructor( envNode ) {
  15719. super( 'vec3' );
  15720. /**
  15721. * The node representing the environment map.
  15722. *
  15723. * @type {Node}
  15724. */
  15725. this.envNode = envNode;
  15726. /**
  15727. * A reference to the internal cube texture.
  15728. *
  15729. * @private
  15730. * @type {?CubeTexture}
  15731. * @default null
  15732. */
  15733. this._cubeTexture = null;
  15734. /**
  15735. * A reference to the internal cube texture node.
  15736. *
  15737. * @private
  15738. * @type {CubeTextureNode}
  15739. */
  15740. this._cubeTextureNode = cubeTexture( null );
  15741. const defaultTexture = new CubeTexture();
  15742. defaultTexture.isRenderTargetTexture = true;
  15743. /**
  15744. * A default cube texture that acts as a placeholder.
  15745. * It is used when the conversion from equirectangular to cube
  15746. * map has not finished yet for a given texture.
  15747. *
  15748. * @private
  15749. * @type {CubeTexture}
  15750. */
  15751. this._defaultTexture = defaultTexture;
  15752. /**
  15753. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  15754. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  15755. *
  15756. * @type {string}
  15757. * @default 'render'
  15758. */
  15759. this.updateBeforeType = NodeUpdateType.RENDER;
  15760. }
  15761. updateBefore( frame ) {
  15762. const { renderer, material } = frame;
  15763. const envNode = this.envNode;
  15764. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  15765. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  15766. if ( texture && texture.isTexture ) {
  15767. const mapping = texture.mapping;
  15768. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  15769. // check for converted cubemap map
  15770. if ( _cache$1.has( texture ) ) {
  15771. const cubeMap = _cache$1.get( texture );
  15772. mapTextureMapping( cubeMap, texture.mapping );
  15773. this._cubeTexture = cubeMap;
  15774. } else {
  15775. // create cube map from equirectangular map
  15776. const image = texture.image;
  15777. if ( isEquirectangularMapReady$1( image ) ) {
  15778. const renderTarget = new CubeRenderTarget( image.height );
  15779. renderTarget.fromEquirectangularTexture( renderer, texture );
  15780. mapTextureMapping( renderTarget.texture, texture.mapping );
  15781. this._cubeTexture = renderTarget.texture;
  15782. _cache$1.set( texture, renderTarget.texture );
  15783. texture.addEventListener( 'dispose', onTextureDispose );
  15784. } else {
  15785. // default cube texture as fallback when equirectangular texture is not yet loaded
  15786. this._cubeTexture = this._defaultTexture;
  15787. }
  15788. }
  15789. //
  15790. this._cubeTextureNode.value = this._cubeTexture;
  15791. } else {
  15792. // envNode already refers to a cube map
  15793. this._cubeTextureNode = this.envNode;
  15794. }
  15795. }
  15796. }
  15797. }
  15798. setup( builder ) {
  15799. this.updateBefore( builder );
  15800. return this._cubeTextureNode;
  15801. }
  15802. }
  15803. /**
  15804. * Returns true if the given equirectangular image has been fully loaded
  15805. * and is ready for further processing.
  15806. *
  15807. * @private
  15808. * @param {Image} image - The equirectangular image to check.
  15809. * @return {boolean} Whether the image is ready or not.
  15810. */
  15811. function isEquirectangularMapReady$1( image ) {
  15812. if ( image === null || image === undefined ) return false;
  15813. return image.height > 0;
  15814. }
  15815. /**
  15816. * This function is executed when `dispose()` is called on the equirectangular
  15817. * texture. In this case, the generated cube map with its render target
  15818. * is deleted as well.
  15819. *
  15820. * @private
  15821. * @param {Object} event - The event object.
  15822. */
  15823. function onTextureDispose( event ) {
  15824. const texture = event.target;
  15825. texture.removeEventListener( 'dispose', onTextureDispose );
  15826. const renderTarget = _cache$1.get( texture );
  15827. if ( renderTarget !== undefined ) {
  15828. _cache$1.delete( texture );
  15829. renderTarget.dispose();
  15830. }
  15831. }
  15832. /**
  15833. * This function makes sure the generated cube map uses the correct
  15834. * texture mapping that corresponds to the equirectangular original.
  15835. *
  15836. * @private
  15837. * @param {Texture} texture - The cube texture.
  15838. * @param {number} mapping - The original texture mapping.
  15839. */
  15840. function mapTextureMapping( texture, mapping ) {
  15841. if ( mapping === EquirectangularReflectionMapping ) {
  15842. texture.mapping = CubeReflectionMapping;
  15843. } else if ( mapping === EquirectangularRefractionMapping ) {
  15844. texture.mapping = CubeRefractionMapping;
  15845. }
  15846. }
  15847. /**
  15848. * TSL function for creating a cube map node.
  15849. *
  15850. * @tsl
  15851. * @function
  15852. * @param {Node} envNode - The node representing the environment map.
  15853. * @returns {CubeMapNode}
  15854. */
  15855. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  15856. /**
  15857. * Represents a basic model for Image-based lighting (IBL). The environment
  15858. * is defined via environment maps in the equirectangular or cube map format.
  15859. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  15860. * or {@link MeshPhongNodeMaterial}.
  15861. *
  15862. * @augments LightingNode
  15863. */
  15864. class BasicEnvironmentNode extends LightingNode {
  15865. static get type() {
  15866. return 'BasicEnvironmentNode';
  15867. }
  15868. /**
  15869. * Constructs a new basic environment node.
  15870. *
  15871. * @param {Node} [envNode=null] - A node representing the environment.
  15872. */
  15873. constructor( envNode = null ) {
  15874. super();
  15875. /**
  15876. * A node representing the environment.
  15877. *
  15878. * @type {Node}
  15879. * @default null
  15880. */
  15881. this.envNode = envNode;
  15882. }
  15883. setup( builder ) {
  15884. // environment property is used in the finish() method of BasicLightingModel
  15885. builder.context.environment = cubeMapNode( this.envNode );
  15886. }
  15887. }
  15888. /**
  15889. * A specific version of {@link IrradianceNode} that is only relevant
  15890. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  15891. * requires a special scaling factor for the light map.
  15892. *
  15893. * @augments LightingNode
  15894. */
  15895. class BasicLightMapNode extends LightingNode {
  15896. static get type() {
  15897. return 'BasicLightMapNode';
  15898. }
  15899. /**
  15900. * Constructs a new basic light map node.
  15901. *
  15902. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  15903. */
  15904. constructor( lightMapNode = null ) {
  15905. super();
  15906. /**
  15907. * The light map node.
  15908. *
  15909. * @type {?Node<vec3>}
  15910. */
  15911. this.lightMapNode = lightMapNode;
  15912. }
  15913. setup( builder ) {
  15914. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  15915. const RECIPROCAL_PI = float( 1 / Math.PI );
  15916. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  15917. }
  15918. }
  15919. /**
  15920. * Abstract class for implementing lighting models. The module defines
  15921. * multiple methods that concrete lighting models can implement. These
  15922. * methods are executed at different points during the light evaluation
  15923. * process.
  15924. */
  15925. class LightingModel {
  15926. /**
  15927. * This method is intended for setting up lighting model and context data
  15928. * which are later used in the evaluation process.
  15929. *
  15930. * @abstract
  15931. * @param {NodeBuilder} builder - The current node builder.
  15932. */
  15933. start( builder ) {
  15934. // lights ( direct )
  15935. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  15936. // indirect
  15937. this.indirect( builder );
  15938. }
  15939. /**
  15940. * This method is intended for executing final tasks like final updates
  15941. * to the outgoing light.
  15942. *
  15943. * @abstract
  15944. * @param {NodeBuilder} builder - The current node builder.
  15945. */
  15946. finish( /*builder*/ ) { }
  15947. /**
  15948. * This method is intended for implementing the direct light term and
  15949. * executed during the build process of directional, point and spot light nodes.
  15950. *
  15951. * @abstract
  15952. * @param {Object} lightData - The light data.
  15953. * @param {NodeBuilder} builder - The current node builder.
  15954. */
  15955. direct( /*lightData, builder*/ ) { }
  15956. /**
  15957. * This method is intended for implementing the direct light term for
  15958. * rect area light nodes.
  15959. *
  15960. * @abstract
  15961. * @param {Object} lightData - The light data.
  15962. * @param {NodeBuilder} builder - The current node builder.
  15963. */
  15964. directRectArea( /*lightData, builder*/ ) {}
  15965. /**
  15966. * This method is intended for implementing the indirect light term.
  15967. *
  15968. * @abstract
  15969. * @param {NodeBuilder} builder - The current node builder.
  15970. */
  15971. indirect( /*builder*/ ) { }
  15972. /**
  15973. * This method is intended for implementing the ambient occlusion term.
  15974. * Unlike other methods, this method must be called manually by the lighting
  15975. * model in its indirect term.
  15976. *
  15977. * @abstract
  15978. * @param {NodeBuilder} builder - The current node builder.
  15979. */
  15980. ambientOcclusion( /*input, stack, builder*/ ) { }
  15981. }
  15982. /**
  15983. * Represents the lighting model for unlit materials. The only light contribution
  15984. * is baked indirect lighting modulated with ambient occlusion and the material's
  15985. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  15986. *
  15987. * @augments LightingModel
  15988. */
  15989. class BasicLightingModel extends LightingModel {
  15990. /**
  15991. * Constructs a new basic lighting model.
  15992. */
  15993. constructor() {
  15994. super();
  15995. }
  15996. /**
  15997. * Implements the baked indirect lighting with its modulation.
  15998. *
  15999. * @param {NodeBuilder} builder - The current node builder.
  16000. */
  16001. indirect( { context } ) {
  16002. const ambientOcclusion = context.ambientOcclusion;
  16003. const reflectedLight = context.reflectedLight;
  16004. const irradianceLightMap = context.irradianceLightMap;
  16005. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  16006. // accumulation (baked indirect lighting only)
  16007. if ( irradianceLightMap ) {
  16008. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  16009. } else {
  16010. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  16011. }
  16012. // modulation
  16013. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16014. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  16015. }
  16016. /**
  16017. * Implements the environment mapping.
  16018. *
  16019. * @param {NodeBuilder} builder - The current node builder.
  16020. */
  16021. finish( builder ) {
  16022. const { material, context } = builder;
  16023. const outgoingLight = context.outgoingLight;
  16024. const envNode = builder.context.environment;
  16025. if ( envNode ) {
  16026. switch ( material.combine ) {
  16027. case MultiplyOperation:
  16028. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  16029. break;
  16030. case MixOperation:
  16031. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  16032. break;
  16033. case AddOperation:
  16034. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  16035. break;
  16036. default:
  16037. warn( 'BasicLightingModel: Unsupported .combine value:', material.combine );
  16038. break;
  16039. }
  16040. }
  16041. }
  16042. }
  16043. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  16044. /**
  16045. * Node material version of {@link MeshBasicMaterial}.
  16046. *
  16047. * @augments NodeMaterial
  16048. */
  16049. class MeshBasicNodeMaterial extends NodeMaterial {
  16050. static get type() {
  16051. return 'MeshBasicNodeMaterial';
  16052. }
  16053. /**
  16054. * Constructs a new mesh basic node material.
  16055. *
  16056. * @param {Object} [parameters] - The configuration parameter.
  16057. */
  16058. constructor( parameters ) {
  16059. super();
  16060. /**
  16061. * This flag can be used for type testing.
  16062. *
  16063. * @type {boolean}
  16064. * @readonly
  16065. * @default true
  16066. */
  16067. this.isMeshBasicNodeMaterial = true;
  16068. /**
  16069. * Although the basic material is by definition unlit, we set
  16070. * this property to `true` since we use a lighting model to compute
  16071. * the outgoing light of the fragment shader.
  16072. *
  16073. * @type {boolean}
  16074. * @default true
  16075. */
  16076. this.lights = true;
  16077. this.setDefaultValues( _defaultValues$9 );
  16078. this.setValues( parameters );
  16079. }
  16080. /**
  16081. * Basic materials are not affected by normal and bump maps so we
  16082. * return by default {@link normalViewGeometry}.
  16083. *
  16084. * @return {Node<vec3>} The normal node.
  16085. */
  16086. setupNormal() {
  16087. return directionToFaceDirection( normalViewGeometry ); // see #28839
  16088. }
  16089. /**
  16090. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16091. * to implement the default environment mapping.
  16092. *
  16093. * @param {NodeBuilder} builder - The current node builder.
  16094. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16095. */
  16096. setupEnvironment( builder ) {
  16097. const envNode = super.setupEnvironment( builder );
  16098. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16099. }
  16100. /**
  16101. * This method must be overwritten since light maps are evaluated
  16102. * with a special scaling factor for basic materials.
  16103. *
  16104. * @param {NodeBuilder} builder - The current node builder.
  16105. * @return {?BasicLightMapNode<vec3>} The light map node.
  16106. */
  16107. setupLightMap( builder ) {
  16108. let node = null;
  16109. if ( builder.material.lightMap ) {
  16110. node = new BasicLightMapNode( materialLightMap );
  16111. }
  16112. return node;
  16113. }
  16114. /**
  16115. * The material overwrites this method because `lights` is set to `true` but
  16116. * we still want to return the diffuse color as the outgoing light.
  16117. *
  16118. * @return {Node<vec3>} The outgoing light node.
  16119. */
  16120. setupOutgoingLight() {
  16121. return diffuseColor.rgb;
  16122. }
  16123. /**
  16124. * Setups the lighting model.
  16125. *
  16126. * @return {BasicLightingModel} The lighting model.
  16127. */
  16128. setupLightingModel() {
  16129. return new BasicLightingModel();
  16130. }
  16131. }
  16132. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  16133. // Original approximation by Christophe Schlick '94
  16134. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  16135. // Optimized variant (presented by Epic at SIGGRAPH '13)
  16136. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  16137. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  16138. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  16139. } ); // validated
  16140. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  16141. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  16142. } ); // validated
  16143. const G_BlinnPhong_Implicit = () => float( 0.25 );
  16144. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  16145. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  16146. } );
  16147. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16148. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16149. const dotNH = normalView.dot( halfDir ).clamp();
  16150. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16151. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  16152. const G = G_BlinnPhong_Implicit();
  16153. const D = D_BlinnPhong( { dotNH } );
  16154. return F.mul( G ).mul( D );
  16155. } );
  16156. /**
  16157. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  16158. *
  16159. * @augments BasicLightingModel
  16160. */
  16161. class PhongLightingModel extends BasicLightingModel {
  16162. /**
  16163. * Constructs a new phong lighting model.
  16164. *
  16165. * @param {boolean} [specular=true] - Whether specular is supported or not.
  16166. */
  16167. constructor( specular = true ) {
  16168. super();
  16169. /**
  16170. * Whether specular is supported or not. Set this to `false` if you are
  16171. * looking for a Lambert-like material meaning a material for non-shiny
  16172. * surfaces, without specular highlights.
  16173. *
  16174. * @type {boolean}
  16175. * @default true
  16176. */
  16177. this.specular = specular;
  16178. }
  16179. /**
  16180. * Implements the direct lighting. The specular portion is optional an can be controlled
  16181. * with the {@link PhongLightingModel#specular} flag.
  16182. *
  16183. * @param {Object} lightData - The light data.
  16184. */
  16185. direct( { lightDirection, lightColor, reflectedLight } ) {
  16186. const dotNL = normalView.dot( lightDirection ).clamp();
  16187. const irradiance = dotNL.mul( lightColor );
  16188. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16189. if ( this.specular === true ) {
  16190. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  16191. }
  16192. }
  16193. /**
  16194. * Implements the indirect lighting.
  16195. *
  16196. * @param {NodeBuilder} builder - The current node builder.
  16197. */
  16198. indirect( builder ) {
  16199. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  16200. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16201. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16202. }
  16203. }
  16204. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  16205. /**
  16206. * Node material version of {@link MeshLambertMaterial}.
  16207. *
  16208. * @augments NodeMaterial
  16209. */
  16210. class MeshLambertNodeMaterial extends NodeMaterial {
  16211. static get type() {
  16212. return 'MeshLambertNodeMaterial';
  16213. }
  16214. /**
  16215. * Constructs a new mesh lambert node material.
  16216. *
  16217. * @param {Object} [parameters] - The configuration parameter.
  16218. */
  16219. constructor( parameters ) {
  16220. super();
  16221. /**
  16222. * This flag can be used for type testing.
  16223. *
  16224. * @type {boolean}
  16225. * @readonly
  16226. * @default true
  16227. */
  16228. this.isMeshLambertNodeMaterial = true;
  16229. /**
  16230. * Set to `true` because lambert materials react on lights.
  16231. *
  16232. * @type {boolean}
  16233. * @default true
  16234. */
  16235. this.lights = true;
  16236. this.setDefaultValues( _defaultValues$8 );
  16237. this.setValues( parameters );
  16238. }
  16239. /**
  16240. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16241. * to implement the default environment mapping.
  16242. *
  16243. * @param {NodeBuilder} builder - The current node builder.
  16244. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16245. */
  16246. setupEnvironment( builder ) {
  16247. const envNode = super.setupEnvironment( builder );
  16248. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16249. }
  16250. /**
  16251. * Setups the lighting model.
  16252. *
  16253. * @return {PhongLightingModel} The lighting model.
  16254. */
  16255. setupLightingModel( /*builder*/ ) {
  16256. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  16257. }
  16258. }
  16259. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  16260. /**
  16261. * Node material version of {@link MeshPhongMaterial}.
  16262. *
  16263. * @augments NodeMaterial
  16264. */
  16265. class MeshPhongNodeMaterial extends NodeMaterial {
  16266. static get type() {
  16267. return 'MeshPhongNodeMaterial';
  16268. }
  16269. /**
  16270. * Constructs a new mesh lambert node material.
  16271. *
  16272. * @param {Object} [parameters] - The configuration parameter.
  16273. */
  16274. constructor( parameters ) {
  16275. super();
  16276. /**
  16277. * This flag can be used for type testing.
  16278. *
  16279. * @type {boolean}
  16280. * @readonly
  16281. * @default true
  16282. */
  16283. this.isMeshPhongNodeMaterial = true;
  16284. /**
  16285. * Set to `true` because phong materials react on lights.
  16286. *
  16287. * @type {boolean}
  16288. * @default true
  16289. */
  16290. this.lights = true;
  16291. /**
  16292. * The shininess of phong materials is by default inferred from the `shininess`
  16293. * property. This node property allows to overwrite the default
  16294. * and define the shininess with a node instead.
  16295. *
  16296. * If you don't want to overwrite the shininess but modify the existing
  16297. * value instead, use {@link materialShininess}.
  16298. *
  16299. * @type {?Node<float>}
  16300. * @default null
  16301. */
  16302. this.shininessNode = null;
  16303. /**
  16304. * The specular color of phong materials is by default inferred from the
  16305. * `specular` property. This node property allows to overwrite the default
  16306. * and define the specular color with a node instead.
  16307. *
  16308. * If you don't want to overwrite the specular color but modify the existing
  16309. * value instead, use {@link materialSpecular}.
  16310. *
  16311. * @type {?Node<vec3>}
  16312. * @default null
  16313. */
  16314. this.specularNode = null;
  16315. this.setDefaultValues( _defaultValues$7 );
  16316. this.setValues( parameters );
  16317. }
  16318. /**
  16319. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16320. * to implement the default environment mapping.
  16321. *
  16322. * @param {NodeBuilder} builder - The current node builder.
  16323. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16324. */
  16325. setupEnvironment( builder ) {
  16326. const envNode = super.setupEnvironment( builder );
  16327. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16328. }
  16329. /**
  16330. * Setups the lighting model.
  16331. *
  16332. * @return {PhongLightingModel} The lighting model.
  16333. */
  16334. setupLightingModel( /*builder*/ ) {
  16335. return new PhongLightingModel();
  16336. }
  16337. /**
  16338. * Setups the phong specific node variables.
  16339. *
  16340. * @param {NodeBuilder} builder - The current node builder.
  16341. */
  16342. setupVariants( /*builder*/ ) {
  16343. // SHININESS
  16344. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16345. shininess.assign( shininessNode );
  16346. // SPECULAR COLOR
  16347. const specularNode = this.specularNode || materialSpecular;
  16348. specularColor.assign( specularNode );
  16349. }
  16350. copy( source ) {
  16351. this.shininessNode = source.shininessNode;
  16352. this.specularNode = source.specularNode;
  16353. return super.copy( source );
  16354. }
  16355. }
  16356. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  16357. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  16358. return float( 0 );
  16359. }
  16360. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  16361. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  16362. return geometryRoughness;
  16363. } );
  16364. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  16365. const { roughness } = inputs;
  16366. const geometryRoughness = getGeometryRoughness();
  16367. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  16368. roughnessFactor = roughnessFactor.add( geometryRoughness );
  16369. roughnessFactor = roughnessFactor.min( 1.0 );
  16370. return roughnessFactor;
  16371. } );
  16372. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  16373. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  16374. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  16375. const a2 = alpha.pow2();
  16376. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  16377. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  16378. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  16379. } ).setLayout( {
  16380. name: 'V_GGX_SmithCorrelated',
  16381. type: 'float',
  16382. inputs: [
  16383. { name: 'alpha', type: 'float' },
  16384. { name: 'dotNL', type: 'float' },
  16385. { name: 'dotNV', type: 'float' }
  16386. ]
  16387. } ); // validated
  16388. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16389. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  16390. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  16391. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  16392. const v = div( 0.5, gv.add( gl ) );
  16393. return v;
  16394. } ).setLayout( {
  16395. name: 'V_GGX_SmithCorrelated_Anisotropic',
  16396. type: 'float',
  16397. inputs: [
  16398. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16399. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16400. { name: 'dotTV', type: 'float', qualifier: 'in' },
  16401. { name: 'dotBV', type: 'float', qualifier: 'in' },
  16402. { name: 'dotTL', type: 'float', qualifier: 'in' },
  16403. { name: 'dotBL', type: 'float', qualifier: 'in' },
  16404. { name: 'dotNV', type: 'float', qualifier: 'in' },
  16405. { name: 'dotNL', type: 'float', qualifier: 'in' }
  16406. ]
  16407. } );
  16408. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  16409. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  16410. // alpha is "roughness squared" in Disney’s reparameterization
  16411. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  16412. const a2 = alpha.pow2();
  16413. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  16414. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  16415. } ).setLayout( {
  16416. name: 'D_GGX',
  16417. type: 'float',
  16418. inputs: [
  16419. { name: 'alpha', type: 'float' },
  16420. { name: 'dotNH', type: 'float' }
  16421. ]
  16422. } ); // validated
  16423. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  16424. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16425. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  16426. const a2 = alphaT.mul( alphaB );
  16427. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  16428. const v2 = v.dot( v );
  16429. const w2 = a2.div( v2 );
  16430. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  16431. } ).setLayout( {
  16432. name: 'D_GGX_Anisotropic',
  16433. type: 'float',
  16434. inputs: [
  16435. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16436. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16437. { name: 'dotNH', type: 'float', qualifier: 'in' },
  16438. { name: 'dotTH', type: 'float', qualifier: 'in' },
  16439. { name: 'dotBH', type: 'float', qualifier: 'in' }
  16440. ]
  16441. } );
  16442. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  16443. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16444. const alpha = roughness.pow2(); // UE4's roughness
  16445. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16446. const dotNL = normalView$1.dot( lightDirection ).clamp();
  16447. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16448. const dotNH = normalView$1.dot( halfDir ).clamp();
  16449. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16450. let F = F_Schlick( { f0, f90, dotVH } );
  16451. let V, D;
  16452. if ( defined( USE_IRIDESCENCE ) ) {
  16453. F = iridescence.mix( F, f );
  16454. }
  16455. if ( defined( USE_ANISOTROPY ) ) {
  16456. const dotTL = anisotropyT.dot( lightDirection );
  16457. const dotTV = anisotropyT.dot( positionViewDirection );
  16458. const dotTH = anisotropyT.dot( halfDir );
  16459. const dotBL = anisotropyB.dot( lightDirection );
  16460. const dotBV = anisotropyB.dot( positionViewDirection );
  16461. const dotBH = anisotropyB.dot( halfDir );
  16462. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  16463. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  16464. } else {
  16465. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  16466. D = D_GGX( { alpha, dotNH } );
  16467. }
  16468. return F.mul( V ).mul( D );
  16469. } ); // validated
  16470. /**
  16471. * Precomputed DFG LUT for Image-Based Lighting
  16472. * Resolution: 32x32
  16473. * Samples: 4096 per texel
  16474. * Format: RG16F (2 half floats per texel: scale, bias)
  16475. */
  16476. const DATA = new Uint16Array( [
  16477. 0x2cd9, 0x3b64, 0x2d0e, 0x3b43, 0x2e20, 0x3aa7, 0x3061, 0x39fb, 0x325e, 0x397c, 0x3454, 0x3908, 0x357d, 0x3893, 0x3698, 0x381e, 0x379d, 0x375b, 0x3845, 0x3689, 0x38af, 0x35ca, 0x390d, 0x351e, 0x395f, 0x3484, 0x39a8, 0x33f9, 0x39e6, 0x330a, 0x3a1c, 0x3239, 0x3a4b, 0x3183, 0x3a73, 0x30e5, 0x3a95, 0x305b, 0x3ab1, 0x2fc6, 0x3ac9, 0x2ef7, 0x3ade, 0x2e43, 0x3aee, 0x2da7, 0x3afc, 0x2d1f, 0x3b07, 0x2ca9, 0x3b10, 0x2c42, 0x3b17, 0x2bd1, 0x3b1c, 0x2b34, 0x3b1f, 0x2aaa, 0x3b22, 0x2a31, 0x3b23, 0x29c7, 0x3b23, 0x2968,
  16478. 0x32d4, 0x3a4b, 0x32dc, 0x3a45, 0x3308, 0x3a26, 0x3378, 0x39d0, 0x3425, 0x394a, 0x34c9, 0x38be, 0x359c, 0x383e, 0x3688, 0x3796, 0x3778, 0x36c4, 0x382f, 0x3603, 0x3898, 0x3553, 0x38f7, 0x34b3, 0x394b, 0x3424, 0x3994, 0x334c, 0x39d3, 0x326c, 0x3a08, 0x31a9, 0x3a35, 0x30fe, 0x3a5a, 0x306a, 0x3a78, 0x2fd1, 0x3a90, 0x2ef1, 0x3aa2, 0x2e2e, 0x3ab0, 0x2d86, 0x3aba, 0x2cf3, 0x3ac1, 0x2c74, 0x3ac4, 0x2c05, 0x3ac4, 0x2b49, 0x3ac2, 0x2aa1, 0x3abd, 0x2a0c, 0x3ab7, 0x298b, 0x3aaf, 0x2918, 0x3aa6, 0x28b3, 0x3a9b, 0x285a,
  16479. 0x3559, 0x3954, 0x355a, 0x3951, 0x3566, 0x3944, 0x3582, 0x391e, 0x35b6, 0x38d3, 0x360a, 0x386a, 0x3684, 0x37ed, 0x3720, 0x370d, 0x37d3, 0x3641, 0x3847, 0x3588, 0x38a3, 0x34e2, 0x38fa, 0x344d, 0x3948, 0x3391, 0x398d, 0x32a6, 0x39c8, 0x31d6, 0x39fa, 0x3121, 0x3a22, 0x3082, 0x3a43, 0x2ff0, 0x3a5c, 0x2f01, 0x3a6f, 0x2e32, 0x3a7c, 0x2d7e, 0x3a84, 0x2ce2, 0x3a87, 0x2c5b, 0x3a87, 0x2bcc, 0x3a83, 0x2b00, 0x3a7b, 0x2a4e, 0x3a71, 0x29b3, 0x3a66, 0x292c, 0x3a58, 0x28b4, 0x3a4b, 0x284b, 0x3a3d, 0x27dc, 0x3a2e, 0x2739,
  16480. 0x3709, 0x387c, 0x370a, 0x387b, 0x3710, 0x3874, 0x3720, 0x385f, 0x373d, 0x3834, 0x376a, 0x37e1, 0x37ac, 0x3732, 0x3805, 0x3675, 0x383f, 0x35bc, 0x3883, 0x3511, 0x38cb, 0x3476, 0x3912, 0x33d8, 0x3955, 0x32e2, 0x3991, 0x3208, 0x39c6, 0x3149, 0x39f1, 0x30a1, 0x3a15, 0x300f, 0x3a30, 0x2f21, 0x3a44, 0x2e45, 0x3a51, 0x2d87, 0x3a59, 0x2ce2, 0x3a5b, 0x2c53, 0x3a58, 0x2bb0, 0x3a52, 0x2ada, 0x3a49, 0x2a1f, 0x3a40, 0x297d, 0x3a34, 0x28f0, 0x3a25, 0x2874, 0x3a13, 0x2807, 0x3a00, 0x274e, 0x39eb, 0x26a6, 0x39d5, 0x2611,
  16481. 0x3840, 0x3780, 0x3840, 0x377e, 0x3842, 0x3776, 0x3846, 0x375e, 0x384f, 0x372a, 0x385b, 0x36d3, 0x386c, 0x3659, 0x3885, 0x35c7, 0x38a8, 0x352d, 0x38d4, 0x3497, 0x3906, 0x340c, 0x393b, 0x331a, 0x3970, 0x323a, 0x39a0, 0x3172, 0x39cb, 0x30c3, 0x39ef, 0x302a, 0x3a0c, 0x2f4a, 0x3a21, 0x2e63, 0x3a2f, 0x2d9b, 0x3a37, 0x2ced, 0x3a39, 0x2c57, 0x3a37, 0x2baa, 0x3a34, 0x2ac9, 0x3a2c, 0x2a05, 0x3a20, 0x295d, 0x3a11, 0x28ca, 0x39ff, 0x2849, 0x39eb, 0x27b2, 0x39d5, 0x26ed, 0x39be, 0x2640, 0x39a5, 0x25aa, 0x398b, 0x2523,
  16482. 0x38e2, 0x363b, 0x38e2, 0x363b, 0x38e3, 0x3635, 0x38e6, 0x3626, 0x38ea, 0x3606, 0x38f0, 0x35cd, 0x38f8, 0x3579, 0x3903, 0x350e, 0x3915, 0x3495, 0x392d, 0x3418, 0x394c, 0x3340, 0x3970, 0x3261, 0x3995, 0x3197, 0x39b8, 0x30e4, 0x39d8, 0x3046, 0x39f3, 0x2f76, 0x3a08, 0x2e86, 0x3a16, 0x2db5, 0x3a1e, 0x2cff, 0x3a22, 0x2c61, 0x3a24, 0x2bb3, 0x3a20, 0x2ac7, 0x3a17, 0x29fc, 0x3a0a, 0x294c, 0x39fa, 0x28b2, 0x39e7, 0x282e, 0x39d1, 0x2773, 0x39b9, 0x26a9, 0x399f, 0x25fa, 0x3985, 0x255f, 0x3968, 0x24d6, 0x394a, 0x245d,
  16483. 0x396e, 0x3524, 0x396e, 0x3524, 0x396e, 0x3520, 0x396f, 0x3517, 0x3971, 0x3502, 0x3973, 0x34dd, 0x3975, 0x34a5, 0x3978, 0x3458, 0x397e, 0x33f9, 0x3987, 0x3332, 0x3997, 0x326b, 0x39aa, 0x31ac, 0x39c0, 0x30fb, 0x39d7, 0x305c, 0x39eb, 0x2f9e, 0x39fc, 0x2ea7, 0x3a07, 0x2dcf, 0x3a0f, 0x2d13, 0x3a16, 0x2c70, 0x3a17, 0x2bc4, 0x3a14, 0x2ad0, 0x3a0a, 0x29fc, 0x39fd, 0x2945, 0x39ed, 0x28a6, 0x39d9, 0x281d, 0x39c2, 0x274a, 0x39a9, 0x267c, 0x398e, 0x25c7, 0x3971, 0x2528, 0x3952, 0x249e, 0x3931, 0x2425, 0x3910, 0x2374,
  16484. 0x39e5, 0x3436, 0x39e5, 0x3435, 0x39e5, 0x3434, 0x39e5, 0x342e, 0x39e5, 0x3420, 0x39e5, 0x3408, 0x39e3, 0x33c4, 0x39e1, 0x3359, 0x39df, 0x32d3, 0x39de, 0x323a, 0x39e1, 0x319a, 0x39e7, 0x30fb, 0x39f0, 0x3065, 0x39f9, 0x2fb6, 0x3a02, 0x2ec0, 0x3a08, 0x2de6, 0x3a0d, 0x2d26, 0x3a12, 0x2c7e, 0x3a13, 0x2bda, 0x3a0e, 0x2adc, 0x3a05, 0x2a02, 0x39f8, 0x2945, 0x39e7, 0x28a1, 0x39d3, 0x2813, 0x39bc, 0x2730, 0x39a2, 0x265c, 0x3985, 0x25a3, 0x3966, 0x2501, 0x3945, 0x2475, 0x3923, 0x23f3, 0x3901, 0x231c, 0x38dd, 0x225e,
  16485. 0x3a4b, 0x32d6, 0x3a4a, 0x32d6, 0x3a4a, 0x32d4, 0x3a4a, 0x32cc, 0x3a48, 0x32bb, 0x3a47, 0x329d, 0x3a43, 0x326b, 0x3a3d, 0x3222, 0x3a36, 0x31c2, 0x3a2e, 0x314f, 0x3a28, 0x30d2, 0x3a23, 0x3052, 0x3a20, 0x2fab, 0x3a1e, 0x2ec2, 0x3a1b, 0x2def, 0x3a19, 0x2d31, 0x3a1a, 0x2c89, 0x3a18, 0x2beb, 0x3a11, 0x2aea, 0x3a07, 0x2a0a, 0x39fa, 0x2948, 0x39e9, 0x28a1, 0x39d4, 0x280f, 0x39bd, 0x2721, 0x39a2, 0x2647, 0x3985, 0x258b, 0x3964, 0x24e5, 0x3942, 0x2455, 0x391f, 0x23b3, 0x38fb, 0x22d8, 0x38d4, 0x2219, 0x38ad, 0x2172,
  16486. 0x3aa0, 0x3180, 0x3aa0, 0x3180, 0x3aa0, 0x317f, 0x3a9f, 0x317b, 0x3a9d, 0x3170, 0x3a99, 0x315d, 0x3a95, 0x313d, 0x3a8d, 0x310c, 0x3a82, 0x30ca, 0x3a76, 0x3077, 0x3a69, 0x3019, 0x3a5c, 0x2f68, 0x3a4f, 0x2e9e, 0x3a42, 0x2dde, 0x3a37, 0x2d2b, 0x3a30, 0x2c89, 0x3a29, 0x2bef, 0x3a1f, 0x2af0, 0x3a12, 0x2a0f, 0x3a03, 0x294a, 0x39f1, 0x28a0, 0x39dc, 0x280c, 0x39c5, 0x2717, 0x39a9, 0x2638, 0x398b, 0x2578, 0x396a, 0x24d0, 0x3947, 0x243f, 0x3923, 0x2380, 0x38fc, 0x22a4, 0x38d4, 0x21e4, 0x38ac, 0x213c, 0x3883, 0x20a8,
  16487. 0x3ae8, 0x3062, 0x3ae8, 0x3062, 0x3ae7, 0x3061, 0x3ae6, 0x305f, 0x3ae4, 0x305a, 0x3ae0, 0x304f, 0x3ada, 0x303b, 0x3ad1, 0x301b, 0x3ac5, 0x2fdd, 0x3ab6, 0x2f6a, 0x3aa4, 0x2ede, 0x3a91, 0x2e45, 0x3a7c, 0x2da5, 0x3a67, 0x2d0a, 0x3a57, 0x2c77, 0x3a48, 0x2bdc, 0x3a38, 0x2ae5, 0x3a27, 0x2a0a, 0x3a16, 0x2947, 0x3a02, 0x289d, 0x39eb, 0x2808, 0x39d3, 0x270d, 0x39b6, 0x262b, 0x3997, 0x256a, 0x3976, 0x24bf, 0x3952, 0x242b, 0x392d, 0x2358, 0x3904, 0x227a, 0x38db, 0x21b8, 0x38b2, 0x2110, 0x3887, 0x207d, 0x385b, 0x1ff6,
  16488. 0x3b23, 0x2ee8, 0x3b23, 0x2ee8, 0x3b22, 0x2ee8, 0x3b21, 0x2ee7, 0x3b1f, 0x2ee3, 0x3b1a, 0x2ed6, 0x3b14, 0x2ec1, 0x3b0b, 0x2e99, 0x3afe, 0x2e60, 0x3aee, 0x2e12, 0x3ad8, 0x2dad, 0x3ac1, 0x2d3d, 0x3aa5, 0x2cc3, 0x3a8b, 0x2c48, 0x3a76, 0x2ba2, 0x3a60, 0x2ac0, 0x3a49, 0x29f2, 0x3a32, 0x2938, 0x3a1b, 0x2893, 0x3a02, 0x27ff, 0x39e8, 0x26ff, 0x39ca, 0x261e, 0x39aa, 0x255b, 0x3988, 0x24b0, 0x3964, 0x241c, 0x393d, 0x2336, 0x3913, 0x2257, 0x38e9, 0x2195, 0x38be, 0x20eb, 0x3891, 0x2059, 0x3864, 0x1fae, 0x3837, 0x1ecd,
  16489. 0x3b54, 0x2d61, 0x3b54, 0x2d61, 0x3b53, 0x2d61, 0x3b52, 0x2d62, 0x3b4f, 0x2d61, 0x3b4b, 0x2d5c, 0x3b45, 0x2d51, 0x3b3b, 0x2d3d, 0x3b2e, 0x2d1a, 0x3b1d, 0x2ce7, 0x3b06, 0x2ca3, 0x3aeb, 0x2c52, 0x3acb, 0x2bee, 0x3ab0, 0x2b31, 0x3a94, 0x2a74, 0x3a77, 0x29bf, 0x3a5a, 0x2915, 0x3a3f, 0x287a, 0x3a22, 0x27de, 0x3a05, 0x26e4, 0x39e5, 0x2609, 0x39c3, 0x2547, 0x39a0, 0x249f, 0x397b, 0x240c, 0x3953, 0x2314, 0x3928, 0x2238, 0x38fd, 0x2175, 0x38d0, 0x20cb, 0x38a2, 0x2038, 0x3873, 0x1f71, 0x3844, 0x1e90, 0x3815, 0x1dce,
  16490. 0x3b7c, 0x2c22, 0x3b7c, 0x2c22, 0x3b7b, 0x2c23, 0x3b7a, 0x2c25, 0x3b77, 0x2c27, 0x3b73, 0x2c26, 0x3b6d, 0x2c23, 0x3b64, 0x2c1a, 0x3b57, 0x2c07, 0x3b46, 0x2bd1, 0x3b2e, 0x2b79, 0x3b0f, 0x2b07, 0x3aef, 0x2a86, 0x3ad1, 0x29f8, 0x3ab0, 0x2967, 0x3a8e, 0x28d7, 0x3a6d, 0x284e, 0x3a4c, 0x279f, 0x3a2b, 0x26b7, 0x3a08, 0x25e5, 0x39e4, 0x252c, 0x39be, 0x2488, 0x3998, 0x23f0, 0x396f, 0x22f2, 0x3943, 0x2215, 0x3917, 0x2155, 0x38e8, 0x20ae, 0x38b9, 0x201c, 0x3888, 0x1f38, 0x3857, 0x1e5a, 0x3826, 0x1d9a, 0x37eb, 0x1cf0,
  16491. 0x3b9c, 0x2a43, 0x3b9c, 0x2a43, 0x3b9b, 0x2a46, 0x3b9a, 0x2a4a, 0x3b98, 0x2a50, 0x3b93, 0x2a54, 0x3b8e, 0x2a59, 0x3b85, 0x2a56, 0x3b79, 0x2a45, 0x3b67, 0x2a24, 0x3b4f, 0x29ee, 0x3b2f, 0x29a4, 0x3b10, 0x294b, 0x3aef, 0x28e5, 0x3ac9, 0x2877, 0x3aa4, 0x2809, 0x3a7e, 0x2739, 0x3a59, 0x266d, 0x3a34, 0x25af, 0x3a0c, 0x2503, 0x39e4, 0x2468, 0x39bb, 0x23bb, 0x3990, 0x22c6, 0x3963, 0x21f0, 0x3936, 0x2133, 0x3906, 0x208f, 0x38d5, 0x1ffd, 0x38a3, 0x1f04, 0x3870, 0x1e28, 0x383d, 0x1d69, 0x380b, 0x1cc3, 0x37b0, 0x1c32,
  16492. 0x3bb5, 0x28aa, 0x3bb5, 0x28ab, 0x3bb5, 0x28ad, 0x3bb4, 0x28b2, 0x3bb2, 0x28b9, 0x3bae, 0x28c2, 0x3ba8, 0x28ca, 0x3ba0, 0x28d1, 0x3b94, 0x28cd, 0x3b83, 0x28c1, 0x3b6a, 0x28a3, 0x3b4b, 0x2876, 0x3b2d, 0x283d, 0x3b09, 0x27ea, 0x3ae1, 0x274b, 0x3ab9, 0x26a6, 0x3a8f, 0x25fe, 0x3a67, 0x255d, 0x3a3d, 0x24c5, 0x3a11, 0x2439, 0x39e6, 0x2371, 0x39b9, 0x228d, 0x398a, 0x21c1, 0x395a, 0x210b, 0x3929, 0x206c, 0x38f7, 0x1fc1, 0x38c3, 0x1ecb, 0x388f, 0x1df6, 0x385a, 0x1d3a, 0x3825, 0x1c99, 0x37e1, 0x1c08, 0x3779, 0x1b1b,
  16493. 0x3bc9, 0x26d3, 0x3bc9, 0x26d4, 0x3bc9, 0x26d9, 0x3bc8, 0x26e3, 0x3bc6, 0x26ef, 0x3bc2, 0x2705, 0x3bbd, 0x271a, 0x3bb6, 0x2731, 0x3baa, 0x273c, 0x3b9a, 0x273d, 0x3b81, 0x2726, 0x3b65, 0x26f7, 0x3b46, 0x26af, 0x3b20, 0x2650, 0x3af7, 0x25e1, 0x3acd, 0x256a, 0x3aa1, 0x24eb, 0x3a75, 0x246f, 0x3a46, 0x23ee, 0x3a17, 0x230d, 0x39e9, 0x223e, 0x39b7, 0x2183, 0x3985, 0x20d8, 0x3953, 0x2043, 0x391e, 0x1f7a, 0x38e9, 0x1e8d, 0x38b3, 0x1dbf, 0x387c, 0x1d0b, 0x3845, 0x1c6c, 0x380e, 0x1bc4, 0x37b0, 0x1ad2, 0x3745, 0x19fd,
  16494. 0x3bd9, 0x24e4, 0x3bd9, 0x24e5, 0x3bd9, 0x24e8, 0x3bd8, 0x24f2, 0x3bd5, 0x24fe, 0x3bd2, 0x2512, 0x3bce, 0x252b, 0x3bc6, 0x2544, 0x3bbc, 0x255a, 0x3bac, 0x256b, 0x3b93, 0x2569, 0x3b7a, 0x2557, 0x3b5b, 0x252f, 0x3b34, 0x24f7, 0x3b0c, 0x24ad, 0x3adf, 0x2458, 0x3ab1, 0x23f8, 0x3a82, 0x233f, 0x3a4f, 0x2286, 0x3a1e, 0x21d5, 0x39eb, 0x2130, 0x39b6, 0x2098, 0x3982, 0x200e, 0x394b, 0x1f25, 0x3914, 0x1e45, 0x38dc, 0x1d83, 0x38a3, 0x1cd6, 0x386b, 0x1c3d, 0x3831, 0x1b71, 0x37f2, 0x1a87, 0x3782, 0x19bc, 0x3714, 0x1909,
  16495. 0x3be5, 0x22d8, 0x3be5, 0x22d9, 0x3be4, 0x22df, 0x3be4, 0x22ef, 0x3be1, 0x2305, 0x3bde, 0x232a, 0x3bda, 0x2358, 0x3bd4, 0x2392, 0x3bcb, 0x23ca, 0x3bbb, 0x23f4, 0x3ba3, 0x2405, 0x3b8c, 0x2405, 0x3b6c, 0x23ec, 0x3b47, 0x23ae, 0x3b1d, 0x2353, 0x3af0, 0x22e2, 0x3ac0, 0x2261, 0x3a8e, 0x21d9, 0x3a5a, 0x214e, 0x3a26, 0x20c7, 0x39ee, 0x2045, 0x39b7, 0x1f97, 0x397f, 0x1eba, 0x3945, 0x1df0, 0x390b, 0x1d3a, 0x38d0, 0x1c9a, 0x3895, 0x1c0a, 0x385a, 0x1b18, 0x381f, 0x1a39, 0x37c9, 0x1975, 0x3756, 0x18cc, 0x36e6, 0x1836,
  16496. 0x3bed, 0x20a8, 0x3bed, 0x20a9, 0x3bed, 0x20ae, 0x3bed, 0x20bb, 0x3beb, 0x20cf, 0x3be8, 0x20ef, 0x3be4, 0x2119, 0x3bde, 0x214f, 0x3bd6, 0x2189, 0x3bc6, 0x21b8, 0x3bb1, 0x21de, 0x3b9a, 0x21f2, 0x3b7b, 0x21f2, 0x3b57, 0x21d8, 0x3b2d, 0x21a4, 0x3b00, 0x215f, 0x3acf, 0x2108, 0x3a99, 0x20a8, 0x3a64, 0x2043, 0x3a2c, 0x1fba, 0x39f2, 0x1ef3, 0x39b8, 0x1e36, 0x397c, 0x1d86, 0x3940, 0x1ce5, 0x3903, 0x1c52, 0x38c6, 0x1b9e, 0x3888, 0x1ab3, 0x384a, 0x19e4, 0x380e, 0x192b, 0x37a3, 0x188b, 0x372d, 0x17f7, 0x36ba, 0x1701,
  16497. 0x3bf4, 0x1e23, 0x3bf4, 0x1e25, 0x3bf4, 0x1e2d, 0x3bf3, 0x1e41, 0x3bf1, 0x1e64, 0x3bef, 0x1e9c, 0x3beb, 0x1ee1, 0x3be6, 0x1f40, 0x3bde, 0x1fa7, 0x3bce, 0x2001, 0x3bbd, 0x202f, 0x3ba6, 0x204e, 0x3b88, 0x205f, 0x3b64, 0x205b, 0x3b3b, 0x2044, 0x3b0e, 0x201f, 0x3adb, 0x1fcf, 0x3aa6, 0x1f4e, 0x3a6e, 0x1ec1, 0x3a33, 0x1e2b, 0x39f7, 0x1d95, 0x39ba, 0x1d06, 0x397b, 0x1c7d, 0x393c, 0x1bfc, 0x38fc, 0x1b13, 0x38bc, 0x1a40, 0x387c, 0x1983, 0x383c, 0x18da, 0x37fa, 0x1842, 0x377f, 0x177f, 0x3706, 0x1695, 0x3691, 0x15c8,
  16498. 0x3bf8, 0x1bca, 0x3bf8, 0x1bcc, 0x3bf8, 0x1bd8, 0x3bf8, 0x1bf7, 0x3bf6, 0x1c1b, 0x3bf4, 0x1c45, 0x3bf1, 0x1c83, 0x3bec, 0x1cce, 0x3be4, 0x1d21, 0x3bd5, 0x1d78, 0x3bc5, 0x1dd1, 0x3bb0, 0x1e17, 0x3b93, 0x1e4a, 0x3b70, 0x1e5f, 0x3b48, 0x1e57, 0x3b1b, 0x1e35, 0x3ae7, 0x1df6, 0x3ab2, 0x1da4, 0x3a77, 0x1d44, 0x3a3a, 0x1cdb, 0x39fc, 0x1c6e, 0x39bb, 0x1c03, 0x397a, 0x1b35, 0x3938, 0x1a72, 0x38f5, 0x19bb, 0x38b3, 0x1914, 0x3870, 0x187d, 0x382e, 0x17eb, 0x37db, 0x16f9, 0x375c, 0x1621, 0x36e1, 0x1565, 0x3669, 0x14be,
  16499. 0x3bfb, 0x18b9, 0x3bfb, 0x18ba, 0x3bfb, 0x18c3, 0x3bfb, 0x18da, 0x3bf9, 0x190a, 0x3bf7, 0x1948, 0x3bf5, 0x19ac, 0x3bf0, 0x1a20, 0x3be9, 0x1ab3, 0x3bdb, 0x1b49, 0x3bcd, 0x1be6, 0x3bb7, 0x1c34, 0x3b9c, 0x1c6d, 0x3b7a, 0x1c8e, 0x3b54, 0x1c9e, 0x3b26, 0x1c96, 0x3af2, 0x1c75, 0x3abc, 0x1c47, 0x3a80, 0x1c09, 0x3a42, 0x1b85, 0x3a01, 0x1aec, 0x39be, 0x1a50, 0x397a, 0x19b5, 0x3935, 0x1921, 0x38f0, 0x1895, 0x38aa, 0x1814, 0x3866, 0x173a, 0x3821, 0x1665, 0x37be, 0x15a4, 0x373c, 0x14f9, 0x36be, 0x1460, 0x3644, 0x13b3,
  16500. 0x3bfd, 0x156b, 0x3bfd, 0x156c, 0x3bfd, 0x1578, 0x3bfd, 0x1598, 0x3bfc, 0x15dd, 0x3bfa, 0x163c, 0x3bf7, 0x16cb, 0x3bf3, 0x177b, 0x3beb, 0x1833, 0x3be0, 0x18ad, 0x3bd2, 0x192e, 0x3bbd, 0x19a6, 0x3ba4, 0x1a0c, 0x3b83, 0x1a5a, 0x3b5d, 0x1a8c, 0x3b30, 0x1a9b, 0x3afd, 0x1a86, 0x3ac6, 0x1a5c, 0x3a89, 0x1a11, 0x3a49, 0x19b7, 0x3a06, 0x194f, 0x39c1, 0x18e3, 0x397a, 0x1873, 0x3933, 0x1805, 0x38eb, 0x173a, 0x38a3, 0x1676, 0x385c, 0x15bf, 0x3816, 0x1519, 0x37a2, 0x1482, 0x371d, 0x13f7, 0x369c, 0x1306, 0x3620, 0x1231,
  16501. 0x3bff, 0x11cb, 0x3bff, 0x11cd, 0x3bfe, 0x11dd, 0x3bfe, 0x1219, 0x3bfd, 0x126b, 0x3bfb, 0x12e9, 0x3bf9, 0x13c5, 0x3bf5, 0x1460, 0x3bee, 0x150f, 0x3be3, 0x15c9, 0x3bd6, 0x168a, 0x3bc3, 0x174f, 0x3baa, 0x1806, 0x3b8b, 0x184f, 0x3b66, 0x1888, 0x3b39, 0x18a6, 0x3b07, 0x18ad, 0x3acf, 0x189c, 0x3a92, 0x1876, 0x3a50, 0x1840, 0x3a0c, 0x17fd, 0x39c4, 0x176a, 0x397b, 0x16ce, 0x3931, 0x1634, 0x38e6, 0x1599, 0x389c, 0x1508, 0x3852, 0x147f, 0x380a, 0x1401, 0x3788, 0x131c, 0x36ff, 0x124a, 0x367c, 0x1190, 0x35fe, 0x10ea,
  16502. 0x3bff, 0x0daa, 0x3bff, 0x0dad, 0x3bff, 0x0dc0, 0x3bff, 0x0e0e, 0x3bfe, 0x0e87, 0x3bfc, 0x0f14, 0x3bfb, 0x1029, 0x3bf7, 0x10d1, 0x3bf0, 0x11d3, 0x3be6, 0x12c9, 0x3bd9, 0x13fc, 0x3bc7, 0x1499, 0x3bb0, 0x152a, 0x3b92, 0x15ab, 0x3b6e, 0x1615, 0x3b42, 0x165a, 0x3b10, 0x1681, 0x3ad8, 0x1683, 0x3a9a, 0x1665, 0x3a57, 0x1629, 0x3a11, 0x15dd, 0x39c8, 0x1580, 0x397c, 0x1518, 0x3930, 0x14ae, 0x38e3, 0x1441, 0x3896, 0x13b1, 0x384a, 0x12e9, 0x37ff, 0x122f, 0x376f, 0x1182, 0x36e3, 0x10e5, 0x365e, 0x1057, 0x35de, 0x0fac,
  16503. 0x3c00, 0x08ea, 0x3c00, 0x08ed, 0x3c00, 0x0902, 0x3c00, 0x0961, 0x3bff, 0x09f3, 0x3bfd, 0x0abc, 0x3bfb, 0x0c1f, 0x3bf8, 0x0d15, 0x3bf1, 0x0e5b, 0x3be8, 0x0fb4, 0x3bdc, 0x10b0, 0x3bcb, 0x1190, 0x3bb5, 0x126c, 0x3b97, 0x132c, 0x3b74, 0x13de, 0x3b4a, 0x1432, 0x3b18, 0x145e, 0x3ae0, 0x1472, 0x3aa2, 0x146f, 0x3a5f, 0x1456, 0x3a17, 0x142e, 0x39cc, 0x13ee, 0x397e, 0x136b, 0x392f, 0x12e1, 0x38df, 0x124f, 0x3890, 0x11bd, 0x3842, 0x1131, 0x37eb, 0x10ac, 0x3757, 0x102e, 0x36c9, 0x0f76, 0x3640, 0x0ea3, 0x35bf, 0x0de4,
  16504. 0x3c00, 0x039b, 0x3c00, 0x039d, 0x3c00, 0x03b2, 0x3c00, 0x041c, 0x3bff, 0x04be, 0x3bfd, 0x05d6, 0x3bfc, 0x0764, 0x3bf8, 0x08e2, 0x3bf2, 0x0a67, 0x3bea, 0x0c1b, 0x3bde, 0x0d41, 0x3bcd, 0x0e5f, 0x3bb8, 0x0f8c, 0x3b9c, 0x1057, 0x3b7a, 0x10e5, 0x3b51, 0x1155, 0x3b20, 0x11a5, 0x3ae8, 0x11da, 0x3aaa, 0x11ef, 0x3a66, 0x11e5, 0x3a1d, 0x11c1, 0x39d0, 0x1185, 0x3980, 0x113b, 0x392e, 0x10e5, 0x38dc, 0x1087, 0x388b, 0x1028, 0x383b, 0x0f94, 0x37d9, 0x0edb, 0x3741, 0x0e2c, 0x36af, 0x0d89, 0x3625, 0x0cf2, 0x35a1, 0x0c69,
  16505. 0x3c00, 0x0107, 0x3c00, 0x0108, 0x3c00, 0x0110, 0x3c00, 0x0145, 0x3bff, 0x0197, 0x3bfe, 0x0224, 0x3bfc, 0x030c, 0x3bf8, 0x0478, 0x3bf3, 0x062c, 0x3beb, 0x0833, 0x3be0, 0x0979, 0x3bd0, 0x0aeb, 0x3bbc, 0x0c3d, 0x3ba0, 0x0d01, 0x3b80, 0x0dbd, 0x3b57, 0x0e69, 0x3b27, 0x0eeb, 0x3af0, 0x0f53, 0x3ab1, 0x0f8a, 0x3a6c, 0x0f9f, 0x3a22, 0x0f8b, 0x39d4, 0x0f5b, 0x3982, 0x0f0f, 0x392f, 0x0eac, 0x38da, 0x0e3d, 0x3886, 0x0dc9, 0x3834, 0x0d51, 0x37c7, 0x0cd9, 0x372c, 0x0c65, 0x3697, 0x0bef, 0x360a, 0x0b20, 0x3585, 0x0a62,
  16506. 0x3c00, 0x0031, 0x3c00, 0x0031, 0x3c00, 0x0034, 0x3c00, 0x004b, 0x3bff, 0x006f, 0x3bfe, 0x00c9, 0x3bfc, 0x011b, 0x3bf9, 0x0207, 0x3bf4, 0x02d6, 0x3bec, 0x0415, 0x3be1, 0x0587, 0x3bd2, 0x0703, 0x3bbf, 0x087d, 0x3ba5, 0x096a, 0x3b85, 0x0a59, 0x3b5d, 0x0b32, 0x3b2e, 0x0bee, 0x3af7, 0x0c44, 0x3ab8, 0x0c7c, 0x3a73, 0x0c9c, 0x3a28, 0x0ca4, 0x39d8, 0x0c98, 0x3985, 0x0c77, 0x392f, 0x0c4a, 0x38d9, 0x0c10, 0x3882, 0x0ba0, 0x382e, 0x0b14, 0x37b6, 0x0a84, 0x3717, 0x09f5, 0x3680, 0x0969, 0x35f0, 0x08e6, 0x356a, 0x086a,
  16507. 0x3c00, 0x0004, 0x3c00, 0x0004, 0x3c00, 0x0004, 0x3c00, 0x000d, 0x3bff, 0x0021, 0x3bfe, 0x003b, 0x3bfd, 0x0070, 0x3bf9, 0x00c7, 0x3bf4, 0x012e, 0x3bed, 0x01c8, 0x3be3, 0x0274, 0x3bd4, 0x033b, 0x3bc1, 0x043a, 0x3ba8, 0x0534, 0x3b89, 0x0641, 0x3b62, 0x073b, 0x3b34, 0x0815, 0x3afd, 0x087c, 0x3abf, 0x08d0, 0x3a7a, 0x090a, 0x3a2e, 0x092c, 0x39dd, 0x0936, 0x3988, 0x0928, 0x3930, 0x0907, 0x38d7, 0x08d7, 0x387f, 0x089b, 0x3828, 0x0855, 0x37a7, 0x080b, 0x3704, 0x077b, 0x366a, 0x06e1, 0x35d8, 0x0649, 0x3550, 0x05b8,
  16508. 0x3c00, 0x0000, 0x3c00, 0x0000, 0x3c00, 0x0000, 0x3c00, 0x0003, 0x3bff, 0x0012, 0x3bfe, 0x001a, 0x3bfd, 0x0035, 0x3bfa, 0x0050, 0x3bf4, 0x0061, 0x3bed, 0x00a5, 0x3be4, 0x00ee, 0x3bd6, 0x0146, 0x3bc3, 0x01ab, 0x3bab, 0x0211, 0x3b8d, 0x028e, 0x3b67, 0x0303, 0x3b39, 0x0375, 0x3b04, 0x03e2, 0x3ac6, 0x0441, 0x3a80, 0x0492, 0x3a34, 0x04cd, 0x39e1, 0x04f2, 0x398b, 0x0504, 0x3931, 0x0502, 0x38d6, 0x04ec, 0x387c, 0x04c7, 0x3822, 0x0496, 0x3798, 0x045c, 0x36f2, 0x041a, 0x3655, 0x03d5, 0x35c1, 0x038e, 0x3537, 0x0347
  16509. ] );
  16510. let lut = null;
  16511. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  16512. if ( lut === null ) {
  16513. lut = new DataTexture( DATA, 32, 32, RGFormat, HalfFloatType );
  16514. lut.minFilter = LinearFilter;
  16515. lut.magFilter = LinearFilter;
  16516. lut.wrapS = ClampToEdgeWrapping;
  16517. lut.wrapT = ClampToEdgeWrapping;
  16518. lut.generateMipmaps = false;
  16519. lut.needsUpdate = true;
  16520. }
  16521. const uv = vec2( roughness, dotNV );
  16522. return texture( lut, uv ).rg;
  16523. } );
  16524. // GGX BRDF with multi-scattering energy compensation for direct lighting
  16525. // This provides more accurate energy conservation, especially for rough materials
  16526. // Based on "Practical Multiple Scattering Compensation for Microfacet Models"
  16527. // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf
  16528. const BRDF_GGX_Multiscatter = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16529. // Single-scattering BRDF (standard GGX)
  16530. const singleScatter = BRDF_GGX( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } );
  16531. // Multi-scattering compensation
  16532. const dotNL = normalView.dot( lightDirection ).clamp();
  16533. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16534. // Precomputed DFG values for view and light directions
  16535. const dfgV = DFGApprox( { roughness: _roughness, dotNV } );
  16536. const dfgL = DFGApprox( { roughness: _roughness, dotNV: dotNL } );
  16537. // Single-scattering energy for view and light
  16538. const FssEss_V = f0.mul( dfgV.x ).add( f90.mul( dfgV.y ) );
  16539. const FssEss_L = f0.mul( dfgL.x ).add( f90.mul( dfgL.y ) );
  16540. const Ess_V = dfgV.x.add( dfgV.y );
  16541. const Ess_L = dfgL.x.add( dfgL.y );
  16542. // Energy lost to multiple scattering
  16543. const Ems_V = float( 1.0 ).sub( Ess_V );
  16544. const Ems_L = float( 1.0 ).sub( Ess_L );
  16545. // Average Fresnel reflectance
  16546. const Favg = f0.add( f0.oneMinus().mul( 0.047619 ) ); // 1/21
  16547. // Multiple scattering contribution
  16548. // Uses geometric mean of view and light contributions for better energy distribution
  16549. 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 ) );
  16550. // Energy compensation factor
  16551. const compensationFactor = Ems_V.mul( Ems_L );
  16552. const multiScatter = Fms.mul( compensationFactor );
  16553. return singleScatter.add( multiScatter );
  16554. } );
  16555. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  16556. const { dotNV, specularColor, specularF90, roughness } = inputs;
  16557. const fab = DFGApprox( { dotNV, roughness } );
  16558. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16559. } );
  16560. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  16561. const x = dotVH.oneMinus().saturate();
  16562. const x2 = x.mul( x );
  16563. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  16564. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  16565. } ).setLayout( {
  16566. name: 'Schlick_to_F0',
  16567. type: 'vec3',
  16568. inputs: [
  16569. { name: 'f', type: 'vec3' },
  16570. { name: 'f90', type: 'float' },
  16571. { name: 'dotVH', type: 'float' }
  16572. ]
  16573. } );
  16574. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16575. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  16576. const alpha = roughness.pow2();
  16577. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  16578. const invAlpha = float( 1.0 ).div( alpha );
  16579. const cos2h = dotNH.pow2();
  16580. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  16581. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  16582. } ).setLayout( {
  16583. name: 'D_Charlie',
  16584. type: 'float',
  16585. inputs: [
  16586. { name: 'roughness', type: 'float' },
  16587. { name: 'dotNH', type: 'float' }
  16588. ]
  16589. } );
  16590. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16591. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  16592. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  16593. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  16594. } ).setLayout( {
  16595. name: 'V_Neubelt',
  16596. type: 'float',
  16597. inputs: [
  16598. { name: 'dotNV', type: 'float' },
  16599. { name: 'dotNL', type: 'float' }
  16600. ]
  16601. } );
  16602. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16603. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16604. const dotNL = normalView.dot( lightDirection ).clamp();
  16605. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16606. const dotNH = normalView.dot( halfDir ).clamp();
  16607. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  16608. const V = V_Neubelt( { dotNV, dotNL } );
  16609. return sheen.mul( D ).mul( V );
  16610. } );
  16611. // Rect Area Light
  16612. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  16613. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  16614. // code: https://github.com/selfshadow/ltc_code/
  16615. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  16616. const LUT_SIZE = 64.0;
  16617. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  16618. const LUT_BIAS = 0.5 / LUT_SIZE;
  16619. const dotNV = N.dot( V ).saturate();
  16620. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  16621. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  16622. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  16623. return uv;
  16624. } ).setLayout( {
  16625. name: 'LTC_Uv',
  16626. type: 'vec2',
  16627. inputs: [
  16628. { name: 'N', type: 'vec3' },
  16629. { name: 'V', type: 'vec3' },
  16630. { name: 'roughness', type: 'float' }
  16631. ]
  16632. } );
  16633. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  16634. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  16635. // An approximation of the form factor of a horizon-clipped rectangle.
  16636. const l = f.length();
  16637. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  16638. } ).setLayout( {
  16639. name: 'LTC_ClippedSphereFormFactor',
  16640. type: 'float',
  16641. inputs: [
  16642. { name: 'f', type: 'vec3' }
  16643. ]
  16644. } );
  16645. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  16646. const x = v1.dot( v2 );
  16647. const y = x.abs().toVar();
  16648. // rational polynomial approximation to theta / sin( theta ) / 2PI
  16649. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  16650. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  16651. const v = a.div( b );
  16652. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  16653. return v1.cross( v2 ).mul( theta_sintheta );
  16654. } ).setLayout( {
  16655. name: 'LTC_EdgeVectorFormFactor',
  16656. type: 'vec3',
  16657. inputs: [
  16658. { name: 'v1', type: 'vec3' },
  16659. { name: 'v2', type: 'vec3' }
  16660. ]
  16661. } );
  16662. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  16663. // bail if point is on back side of plane of light
  16664. // assumes ccw winding order of light vertices
  16665. const v1 = p1.sub( p0 ).toVar();
  16666. const v2 = p3.sub( p0 ).toVar();
  16667. const lightNormal = v1.cross( v2 );
  16668. const result = vec3().toVar();
  16669. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16670. // construct orthonormal basis around N
  16671. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  16672. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  16673. // compute transform
  16674. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  16675. // transform rect
  16676. // & project rect onto sphere
  16677. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  16678. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  16679. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  16680. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  16681. // calculate vector form factor
  16682. const vectorFormFactor = vec3( 0 ).toVar();
  16683. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16684. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16685. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16686. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16687. // adjust for horizon clipping
  16688. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  16689. } );
  16690. return result;
  16691. } ).setLayout( {
  16692. name: 'LTC_Evaluate',
  16693. type: 'vec3',
  16694. inputs: [
  16695. { name: 'N', type: 'vec3' },
  16696. { name: 'V', type: 'vec3' },
  16697. { name: 'P', type: 'vec3' },
  16698. { name: 'mInv', type: 'mat3' },
  16699. { name: 'p0', type: 'vec3' },
  16700. { name: 'p1', type: 'vec3' },
  16701. { name: 'p2', type: 'vec3' },
  16702. { name: 'p3', type: 'vec3' }
  16703. ]
  16704. } );
  16705. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  16706. // bail if point is on back side of plane of light
  16707. // assumes ccw winding order of light vertices
  16708. const v1 = p1.sub( p0 ).toVar();
  16709. const v2 = p3.sub( p0 ).toVar();
  16710. const lightNormal = v1.cross( v2 );
  16711. const result = vec3().toVar();
  16712. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16713. // transform rect
  16714. // & project rect onto sphere
  16715. const coords0 = p0.sub( P ).normalize().toVar();
  16716. const coords1 = p1.sub( P ).normalize().toVar();
  16717. const coords2 = p2.sub( P ).normalize().toVar();
  16718. const coords3 = p3.sub( P ).normalize().toVar();
  16719. // calculate vector form factor
  16720. const vectorFormFactor = vec3( 0 ).toVar();
  16721. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16722. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16723. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16724. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16725. // adjust for horizon clipping
  16726. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  16727. } );
  16728. return result;
  16729. } ).setLayout( {
  16730. name: 'LTC_Evaluate',
  16731. type: 'vec3',
  16732. inputs: [
  16733. { name: 'P', type: 'vec3' },
  16734. { name: 'p0', type: 'vec3' },
  16735. { name: 'p1', type: 'vec3' },
  16736. { name: 'p2', type: 'vec3' },
  16737. { name: 'p3', type: 'vec3' }
  16738. ]
  16739. } );
  16740. // Mipped Bicubic Texture Filtering by N8
  16741. // https://www.shadertoy.com/view/Dl2SDW
  16742. const bC = 1.0 / 6.0;
  16743. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  16744. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  16745. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  16746. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  16747. const g0 = ( a ) => w0( a ).add( w1( a ) );
  16748. const g1 = ( a ) => w2( a ).add( w3( a ) );
  16749. // h0 and h1 are the two offset functions
  16750. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  16751. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  16752. const bicubic = ( textureNode, texelSize, lod ) => {
  16753. const uv = textureNode.uvNode;
  16754. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  16755. const iuv = floor( uvScaled );
  16756. const fuv = fract( uvScaled );
  16757. const g0x = g0( fuv.x );
  16758. const g1x = g1( fuv.x );
  16759. const h0x = h0( fuv.x );
  16760. const h1x = h1( fuv.x );
  16761. const h0y = h0( fuv.y );
  16762. const h1y = h1( fuv.y );
  16763. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16764. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16765. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16766. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16767. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  16768. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  16769. return a.add( b );
  16770. };
  16771. /**
  16772. * Applies mipped bicubic texture filtering to the given texture node.
  16773. *
  16774. * @tsl
  16775. * @function
  16776. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16777. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  16778. * @return {Node} The filtered texture sample.
  16779. */
  16780. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  16781. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  16782. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  16783. const fLodSizeInv = div( 1.0, fLodSize );
  16784. const cLodSizeInv = div( 1.0, cLodSize );
  16785. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  16786. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  16787. return fract( lodNode ).mix( fSample, cSample );
  16788. } );
  16789. /**
  16790. * Applies mipped bicubic texture filtering to the given texture node.
  16791. *
  16792. * @tsl
  16793. * @function
  16794. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16795. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  16796. * @return {Node} The filtered texture sample.
  16797. */
  16798. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  16799. const lod = strength.mul( maxMipLevel( textureNode ) );
  16800. return textureBicubicLevel( textureNode, lod );
  16801. } );
  16802. //
  16803. // Transmission
  16804. //
  16805. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  16806. // Direction of refracted light.
  16807. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  16808. // Compute rotation-independent scaling of the model matrix.
  16809. const modelScale = vec3(
  16810. length( modelMatrix[ 0 ].xyz ),
  16811. length( modelMatrix[ 1 ].xyz ),
  16812. length( modelMatrix[ 2 ].xyz )
  16813. );
  16814. // The thickness is specified in local space.
  16815. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  16816. } ).setLayout( {
  16817. name: 'getVolumeTransmissionRay',
  16818. type: 'vec3',
  16819. inputs: [
  16820. { name: 'n', type: 'vec3' },
  16821. { name: 'v', type: 'vec3' },
  16822. { name: 'thickness', type: 'float' },
  16823. { name: 'ior', type: 'float' },
  16824. { name: 'modelMatrix', type: 'mat4' }
  16825. ]
  16826. } );
  16827. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  16828. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  16829. // an IOR of 1.5 results in the default amount of microfacet refraction.
  16830. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  16831. } ).setLayout( {
  16832. name: 'applyIorToRoughness',
  16833. type: 'float',
  16834. inputs: [
  16835. { name: 'roughness', type: 'float' },
  16836. { name: 'ior', type: 'float' }
  16837. ]
  16838. } );
  16839. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  16840. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  16841. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  16842. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  16843. const transmissionSample = vTexture.sample( fragCoord );
  16844. //const transmissionSample = viewportMipTexture( fragCoord );
  16845. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  16846. return textureBicubicLevel( transmissionSample, lod );
  16847. } );
  16848. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  16849. If( attenuationDistance.notEqual( 0 ), () => {
  16850. // Compute light attenuation using Beer's law.
  16851. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  16852. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  16853. return transmittance;
  16854. } );
  16855. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  16856. return vec3( 1.0 );
  16857. } ).setLayout( {
  16858. name: 'volumeAttenuation',
  16859. type: 'vec3',
  16860. inputs: [
  16861. { name: 'transmissionDistance', type: 'float' },
  16862. { name: 'attenuationColor', type: 'vec3' },
  16863. { name: 'attenuationDistance', type: 'float' }
  16864. ]
  16865. } );
  16866. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  16867. let transmittedLight, transmittance;
  16868. if ( dispersion ) {
  16869. transmittedLight = vec4().toVar();
  16870. transmittance = vec3().toVar();
  16871. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  16872. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  16873. Loop( { start: 0, end: 3 }, ( { i } ) => {
  16874. const ior = iors.element( i );
  16875. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16876. const refractedRayExit = position.add( transmissionRay );
  16877. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16878. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16879. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16880. refractionCoords.addAssign( 1.0 );
  16881. refractionCoords.divAssign( 2.0 );
  16882. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16883. // Sample framebuffer to get pixel the refracted ray hits.
  16884. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  16885. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  16886. transmittedLight.a.addAssign( transmissionSample.a );
  16887. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  16888. } );
  16889. transmittedLight.a.divAssign( 3.0 );
  16890. } else {
  16891. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16892. const refractedRayExit = position.add( transmissionRay );
  16893. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16894. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16895. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16896. refractionCoords.addAssign( 1.0 );
  16897. refractionCoords.divAssign( 2.0 );
  16898. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16899. // Sample framebuffer to get pixel the refracted ray hits.
  16900. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  16901. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  16902. }
  16903. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  16904. const dotNV = n.dot( v ).clamp();
  16905. // Get the specular component.
  16906. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  16907. dotNV,
  16908. specularColor,
  16909. specularF90,
  16910. roughness
  16911. } ) );
  16912. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  16913. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  16914. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  16915. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  16916. } );
  16917. //
  16918. // Iridescence
  16919. //
  16920. // XYZ to linear-sRGB color space
  16921. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  16922. 3.2404542, -0.969266, 0.0556434,
  16923. -1.5371385, 1.8760108, -0.2040259,
  16924. -0.4985314, 0.0415560, 1.0572252
  16925. );
  16926. // Assume air interface for top
  16927. // Note: We don't handle the case fresnel0 == 1
  16928. const Fresnel0ToIor = ( fresnel0 ) => {
  16929. const sqrtF0 = fresnel0.sqrt();
  16930. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  16931. };
  16932. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  16933. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  16934. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  16935. };
  16936. // Fresnel equations for dielectric/dielectric interfaces.
  16937. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  16938. // Evaluation XYZ sensitivity curves in Fourier space
  16939. const evalSensitivity = ( OPD, shift ) => {
  16940. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  16941. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  16942. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  16943. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  16944. 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() );
  16945. 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() );
  16946. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  16947. const rgb = XYZ_TO_REC709.mul( xyz );
  16948. return rgb;
  16949. };
  16950. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  16951. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  16952. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  16953. // Evaluate the cosTheta on the base layer (Snell law)
  16954. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  16955. // Handle TIR:
  16956. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  16957. If( cosTheta2Sq.lessThan( 0 ), () => {
  16958. return vec3( 1.0 );
  16959. } );
  16960. const cosTheta2 = cosTheta2Sq.sqrt();
  16961. // First interface
  16962. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  16963. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  16964. //const R21 = R12;
  16965. const T121 = R12.oneMinus();
  16966. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  16967. const phi21 = float( Math.PI ).sub( phi12 );
  16968. // Second interface
  16969. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  16970. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  16971. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  16972. const phi23 = vec3(
  16973. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16974. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16975. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  16976. );
  16977. // Phase shift
  16978. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  16979. const phi = vec3( phi21 ).add( phi23 );
  16980. // Compound terms
  16981. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  16982. const r123 = R123.sqrt();
  16983. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  16984. // Reflectance term for m = 0 (DC term amplitude)
  16985. const C0 = R12.add( Rs );
  16986. const I = C0.toVar();
  16987. // Reflectance term for m > 0 (pairs of diracs)
  16988. const Cm = Rs.sub( T121 ).toVar();
  16989. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  16990. Cm.mulAssign( r123 );
  16991. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  16992. I.addAssign( Cm.mul( Sm ) );
  16993. } );
  16994. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  16995. return I.max( vec3( 0.0 ) );
  16996. } ).setLayout( {
  16997. name: 'evalIridescence',
  16998. type: 'vec3',
  16999. inputs: [
  17000. { name: 'outsideIOR', type: 'float' },
  17001. { name: 'eta2', type: 'float' },
  17002. { name: 'cosTheta1', type: 'float' },
  17003. { name: 'thinFilmThickness', type: 'float' },
  17004. { name: 'baseF0', type: 'vec3' }
  17005. ]
  17006. } );
  17007. //
  17008. // Sheen
  17009. //
  17010. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  17011. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  17012. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  17013. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  17014. const dotNV = normal.dot( viewDir ).saturate();
  17015. const r2 = roughness.pow2();
  17016. const a = select(
  17017. roughness.lessThan( 0.25 ),
  17018. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  17019. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  17020. );
  17021. const b = select(
  17022. roughness.lessThan( 0.25 ),
  17023. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  17024. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  17025. );
  17026. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  17027. return DG.mul( 1.0 / Math.PI ).saturate();
  17028. } );
  17029. const clearcoatF0 = vec3( 0.04 );
  17030. const clearcoatF90 = float( 1 );
  17031. /**
  17032. * Represents the lighting model for a PBR material.
  17033. *
  17034. * @augments LightingModel
  17035. */
  17036. class PhysicalLightingModel extends LightingModel {
  17037. /**
  17038. * Constructs a new physical lighting model.
  17039. *
  17040. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  17041. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  17042. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  17043. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  17044. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  17045. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  17046. */
  17047. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  17048. super();
  17049. /**
  17050. * Whether clearcoat is supported or not.
  17051. *
  17052. * @type {boolean}
  17053. * @default false
  17054. */
  17055. this.clearcoat = clearcoat;
  17056. /**
  17057. * Whether sheen is supported or not.
  17058. *
  17059. * @type {boolean}
  17060. * @default false
  17061. */
  17062. this.sheen = sheen;
  17063. /**
  17064. * Whether iridescence is supported or not.
  17065. *
  17066. * @type {boolean}
  17067. * @default false
  17068. */
  17069. this.iridescence = iridescence;
  17070. /**
  17071. * Whether anisotropy is supported or not.
  17072. *
  17073. * @type {boolean}
  17074. * @default false
  17075. */
  17076. this.anisotropy = anisotropy;
  17077. /**
  17078. * Whether transmission is supported or not.
  17079. *
  17080. * @type {boolean}
  17081. * @default false
  17082. */
  17083. this.transmission = transmission;
  17084. /**
  17085. * Whether dispersion is supported or not.
  17086. *
  17087. * @type {boolean}
  17088. * @default false
  17089. */
  17090. this.dispersion = dispersion;
  17091. /**
  17092. * The clear coat radiance.
  17093. *
  17094. * @type {?Node}
  17095. * @default null
  17096. */
  17097. this.clearcoatRadiance = null;
  17098. /**
  17099. * The clear coat specular direct.
  17100. *
  17101. * @type {?Node}
  17102. * @default null
  17103. */
  17104. this.clearcoatSpecularDirect = null;
  17105. /**
  17106. * The clear coat specular indirect.
  17107. *
  17108. * @type {?Node}
  17109. * @default null
  17110. */
  17111. this.clearcoatSpecularIndirect = null;
  17112. /**
  17113. * The sheen specular direct.
  17114. *
  17115. * @type {?Node}
  17116. * @default null
  17117. */
  17118. this.sheenSpecularDirect = null;
  17119. /**
  17120. * The sheen specular indirect.
  17121. *
  17122. * @type {?Node}
  17123. * @default null
  17124. */
  17125. this.sheenSpecularIndirect = null;
  17126. /**
  17127. * The iridescence Fresnel.
  17128. *
  17129. * @type {?Node}
  17130. * @default null
  17131. */
  17132. this.iridescenceFresnel = null;
  17133. /**
  17134. * The iridescence F0.
  17135. *
  17136. * @type {?Node}
  17137. * @default null
  17138. */
  17139. this.iridescenceF0 = null;
  17140. /**
  17141. * The iridescence F0 dielectric.
  17142. *
  17143. * @type {?Node}
  17144. * @default null
  17145. */
  17146. this.iridescenceF0Dielectric = null;
  17147. /**
  17148. * The iridescence F0 metallic.
  17149. *
  17150. * @type {?Node}
  17151. * @default null
  17152. */
  17153. this.iridescenceF0Metallic = null;
  17154. }
  17155. /**
  17156. * Depending on what features are requested, the method prepares certain node variables
  17157. * which are later used for lighting computations.
  17158. *
  17159. * @param {NodeBuilder} builder - The current node builder.
  17160. */
  17161. start( builder ) {
  17162. if ( this.clearcoat === true ) {
  17163. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  17164. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  17165. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  17166. }
  17167. if ( this.sheen === true ) {
  17168. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  17169. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  17170. }
  17171. if ( this.iridescence === true ) {
  17172. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  17173. const iridescenceFresnelDielectric = evalIridescence( {
  17174. outsideIOR: float( 1.0 ),
  17175. eta2: iridescenceIOR,
  17176. cosTheta1: dotNVi,
  17177. thinFilmThickness: iridescenceThickness,
  17178. baseF0: specularColor
  17179. } );
  17180. const iridescenceFresnelMetallic = evalIridescence( {
  17181. outsideIOR: float( 1.0 ),
  17182. eta2: iridescenceIOR,
  17183. cosTheta1: dotNVi,
  17184. thinFilmThickness: iridescenceThickness,
  17185. baseF0: diffuseColor.rgb
  17186. } );
  17187. this.iridescenceFresnel = mix( iridescenceFresnelDielectric, iridescenceFresnelMetallic, metalness );
  17188. this.iridescenceF0Dielectric = Schlick_to_F0( { f: iridescenceFresnelDielectric, f90: 1.0, dotVH: dotNVi } );
  17189. this.iridescenceF0Metallic = Schlick_to_F0( { f: iridescenceFresnelMetallic, f90: 1.0, dotVH: dotNVi } );
  17190. this.iridescenceF0 = mix( this.iridescenceF0Dielectric, this.iridescenceF0Metallic, metalness );
  17191. }
  17192. if ( this.transmission === true ) {
  17193. const position = positionWorld;
  17194. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  17195. const n = normalWorld;
  17196. const context = builder.context;
  17197. context.backdrop = getIBLVolumeRefraction(
  17198. n,
  17199. v,
  17200. roughness,
  17201. diffuseContribution,
  17202. specularColorBlended,
  17203. specularF90, // specularF90
  17204. position, // positionWorld
  17205. modelWorldMatrix, // modelMatrix
  17206. cameraViewMatrix, // viewMatrix
  17207. cameraProjectionMatrix, // projMatrix
  17208. ior,
  17209. thickness,
  17210. attenuationColor,
  17211. attenuationDistance,
  17212. this.dispersion ? dispersion : null
  17213. );
  17214. context.backdropAlpha = transmission;
  17215. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  17216. }
  17217. super.start( builder );
  17218. }
  17219. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  17220. // Approximates multi-scattering in order to preserve energy.
  17221. // http://www.jcgt.org/published/0008/01/03/
  17222. computeMultiscattering( singleScatter, multiScatter, specularF90, f0, iridescenceF0 = null ) {
  17223. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17224. const fab = DFGApprox( { roughness, dotNV } );
  17225. const Fr = iridescenceF0 ? iridescence.mix( f0, iridescenceF0 ) : f0;
  17226. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  17227. const Ess = fab.x.add( fab.y );
  17228. const Ems = Ess.oneMinus();
  17229. const Favg = Fr.add( Fr.oneMinus().mul( 0.047619 ) ); // 1/21
  17230. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  17231. singleScatter.addAssign( FssEss );
  17232. multiScatter.addAssign( Fms.mul( Ems ) );
  17233. }
  17234. /**
  17235. * Implements the direct light.
  17236. *
  17237. * @param {Object} lightData - The light data.
  17238. * @param {NodeBuilder} builder - The current node builder.
  17239. */
  17240. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  17241. const dotNL = normalView.dot( lightDirection ).clamp();
  17242. const irradiance = dotNL.mul( lightColor );
  17243. if ( this.sheen === true ) {
  17244. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  17245. }
  17246. if ( this.clearcoat === true ) {
  17247. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  17248. const ccIrradiance = dotNLcc.mul( lightColor );
  17249. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  17250. }
  17251. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ) );
  17252. 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 } ) ) );
  17253. }
  17254. /**
  17255. * This method is intended for implementing the direct light term for
  17256. * rect area light nodes.
  17257. *
  17258. * @param {Object} input - The input data.
  17259. * @param {NodeBuilder} builder - The current node builder.
  17260. */
  17261. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  17262. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  17263. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  17264. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  17265. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  17266. const N = normalView;
  17267. const V = positionViewDirection;
  17268. const P = positionView.toVar();
  17269. const uv = LTC_Uv( { N, V, roughness } );
  17270. const t1 = ltc_1.sample( uv ).toVar();
  17271. const t2 = ltc_2.sample( uv ).toVar();
  17272. const mInv = mat3(
  17273. vec3( t1.x, 0, t1.y ),
  17274. vec3( 0, 1, 0 ),
  17275. vec3( t1.z, 0, t1.w )
  17276. ).toVar();
  17277. // LTC Fresnel Approximation by Stephen Hill
  17278. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  17279. const fresnel = specularColorBlended.mul( t2.x ).add( specularColorBlended.oneMinus().mul( t2.y ) ).toVar();
  17280. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  17281. 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 } ) ) );
  17282. }
  17283. /**
  17284. * Implements the indirect lighting.
  17285. *
  17286. * @param {NodeBuilder} builder - The current node builder.
  17287. */
  17288. indirect( builder ) {
  17289. this.indirectDiffuse( builder );
  17290. this.indirectSpecular( builder );
  17291. this.ambientOcclusion( builder );
  17292. }
  17293. /**
  17294. * Implements the indirect diffuse term.
  17295. *
  17296. * @param {NodeBuilder} builder - The current node builder.
  17297. */
  17298. indirectDiffuse( builder ) {
  17299. const { irradiance, reflectedLight } = builder.context;
  17300. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ) );
  17301. }
  17302. /**
  17303. * Implements the indirect specular term.
  17304. *
  17305. * @param {NodeBuilder} builder - The current node builder.
  17306. */
  17307. indirectSpecular( builder ) {
  17308. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  17309. if ( this.sheen === true ) {
  17310. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  17311. sheen,
  17312. IBLSheenBRDF( {
  17313. normal: normalView,
  17314. viewDir: positionViewDirection,
  17315. roughness: sheenRoughness
  17316. } )
  17317. ) );
  17318. }
  17319. if ( this.clearcoat === true ) {
  17320. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17321. const clearcoatEnv = EnvironmentBRDF( {
  17322. dotNV: dotNVcc,
  17323. specularColor: clearcoatF0,
  17324. specularF90: clearcoatF90,
  17325. roughness: clearcoatRoughness
  17326. } );
  17327. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  17328. }
  17329. // Both indirect specular and indirect diffuse light accumulate here
  17330. // Compute multiscattering separately for dielectric and metallic, then mix
  17331. const singleScatteringDielectric = vec3().toVar( 'singleScatteringDielectric' );
  17332. const multiScatteringDielectric = vec3().toVar( 'multiScatteringDielectric' );
  17333. const singleScatteringMetallic = vec3().toVar( 'singleScatteringMetallic' );
  17334. const multiScatteringMetallic = vec3().toVar( 'multiScatteringMetallic' );
  17335. this.computeMultiscattering( singleScatteringDielectric, multiScatteringDielectric, specularF90, specularColor, this.iridescenceF0Dielectric );
  17336. this.computeMultiscattering( singleScatteringMetallic, multiScatteringMetallic, specularF90, diffuseColor.rgb, this.iridescenceF0Metallic );
  17337. // Mix based on metalness
  17338. const singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, metalness );
  17339. const multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, metalness );
  17340. // Diffuse energy conservation uses dielectric path
  17341. const totalScatteringDielectric = singleScatteringDielectric.add( multiScatteringDielectric );
  17342. const diffuse = diffuseContribution.mul( totalScatteringDielectric.oneMinus() );
  17343. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  17344. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  17345. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  17346. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  17347. }
  17348. /**
  17349. * Implements the ambient occlusion term.
  17350. *
  17351. * @param {NodeBuilder} builder - The current node builder.
  17352. */
  17353. ambientOcclusion( builder ) {
  17354. const { ambientOcclusion, reflectedLight } = builder.context;
  17355. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17356. const aoNV = dotNV.add( ambientOcclusion );
  17357. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  17358. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  17359. if ( this.clearcoat === true ) {
  17360. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  17361. }
  17362. if ( this.sheen === true ) {
  17363. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  17364. }
  17365. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  17366. reflectedLight.indirectSpecular.mulAssign( aoNode );
  17367. }
  17368. /**
  17369. * Used for final lighting accumulations depending on the requested features.
  17370. *
  17371. * @param {NodeBuilder} builder - The current node builder.
  17372. */
  17373. finish( { context } ) {
  17374. const { outgoingLight } = context;
  17375. if ( this.clearcoat === true ) {
  17376. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17377. const Fcc = F_Schlick( {
  17378. dotVH: dotNVcc,
  17379. f0: clearcoatF0,
  17380. f90: clearcoatF90
  17381. } );
  17382. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  17383. outgoingLight.assign( clearcoatLight );
  17384. }
  17385. if ( this.sheen === true ) {
  17386. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  17387. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  17388. outgoingLight.assign( sheenLight );
  17389. }
  17390. }
  17391. }
  17392. // These defines must match with PMREMGenerator
  17393. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  17394. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  17395. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  17396. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  17397. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  17398. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  17399. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  17400. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  17401. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  17402. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  17403. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  17404. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  17405. // These shader functions convert between the UV coordinates of a single face of
  17406. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  17407. // sampling a textureCube (not generally normalized ).
  17408. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  17409. const absDirection = vec3( abs( direction ) ).toVar();
  17410. const face = float( -1 ).toVar();
  17411. If( absDirection.x.greaterThan( absDirection.z ), () => {
  17412. If( absDirection.x.greaterThan( absDirection.y ), () => {
  17413. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  17414. } ).Else( () => {
  17415. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17416. } );
  17417. } ).Else( () => {
  17418. If( absDirection.z.greaterThan( absDirection.y ), () => {
  17419. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  17420. } ).Else( () => {
  17421. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17422. } );
  17423. } );
  17424. return face;
  17425. } ).setLayout( {
  17426. name: 'getFace',
  17427. type: 'float',
  17428. inputs: [
  17429. { name: 'direction', type: 'vec3' }
  17430. ]
  17431. } );
  17432. // RH coordinate system; PMREM face-indexing convention
  17433. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  17434. const uv = vec2().toVar();
  17435. If( face.equal( 0.0 ), () => {
  17436. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  17437. } ).ElseIf( face.equal( 1.0 ), () => {
  17438. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  17439. } ).ElseIf( face.equal( 2.0 ), () => {
  17440. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  17441. } ).ElseIf( face.equal( 3.0 ), () => {
  17442. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  17443. } ).ElseIf( face.equal( 4.0 ), () => {
  17444. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  17445. } ).Else( () => {
  17446. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  17447. } );
  17448. return mul( 0.5, uv.add( 1.0 ) );
  17449. } ).setLayout( {
  17450. name: 'getUV',
  17451. type: 'vec2',
  17452. inputs: [
  17453. { name: 'direction', type: 'vec3' },
  17454. { name: 'face', type: 'float' }
  17455. ]
  17456. } );
  17457. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  17458. const mip = float( 0.0 ).toVar();
  17459. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  17460. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  17461. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  17462. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  17463. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  17464. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  17465. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  17466. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  17467. } ).Else( () => {
  17468. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  17469. } );
  17470. return mip;
  17471. } ).setLayout( {
  17472. name: 'roughnessToMip',
  17473. type: 'float',
  17474. inputs: [
  17475. { name: 'roughness', type: 'float' }
  17476. ]
  17477. } );
  17478. // RH coordinate system; PMREM face-indexing convention
  17479. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  17480. const uv = uv_immutable.toVar();
  17481. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  17482. const direction = vec3( uv, 1.0 ).toVar();
  17483. If( face.equal( 0.0 ), () => {
  17484. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  17485. } ).ElseIf( face.equal( 1.0 ), () => {
  17486. direction.assign( direction.xzy );
  17487. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  17488. } ).ElseIf( face.equal( 2.0 ), () => {
  17489. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  17490. } ).ElseIf( face.equal( 3.0 ), () => {
  17491. direction.assign( direction.zyx );
  17492. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  17493. } ).ElseIf( face.equal( 4.0 ), () => {
  17494. direction.assign( direction.xzy );
  17495. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  17496. } ).ElseIf( face.equal( 5.0 ), () => {
  17497. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  17498. } );
  17499. return direction;
  17500. } ).setLayout( {
  17501. name: 'getDirection',
  17502. type: 'vec3',
  17503. inputs: [
  17504. { name: 'uv', type: 'vec2' },
  17505. { name: 'face', type: 'float' }
  17506. ]
  17507. } );
  17508. //
  17509. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17510. const roughness = float( roughness_immutable );
  17511. const sampleDir = vec3( sampleDir_immutable );
  17512. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  17513. const mipF = fract( mip );
  17514. const mipInt = floor( mip );
  17515. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17516. If( mipF.notEqual( 0.0 ), () => {
  17517. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17518. color0.assign( mix( color0, color1, mipF ) );
  17519. } );
  17520. return color0;
  17521. } );
  17522. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17523. const mipInt = float( mipInt_immutable ).toVar();
  17524. const direction = vec3( direction_immutable );
  17525. const face = float( getFace( direction ) ).toVar();
  17526. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  17527. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  17528. const faceSize = float( exp2( mipInt ) ).toVar();
  17529. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  17530. If( face.greaterThan( 2.0 ), () => {
  17531. uv.y.addAssign( faceSize );
  17532. face.subAssign( 3.0 );
  17533. } );
  17534. uv.x.addAssign( face.mul( faceSize ) );
  17535. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  17536. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  17537. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  17538. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  17539. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  17540. } );
  17541. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17542. const cosTheta = cos( theta );
  17543. // Rodrigues' axis-angle rotation
  17544. const sampleDirection = outputDirection.mul( cosTheta )
  17545. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  17546. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  17547. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  17548. } );
  17549. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17550. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  17551. If( axis.equal( vec3( 0.0 ) ), () => {
  17552. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  17553. } );
  17554. axis.assign( normalize( axis ) );
  17555. const gl_FragColor = vec3().toVar();
  17556. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17557. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  17558. If( i.greaterThanEqual( samples ), () => {
  17559. Break();
  17560. } );
  17561. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  17562. 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 } ) ) );
  17563. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17564. } );
  17565. return vec4( gl_FragColor, 1 );
  17566. } );
  17567. // GGX VNDF importance sampling functions
  17568. // Van der Corput radical inverse for generating quasi-random sequences
  17569. const radicalInverse_VdC = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  17570. const bits = uint( bits_immutable ).toVar();
  17571. bits.assign( bits.shiftLeft( uint( 16 ) ).bitOr( bits.shiftRight( uint( 16 ) ) ) );
  17572. bits.assign( bits.bitAnd( uint( 0x55555555 ) ).shiftLeft( uint( 1 ) ).bitOr( bits.bitAnd( uint( 0xAAAAAAAA ) ).shiftRight( uint( 1 ) ) ) );
  17573. bits.assign( bits.bitAnd( uint( 0x33333333 ) ).shiftLeft( uint( 2 ) ).bitOr( bits.bitAnd( uint( 0xCCCCCCCC ) ).shiftRight( uint( 2 ) ) ) );
  17574. bits.assign( bits.bitAnd( uint( 0x0F0F0F0F ) ).shiftLeft( uint( 4 ) ).bitOr( bits.bitAnd( uint( 0xF0F0F0F0 ) ).shiftRight( uint( 4 ) ) ) );
  17575. bits.assign( bits.bitAnd( uint( 0x00FF00FF ) ).shiftLeft( uint( 8 ) ).bitOr( bits.bitAnd( uint( 0xFF00FF00 ) ).shiftRight( uint( 8 ) ) ) );
  17576. return float( bits ).mul( 2.3283064365386963e-10 ); // / 0x100000000
  17577. } );
  17578. // Hammersley sequence for quasi-Monte Carlo sampling
  17579. const hammersley = /*@__PURE__*/ Fn( ( [ i, N ] ) => {
  17580. return vec2( float( i ).div( float( N ) ), radicalInverse_VdC( i ) );
  17581. } );
  17582. // GGX VNDF importance sampling (Eric Heitz 2018)
  17583. // "Sampling the GGX Distribution of Visible Normals"
  17584. // https://jcgt.org/published/0007/04/01/
  17585. const importanceSampleGGX_VNDF = /*@__PURE__*/ Fn( ( [ Xi, V_immutable, roughness_immutable ] ) => {
  17586. const V = vec3( V_immutable ).toVar();
  17587. const roughness = float( roughness_immutable );
  17588. const alpha = roughness.mul( roughness ).toVar();
  17589. // Section 3.2: Transform view direction to hemisphere configuration
  17590. const Vh = normalize( vec3( alpha.mul( V.x ), alpha.mul( V.y ), V.z ) ).toVar();
  17591. // Section 4.1: Orthonormal basis
  17592. const lensq = Vh.x.mul( Vh.x ).add( Vh.y.mul( Vh.y ) );
  17593. 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();
  17594. const T2 = cross( Vh, T1 ).toVar();
  17595. // Section 4.2: Parameterization of projected area
  17596. const r = sqrt( Xi.x );
  17597. const phi = mul( 2.0, 3.14159265359 ).mul( Xi.y );
  17598. const t1 = r.mul( cos( phi ) ).toVar();
  17599. const t2 = r.mul( sin( phi ) ).toVar();
  17600. const s = mul( 0.5, Vh.z.add( 1.0 ) );
  17601. t2.assign( s.oneMinus().mul( sqrt( t1.mul( t1 ).oneMinus() ) ).add( s.mul( t2 ) ) );
  17602. // Section 4.3: Reprojection onto hemisphere
  17603. 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() ) ) ) );
  17604. // Section 3.4: Transform back to ellipsoid configuration
  17605. return normalize( vec3( alpha.mul( Nh.x ), alpha.mul( Nh.y ), max$1( 0.0, Nh.z ) ) );
  17606. } );
  17607. // GGX convolution using VNDF importance sampling
  17608. const ggxConvolution = /*@__PURE__*/ Fn( ( { roughness, mipInt, envMap, N_immutable, GGX_SAMPLES, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17609. const N = vec3( N_immutable ).toVar();
  17610. const prefilteredColor = vec3( 0.0 ).toVar();
  17611. const totalWeight = float( 0.0 ).toVar();
  17612. // For very low roughness, just sample the environment directly
  17613. If( roughness.lessThan( 0.001 ), () => {
  17614. prefilteredColor.assign( bilinearCubeUV( envMap, N, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) );
  17615. } ).Else( () => {
  17616. // Tangent space basis for VNDF sampling
  17617. const up = select( abs( N.z ).lessThan( 0.999 ), vec3( 0.0, 0.0, 1.0 ), vec3( 1.0, 0.0, 0.0 ) );
  17618. const tangent = normalize( cross( up, N ) ).toVar();
  17619. const bitangent = cross( N, tangent ).toVar();
  17620. Loop( { start: uint( 0 ), end: GGX_SAMPLES }, ( { i } ) => {
  17621. const Xi = hammersley( i, GGX_SAMPLES );
  17622. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  17623. const H_tangent = importanceSampleGGX_VNDF( Xi, vec3( 0.0, 0.0, 1.0 ), roughness );
  17624. // Transform H back to world space
  17625. const H = normalize( tangent.mul( H_tangent.x ).add( bitangent.mul( H_tangent.y ) ).add( N.mul( H_tangent.z ) ) );
  17626. const L = normalize( H.mul( dot( N, H ).mul( 2.0 ) ).sub( N ) );
  17627. const NdotL = max$1( dot( N, L ), 0.0 );
  17628. If( NdotL.greaterThan( 0.0 ), () => {
  17629. // Sample environment at fixed mip level
  17630. // VNDF importance sampling handles the distribution filtering
  17631. const sampleColor = bilinearCubeUV( envMap, L, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  17632. // Weight by NdotL for the split-sum approximation
  17633. // VNDF PDF naturally accounts for the visible microfacet distribution
  17634. prefilteredColor.addAssign( sampleColor.mul( NdotL ) );
  17635. totalWeight.addAssign( NdotL );
  17636. } );
  17637. } );
  17638. If( totalWeight.greaterThan( 0.0 ), () => {
  17639. prefilteredColor.assign( prefilteredColor.div( totalWeight ) );
  17640. } );
  17641. } );
  17642. return vec4( prefilteredColor, 1.0 );
  17643. } );
  17644. const LOD_MIN = 4;
  17645. // The standard deviations (radians) associated with the extra mips.
  17646. // Used for scene blur in fromScene() method.
  17647. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  17648. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  17649. // samples and exit early, but not recompile the shader.
  17650. // Used for scene blur in fromScene() method.
  17651. const MAX_SAMPLES = 20;
  17652. // GGX VNDF importance sampling configuration
  17653. const GGX_SAMPLES = 512;
  17654. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  17655. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  17656. const _clearColor$2 = /*@__PURE__*/ new Color();
  17657. let _oldTarget = null;
  17658. let _oldActiveCubeFace = 0;
  17659. let _oldActiveMipmapLevel = 0;
  17660. const _origin = /*@__PURE__*/ new Vector3();
  17661. // maps blur materials to their uniforms dictionary
  17662. const _uniformsMap = new WeakMap();
  17663. // WebGPU Face indices
  17664. const _faceLib = [
  17665. 3, 1, 5,
  17666. 0, 4, 2
  17667. ];
  17668. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  17669. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  17670. /**
  17671. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  17672. * (PMREM) from a cubeMap environment texture. This allows different levels of
  17673. * blur to be quickly accessed based on material roughness. It is packed into a
  17674. * special CubeUV format that allows us to perform custom interpolation so that
  17675. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  17676. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  17677. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  17678. * higher roughness levels. In this way we maintain resolution to smoothly
  17679. * interpolate diffuse lighting while limiting sampling computation.
  17680. *
  17681. * The prefiltering uses GGX VNDF (Visible Normal Distribution Function)
  17682. * importance sampling based on "Sampling the GGX Distribution of Visible Normals"
  17683. * (Heitz, 2018) to generate environment maps that accurately match the GGX BRDF
  17684. * used in material rendering for physically-based image-based lighting.
  17685. */
  17686. class PMREMGenerator {
  17687. /**
  17688. * Constructs a new PMREM generator.
  17689. *
  17690. * @param {Renderer} renderer - The renderer.
  17691. */
  17692. constructor( renderer ) {
  17693. this._renderer = renderer;
  17694. this._pingPongRenderTarget = null;
  17695. this._lodMax = 0;
  17696. this._cubeSize = 0;
  17697. this._sizeLods = [];
  17698. this._sigmas = [];
  17699. this._lodMeshes = [];
  17700. this._blurMaterial = null;
  17701. this._ggxMaterial = null;
  17702. this._cubemapMaterial = null;
  17703. this._equirectMaterial = null;
  17704. this._backgroundBox = null;
  17705. }
  17706. get _hasInitialized() {
  17707. return this._renderer.hasInitialized();
  17708. }
  17709. /**
  17710. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17711. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17712. * in radians to be applied to the scene before PMREM generation. Optional near
  17713. * and far planes ensure the scene is rendered in its entirety.
  17714. *
  17715. * @param {Scene} scene - The scene to be captured.
  17716. * @param {number} [sigma=0] - The blur radius in radians.
  17717. * @param {number} [near=0.1] - The near plane distance.
  17718. * @param {number} [far=100] - The far plane distance.
  17719. * @param {Object} [options={}] - The configuration options.
  17720. * @param {number} [options.size=256] - The texture size of the PMREM.
  17721. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  17722. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17723. * @return {RenderTarget} The resulting PMREM.
  17724. * @see {@link PMREMGenerator#fromScene}
  17725. */
  17726. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17727. const {
  17728. size = 256,
  17729. position = _origin,
  17730. renderTarget = null,
  17731. } = options;
  17732. this._setSize( size );
  17733. if ( this._hasInitialized === false ) {
  17734. warn( 'PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.' );
  17735. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17736. options.renderTarget = cubeUVRenderTarget;
  17737. this.fromSceneAsync( scene, sigma, near, far, options );
  17738. return cubeUVRenderTarget;
  17739. }
  17740. _oldTarget = this._renderer.getRenderTarget();
  17741. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17742. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17743. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17744. cubeUVRenderTarget.depthBuffer = true;
  17745. this._init( cubeUVRenderTarget );
  17746. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  17747. if ( sigma > 0 ) {
  17748. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  17749. }
  17750. this._applyPMREM( cubeUVRenderTarget );
  17751. this._cleanup( cubeUVRenderTarget );
  17752. return cubeUVRenderTarget;
  17753. }
  17754. /**
  17755. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17756. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17757. * in radians to be applied to the scene before PMREM generation. Optional near
  17758. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  17759. * is placed at the origin).
  17760. *
  17761. * @deprecated
  17762. * @param {Scene} scene - The scene to be captured.
  17763. * @param {number} [sigma=0] - The blur radius in radians.
  17764. * @param {number} [near=0.1] - The near plane distance.
  17765. * @param {number} [far=100] - The far plane distance.
  17766. * @param {Object} [options={}] - The configuration options.
  17767. * @param {number} [options.size=256] - The texture size of the PMREM.
  17768. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  17769. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17770. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  17771. * @see {@link PMREMGenerator#fromScene}
  17772. */
  17773. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17774. warnOnce( 'PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17775. await this._renderer.init();
  17776. return this.fromScene( scene, sigma, near, far, options );
  17777. }
  17778. /**
  17779. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17780. * or HDR. The ideal input image size is 1k (1024 x 512),
  17781. * as this matches best with the 256 x 256 cubemap output.
  17782. *
  17783. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17784. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17785. * @return {RenderTarget} The resulting PMREM.
  17786. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  17787. */
  17788. fromEquirectangular( equirectangular, renderTarget = null ) {
  17789. if ( this._hasInitialized === false ) {
  17790. warn( 'PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.' );
  17791. this._setSizeFromTexture( equirectangular );
  17792. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17793. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  17794. return cubeUVRenderTarget;
  17795. }
  17796. return this._fromTexture( equirectangular, renderTarget );
  17797. }
  17798. /**
  17799. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17800. * or HDR. The ideal input image size is 1k (1024 x 512),
  17801. * as this matches best with the 256 x 256 cubemap output.
  17802. *
  17803. * @deprecated
  17804. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17805. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17806. * @return {Promise<RenderTarget>} The resulting PMREM.
  17807. * @see {@link PMREMGenerator#fromEquirectangular}
  17808. */
  17809. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  17810. warnOnce( 'PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17811. await this._renderer.init();
  17812. return this._fromTexture( equirectangular, renderTarget );
  17813. }
  17814. /**
  17815. * Generates a PMREM from an cubemap texture, which can be either LDR
  17816. * or HDR. The ideal input cube size is 256 x 256,
  17817. * as this matches best with the 256 x 256 cubemap output.
  17818. *
  17819. * @param {Texture} cubemap - The cubemap texture to be converted.
  17820. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17821. * @return {RenderTarget} The resulting PMREM.
  17822. * @see {@link PMREMGenerator#fromCubemapAsync}
  17823. */
  17824. fromCubemap( cubemap, renderTarget = null ) {
  17825. if ( this._hasInitialized === false ) {
  17826. warn( 'PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  17827. this._setSizeFromTexture( cubemap );
  17828. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17829. this.fromCubemapAsync( cubemap, renderTarget );
  17830. return cubeUVRenderTarget;
  17831. }
  17832. return this._fromTexture( cubemap, renderTarget );
  17833. }
  17834. /**
  17835. * Generates a PMREM from an cubemap texture, which can be either LDR
  17836. * or HDR. The ideal input cube size is 256 x 256,
  17837. * with the 256 x 256 cubemap output.
  17838. *
  17839. * @deprecated
  17840. * @param {Texture} cubemap - The cubemap texture to be converted.
  17841. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17842. * @return {Promise<RenderTarget>} The resulting PMREM.
  17843. * @see {@link PMREMGenerator#fromCubemap}
  17844. */
  17845. async fromCubemapAsync( cubemap, renderTarget = null ) {
  17846. warnOnce( 'PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17847. await this._renderer.init();
  17848. return this._fromTexture( cubemap, renderTarget );
  17849. }
  17850. /**
  17851. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  17852. * your texture's network fetch for increased concurrency.
  17853. *
  17854. * @returns {Promise}
  17855. */
  17856. async compileCubemapShader() {
  17857. if ( this._cubemapMaterial === null ) {
  17858. this._cubemapMaterial = _getCubemapMaterial();
  17859. await this._compileMaterial( this._cubemapMaterial );
  17860. }
  17861. }
  17862. /**
  17863. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  17864. * your texture's network fetch for increased concurrency.
  17865. *
  17866. * @returns {Promise}
  17867. */
  17868. async compileEquirectangularShader() {
  17869. if ( this._equirectMaterial === null ) {
  17870. this._equirectMaterial = _getEquirectMaterial();
  17871. await this._compileMaterial( this._equirectMaterial );
  17872. }
  17873. }
  17874. /**
  17875. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  17876. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  17877. * one of them will cause any others to also become unusable.
  17878. */
  17879. dispose() {
  17880. this._dispose();
  17881. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  17882. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  17883. if ( this._backgroundBox !== null ) {
  17884. this._backgroundBox.geometry.dispose();
  17885. this._backgroundBox.material.dispose();
  17886. }
  17887. }
  17888. // private interface
  17889. _setSizeFromTexture( texture ) {
  17890. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  17891. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  17892. } else { // Equirectangular
  17893. this._setSize( texture.image.width / 4 );
  17894. }
  17895. }
  17896. _setSize( cubeSize ) {
  17897. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  17898. this._cubeSize = Math.pow( 2, this._lodMax );
  17899. }
  17900. _dispose() {
  17901. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  17902. if ( this._ggxMaterial !== null ) this._ggxMaterial.dispose();
  17903. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  17904. for ( let i = 0; i < this._lodMeshes.length; i ++ ) {
  17905. this._lodMeshes[ i ].geometry.dispose();
  17906. }
  17907. }
  17908. _cleanup( outputTarget ) {
  17909. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  17910. outputTarget.scissorTest = false;
  17911. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  17912. }
  17913. _fromTexture( texture, renderTarget ) {
  17914. this._setSizeFromTexture( texture );
  17915. _oldTarget = this._renderer.getRenderTarget();
  17916. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17917. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17918. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17919. this._init( cubeUVRenderTarget );
  17920. this._textureToCubeUV( texture, cubeUVRenderTarget );
  17921. this._applyPMREM( cubeUVRenderTarget );
  17922. this._cleanup( cubeUVRenderTarget );
  17923. return cubeUVRenderTarget;
  17924. }
  17925. _allocateTarget() {
  17926. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  17927. const height = 4 * this._cubeSize;
  17928. const cubeUVRenderTarget = _createRenderTarget( width, height );
  17929. return cubeUVRenderTarget;
  17930. }
  17931. _init( renderTarget ) {
  17932. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  17933. if ( this._pingPongRenderTarget !== null ) {
  17934. this._dispose();
  17935. }
  17936. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  17937. const { _lodMax } = this;
  17938. ( { lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  17939. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  17940. this._ggxMaterial = _getGGXShader( _lodMax, renderTarget.width, renderTarget.height );
  17941. }
  17942. }
  17943. async _compileMaterial( material ) {
  17944. const mesh = new Mesh( new BufferGeometry(), material );
  17945. await this._renderer.compile( mesh, _flatCamera );
  17946. }
  17947. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  17948. const cubeCamera = _cubeCamera;
  17949. cubeCamera.near = near;
  17950. cubeCamera.far = far;
  17951. // px, py, pz, nx, ny, nz
  17952. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  17953. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  17954. const renderer = this._renderer;
  17955. const originalAutoClear = renderer.autoClear;
  17956. renderer.getClearColor( _clearColor$2 );
  17957. renderer.autoClear = false;
  17958. if ( this._backgroundBox === null ) {
  17959. this._backgroundBox = new Mesh(
  17960. new BoxGeometry(),
  17961. new MeshBasicMaterial( {
  17962. name: 'PMREM.Background',
  17963. side: BackSide,
  17964. depthWrite: false,
  17965. depthTest: false,
  17966. } )
  17967. );
  17968. }
  17969. const backgroundBox = this._backgroundBox;
  17970. const backgroundMaterial = backgroundBox.material;
  17971. let useSolidColor = false;
  17972. const background = scene.background;
  17973. if ( background ) {
  17974. if ( background.isColor ) {
  17975. backgroundMaterial.color.copy( background );
  17976. scene.background = null;
  17977. useSolidColor = true;
  17978. }
  17979. } else {
  17980. backgroundMaterial.color.copy( _clearColor$2 );
  17981. useSolidColor = true;
  17982. }
  17983. renderer.setRenderTarget( cubeUVRenderTarget );
  17984. renderer.clear();
  17985. if ( useSolidColor ) {
  17986. renderer.render( backgroundBox, cubeCamera );
  17987. }
  17988. for ( let i = 0; i < 6; i ++ ) {
  17989. const col = i % 3;
  17990. if ( col === 0 ) {
  17991. cubeCamera.up.set( 0, upSign[ i ], 0 );
  17992. cubeCamera.position.set( position.x, position.y, position.z );
  17993. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  17994. } else if ( col === 1 ) {
  17995. cubeCamera.up.set( 0, 0, upSign[ i ] );
  17996. cubeCamera.position.set( position.x, position.y, position.z );
  17997. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  17998. } else {
  17999. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18000. cubeCamera.position.set( position.x, position.y, position.z );
  18001. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  18002. }
  18003. const size = this._cubeSize;
  18004. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  18005. renderer.render( scene, cubeCamera );
  18006. }
  18007. renderer.autoClear = originalAutoClear;
  18008. scene.background = background;
  18009. }
  18010. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  18011. const renderer = this._renderer;
  18012. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  18013. if ( isCubeTexture ) {
  18014. if ( this._cubemapMaterial === null ) {
  18015. this._cubemapMaterial = _getCubemapMaterial( texture );
  18016. }
  18017. } else {
  18018. if ( this._equirectMaterial === null ) {
  18019. this._equirectMaterial = _getEquirectMaterial( texture );
  18020. }
  18021. }
  18022. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  18023. material.fragmentNode.value = texture;
  18024. const mesh = this._lodMeshes[ 0 ];
  18025. mesh.material = material;
  18026. const size = this._cubeSize;
  18027. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  18028. renderer.setRenderTarget( cubeUVRenderTarget );
  18029. renderer.render( mesh, _flatCamera );
  18030. }
  18031. _applyPMREM( cubeUVRenderTarget ) {
  18032. const renderer = this._renderer;
  18033. const autoClear = renderer.autoClear;
  18034. renderer.autoClear = false;
  18035. const n = this._lodMeshes.length;
  18036. // Use GGX VNDF importance sampling
  18037. for ( let i = 1; i < n; i ++ ) {
  18038. this._applyGGXFilter( cubeUVRenderTarget, i - 1, i );
  18039. }
  18040. renderer.autoClear = autoClear;
  18041. }
  18042. /**
  18043. * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map.
  18044. * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the
  18045. * GGX BRDF for physically-based rendering. Reads from the previous LOD level and
  18046. * applies incremental roughness filtering to avoid over-blurring.
  18047. *
  18048. * @private
  18049. * @param {RenderTarget} cubeUVRenderTarget
  18050. * @param {number} lodIn - Source LOD level to read from
  18051. * @param {number} lodOut - Target LOD level to write to
  18052. */
  18053. _applyGGXFilter( cubeUVRenderTarget, lodIn, lodOut ) {
  18054. const renderer = this._renderer;
  18055. const pingPongRenderTarget = this._pingPongRenderTarget;
  18056. const ggxMaterial = this._ggxMaterial;
  18057. const ggxMesh = this._lodMeshes[ lodOut ];
  18058. ggxMesh.material = ggxMaterial;
  18059. const ggxUniforms = _uniformsMap.get( ggxMaterial );
  18060. // Calculate incremental roughness between LOD levels
  18061. const targetRoughness = lodOut / ( this._lodMeshes.length - 1 );
  18062. const sourceRoughness = lodIn / ( this._lodMeshes.length - 1 );
  18063. const incrementalRoughness = Math.sqrt( targetRoughness * targetRoughness - sourceRoughness * sourceRoughness );
  18064. // Apply blur strength mapping for better quality across the roughness range
  18065. const blurStrength = 0.0 + targetRoughness * 1.25;
  18066. const adjustedRoughness = incrementalRoughness * blurStrength;
  18067. // Calculate viewport position based on output LOD level
  18068. const { _lodMax } = this;
  18069. const outputSize = this._sizeLods[ lodOut ];
  18070. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18071. const y = 4 * ( this._cubeSize - outputSize );
  18072. // Read from previous LOD with incremental roughness
  18073. cubeUVRenderTarget.texture.frame = ( cubeUVRenderTarget.texture.frame || 0 ) + 1;
  18074. ggxUniforms.envMap.value = cubeUVRenderTarget.texture;
  18075. ggxUniforms.roughness.value = adjustedRoughness;
  18076. ggxUniforms.mipInt.value = _lodMax - lodIn; // Sample from input LOD
  18077. _setViewport( pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18078. renderer.setRenderTarget( pingPongRenderTarget );
  18079. renderer.render( ggxMesh, _flatCamera );
  18080. // Copy from pingPong back to cubeUV (simple direct copy)
  18081. pingPongRenderTarget.texture.frame = ( pingPongRenderTarget.texture.frame || 0 ) + 1;
  18082. ggxUniforms.envMap.value = pingPongRenderTarget.texture;
  18083. ggxUniforms.roughness.value = 0.0; // Direct copy
  18084. ggxUniforms.mipInt.value = _lodMax - lodOut; // Read from the level we just wrote
  18085. _setViewport( cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18086. renderer.setRenderTarget( cubeUVRenderTarget );
  18087. renderer.render( ggxMesh, _flatCamera );
  18088. }
  18089. /**
  18090. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  18091. * vertically and horizontally, but this breaks down on a cube. Here we apply
  18092. * the blur latitudinally (around the poles), and then longitudinally (towards
  18093. * the poles) to approximate the orthogonally-separable blur. It is least
  18094. * accurate at the poles, but still does a decent job.
  18095. *
  18096. * Used for initial scene blur in fromScene() method when sigma > 0.
  18097. *
  18098. * @private
  18099. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  18100. * @param {number} lodIn - The input level-of-detail.
  18101. * @param {number} lodOut - The output level-of-detail.
  18102. * @param {number} sigma - The blur radius in radians.
  18103. * @param {Vector3} [poleAxis] - The pole axis.
  18104. */
  18105. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  18106. const pingPongRenderTarget = this._pingPongRenderTarget;
  18107. this._halfBlur(
  18108. cubeUVRenderTarget,
  18109. pingPongRenderTarget,
  18110. lodIn,
  18111. lodOut,
  18112. sigma,
  18113. 'latitudinal',
  18114. poleAxis );
  18115. this._halfBlur(
  18116. pingPongRenderTarget,
  18117. cubeUVRenderTarget,
  18118. lodOut,
  18119. lodOut,
  18120. sigma,
  18121. 'longitudinal',
  18122. poleAxis );
  18123. }
  18124. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  18125. const renderer = this._renderer;
  18126. const blurMaterial = this._blurMaterial;
  18127. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  18128. error( 'blur direction must be either latitudinal or longitudinal!' );
  18129. }
  18130. // Number of standard deviations at which to cut off the discrete approximation.
  18131. const STANDARD_DEVIATIONS = 3;
  18132. const blurMesh = this._lodMeshes[ lodOut ];
  18133. blurMesh.material = blurMaterial;
  18134. const blurUniforms = _uniformsMap.get( blurMaterial );
  18135. const pixels = this._sizeLods[ lodIn ] - 1;
  18136. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  18137. const sigmaPixels = sigmaRadians / radiansPerPixel;
  18138. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  18139. if ( samples > MAX_SAMPLES ) {
  18140. warn( `sigmaRadians, ${
  18141. sigmaRadians}, is too large and will clip, as it requested ${
  18142. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  18143. }
  18144. const weights = [];
  18145. let sum = 0;
  18146. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  18147. const x = i / sigmaPixels;
  18148. const weight = Math.exp( - x * x / 2 );
  18149. weights.push( weight );
  18150. if ( i === 0 ) {
  18151. sum += weight;
  18152. } else if ( i < samples ) {
  18153. sum += 2 * weight;
  18154. }
  18155. }
  18156. for ( let i = 0; i < weights.length; i ++ ) {
  18157. weights[ i ] = weights[ i ] / sum;
  18158. }
  18159. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  18160. blurUniforms.envMap.value = targetIn.texture;
  18161. blurUniforms.samples.value = samples;
  18162. blurUniforms.weights.array = weights;
  18163. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  18164. if ( poleAxis ) {
  18165. blurUniforms.poleAxis.value = poleAxis;
  18166. }
  18167. const { _lodMax } = this;
  18168. blurUniforms.dTheta.value = radiansPerPixel;
  18169. blurUniforms.mipInt.value = _lodMax - lodIn;
  18170. const outputSize = this._sizeLods[ lodOut ];
  18171. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18172. const y = 4 * ( this._cubeSize - outputSize );
  18173. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  18174. renderer.setRenderTarget( targetOut );
  18175. renderer.render( blurMesh, _flatCamera );
  18176. }
  18177. }
  18178. function _createPlanes( lodMax ) {
  18179. const sizeLods = [];
  18180. const sigmas = [];
  18181. const lodMeshes = [];
  18182. let lod = lodMax;
  18183. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  18184. for ( let i = 0; i < totalLods; i ++ ) {
  18185. const sizeLod = Math.pow( 2, lod );
  18186. sizeLods.push( sizeLod );
  18187. let sigma = 1.0 / sizeLod;
  18188. if ( i > lodMax - LOD_MIN ) {
  18189. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  18190. } else if ( i === 0 ) {
  18191. sigma = 0;
  18192. }
  18193. sigmas.push( sigma );
  18194. const texelSize = 1.0 / ( sizeLod - 2 );
  18195. const min = - texelSize;
  18196. const max = 1 + texelSize;
  18197. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  18198. const cubeFaces = 6;
  18199. const vertices = 6;
  18200. const positionSize = 3;
  18201. const uvSize = 2;
  18202. const faceIndexSize = 1;
  18203. const position = new Float32Array( positionSize * vertices * cubeFaces );
  18204. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  18205. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  18206. for ( let face = 0; face < cubeFaces; face ++ ) {
  18207. const x = ( face % 3 ) * 2 / 3 - 1;
  18208. const y = face > 2 ? 0 : -1;
  18209. const coordinates = [
  18210. x, y, 0,
  18211. x + 2 / 3, y, 0,
  18212. x + 2 / 3, y + 1, 0,
  18213. x, y, 0,
  18214. x + 2 / 3, y + 1, 0,
  18215. x, y + 1, 0
  18216. ];
  18217. const faceIdx = _faceLib[ face ];
  18218. position.set( coordinates, positionSize * vertices * faceIdx );
  18219. uv.set( uv1, uvSize * vertices * faceIdx );
  18220. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  18221. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  18222. }
  18223. const planes = new BufferGeometry();
  18224. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  18225. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  18226. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  18227. lodMeshes.push( new Mesh( planes, null ) );
  18228. if ( lod > LOD_MIN ) {
  18229. lod --;
  18230. }
  18231. }
  18232. return { lodMeshes, sizeLods, sigmas };
  18233. }
  18234. function _createRenderTarget( width, height ) {
  18235. const params = {
  18236. magFilter: LinearFilter,
  18237. minFilter: LinearFilter,
  18238. generateMipmaps: false,
  18239. type: HalfFloatType,
  18240. format: RGBAFormat,
  18241. colorSpace: LinearSRGBColorSpace,
  18242. //depthBuffer: false
  18243. };
  18244. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  18245. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  18246. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  18247. cubeUVRenderTarget.texture.isPMREMTexture = true;
  18248. cubeUVRenderTarget.scissorTest = true;
  18249. return cubeUVRenderTarget;
  18250. }
  18251. function _setViewport( target, x, y, width, height ) {
  18252. target.viewport.set( x, y, width, height );
  18253. target.scissor.set( x, y, width, height );
  18254. }
  18255. function _getMaterial( type ) {
  18256. const material = new NodeMaterial();
  18257. material.depthTest = false;
  18258. material.depthWrite = false;
  18259. material.blending = NoBlending;
  18260. material.name = `PMREM_${ type }`;
  18261. return material;
  18262. }
  18263. function _getBlurShader( lodMax, width, height ) {
  18264. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  18265. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  18266. const dTheta = uniform( 0 );
  18267. const n = float( MAX_SAMPLES );
  18268. const latitudinal = uniform( 0 ); // false, bool
  18269. const samples = uniform( 1 ); // int
  18270. const envMap = texture();
  18271. const mipInt = uniform( 0 ); // int
  18272. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18273. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18274. const CUBEUV_MAX_MIP = float( lodMax );
  18275. const materialUniforms = {
  18276. n,
  18277. latitudinal,
  18278. weights,
  18279. poleAxis,
  18280. outputDirection: _outputDirection,
  18281. dTheta,
  18282. samples,
  18283. envMap,
  18284. mipInt,
  18285. CUBEUV_TEXEL_WIDTH,
  18286. CUBEUV_TEXEL_HEIGHT,
  18287. CUBEUV_MAX_MIP
  18288. };
  18289. const material = _getMaterial( 'blur' );
  18290. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  18291. _uniformsMap.set( material, materialUniforms );
  18292. return material;
  18293. }
  18294. function _getGGXShader( lodMax, width, height ) {
  18295. const envMap = texture();
  18296. const roughness = uniform( 0 );
  18297. const mipInt = uniform( 0 );
  18298. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18299. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18300. const CUBEUV_MAX_MIP = float( lodMax );
  18301. const materialUniforms = {
  18302. envMap,
  18303. roughness,
  18304. mipInt,
  18305. CUBEUV_TEXEL_WIDTH,
  18306. CUBEUV_TEXEL_HEIGHT,
  18307. CUBEUV_MAX_MIP
  18308. };
  18309. const material = _getMaterial( 'ggx' );
  18310. material.fragmentNode = ggxConvolution( {
  18311. ...materialUniforms,
  18312. N_immutable: _outputDirection,
  18313. GGX_SAMPLES: uint( GGX_SAMPLES )
  18314. } );
  18315. _uniformsMap.set( material, materialUniforms );
  18316. return material;
  18317. }
  18318. function _getCubemapMaterial( envTexture ) {
  18319. const material = _getMaterial( 'cubemap' );
  18320. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  18321. return material;
  18322. }
  18323. function _getEquirectMaterial( envTexture ) {
  18324. const material = _getMaterial( 'equirect' );
  18325. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  18326. return material;
  18327. }
  18328. const _cache = new WeakMap();
  18329. /**
  18330. * Generates the cubeUV size based on the given image height.
  18331. *
  18332. * @private
  18333. * @param {number} imageHeight - The image height.
  18334. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  18335. */
  18336. function _generateCubeUVSize( imageHeight ) {
  18337. const maxMip = Math.log2( imageHeight ) - 2;
  18338. const texelHeight = 1.0 / imageHeight;
  18339. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  18340. return { texelWidth, texelHeight, maxMip };
  18341. }
  18342. /**
  18343. * Generates a PMREM from the given texture.
  18344. *
  18345. * @private
  18346. * @param {Texture} texture - The texture to create the PMREM for.
  18347. * @param {Renderer} renderer - The renderer.
  18348. * @param {PMREMGenerator} generator - The PMREM generator.
  18349. * @return {?Texture} The PMREM.
  18350. */
  18351. function _getPMREMFromTexture( texture, renderer, generator ) {
  18352. const cache = _getCache( renderer );
  18353. let cacheTexture = cache.get( texture );
  18354. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  18355. if ( pmremVersion !== texture.pmremVersion ) {
  18356. const image = texture.image;
  18357. if ( texture.isCubeTexture ) {
  18358. if ( isCubeMapReady( image ) ) {
  18359. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  18360. } else {
  18361. return null;
  18362. }
  18363. } else {
  18364. if ( isEquirectangularMapReady( image ) ) {
  18365. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  18366. } else {
  18367. return null;
  18368. }
  18369. }
  18370. cacheTexture.pmremVersion = texture.pmremVersion;
  18371. cache.set( texture, cacheTexture );
  18372. }
  18373. return cacheTexture.texture;
  18374. }
  18375. /**
  18376. * Returns a cache that stores generated PMREMs for the respective textures.
  18377. * A cache must be maintained per renderer since PMREMs are render target textures
  18378. * which can't be shared across render contexts.
  18379. *
  18380. * @private
  18381. * @param {Renderer} renderer - The renderer.
  18382. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  18383. */
  18384. function _getCache( renderer ) {
  18385. let rendererCache = _cache.get( renderer );
  18386. if ( rendererCache === undefined ) {
  18387. rendererCache = new WeakMap();
  18388. _cache.set( renderer, rendererCache );
  18389. }
  18390. return rendererCache;
  18391. }
  18392. /**
  18393. * This node represents a PMREM which is a special type of preprocessed
  18394. * environment map intended for PBR materials.
  18395. *
  18396. * ```js
  18397. * const material = new MeshStandardNodeMaterial();
  18398. * material.envNode = pmremTexture( envMap );
  18399. * ```
  18400. *
  18401. * @augments TempNode
  18402. */
  18403. class PMREMNode extends TempNode {
  18404. static get type() {
  18405. return 'PMREMNode';
  18406. }
  18407. /**
  18408. * Constructs a new function overloading node.
  18409. *
  18410. * @param {Texture} value - The input texture.
  18411. * @param {Node<vec2>} [uvNode=null] - The uv node.
  18412. * @param {Node<float>} [levelNode=null] - The level node.
  18413. */
  18414. constructor( value, uvNode = null, levelNode = null ) {
  18415. super( 'vec3' );
  18416. /**
  18417. * Reference to the input texture.
  18418. *
  18419. * @private
  18420. * @type {Texture}
  18421. */
  18422. this._value = value;
  18423. /**
  18424. * Reference to the generated PMREM.
  18425. *
  18426. * @private
  18427. * @type {Texture | null}
  18428. * @default null
  18429. */
  18430. this._pmrem = null;
  18431. /**
  18432. * The uv node.
  18433. *
  18434. * @type {Node<vec2>}
  18435. */
  18436. this.uvNode = uvNode;
  18437. /**
  18438. * The level node.
  18439. *
  18440. * @type {Node<float>}
  18441. */
  18442. this.levelNode = levelNode;
  18443. /**
  18444. * Reference to a PMREM generator.
  18445. *
  18446. * @private
  18447. * @type {?PMREMGenerator}
  18448. * @default null
  18449. */
  18450. this._generator = null;
  18451. const defaultTexture = new Texture();
  18452. defaultTexture.isRenderTargetTexture = true;
  18453. /**
  18454. * The texture node holding the generated PMREM.
  18455. *
  18456. * @private
  18457. * @type {TextureNode}
  18458. */
  18459. this._texture = texture( defaultTexture );
  18460. /**
  18461. * A uniform representing the PMREM's width.
  18462. *
  18463. * @private
  18464. * @type {UniformNode<float>}
  18465. */
  18466. this._width = uniform( 0 );
  18467. /**
  18468. * A uniform representing the PMREM's height.
  18469. *
  18470. * @private
  18471. * @type {UniformNode<float>}
  18472. */
  18473. this._height = uniform( 0 );
  18474. /**
  18475. * A uniform representing the PMREM's max Mip.
  18476. *
  18477. * @private
  18478. * @type {UniformNode<float>}
  18479. */
  18480. this._maxMip = uniform( 0 );
  18481. /**
  18482. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  18483. *
  18484. * @type {string}
  18485. * @default 'render'
  18486. */
  18487. this.updateBeforeType = NodeUpdateType.RENDER;
  18488. }
  18489. set value( value ) {
  18490. this._value = value;
  18491. this._pmrem = null;
  18492. }
  18493. /**
  18494. * The node's texture value.
  18495. *
  18496. * @type {Texture}
  18497. */
  18498. get value() {
  18499. return this._value;
  18500. }
  18501. /**
  18502. * Uses the given PMREM texture to update internal values.
  18503. *
  18504. * @param {Texture} texture - The PMREM texture.
  18505. */
  18506. updateFromTexture( texture ) {
  18507. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  18508. this._texture.value = texture;
  18509. this._width.value = cubeUVSize.texelWidth;
  18510. this._height.value = cubeUVSize.texelHeight;
  18511. this._maxMip.value = cubeUVSize.maxMip;
  18512. }
  18513. updateBefore( frame ) {
  18514. let pmrem = this._pmrem;
  18515. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  18516. const texture = this._value;
  18517. if ( pmremVersion !== texture.pmremVersion ) {
  18518. if ( texture.isPMREMTexture === true ) {
  18519. pmrem = texture;
  18520. } else {
  18521. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  18522. }
  18523. if ( pmrem !== null ) {
  18524. this._pmrem = pmrem;
  18525. this.updateFromTexture( pmrem );
  18526. }
  18527. }
  18528. }
  18529. setup( builder ) {
  18530. if ( this._generator === null ) {
  18531. this._generator = new PMREMGenerator( builder.renderer );
  18532. }
  18533. this.updateBefore( builder );
  18534. //
  18535. let uvNode = this.uvNode;
  18536. if ( uvNode === null && builder.context.getUV ) {
  18537. uvNode = builder.context.getUV( this, builder );
  18538. }
  18539. //
  18540. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  18541. //
  18542. let levelNode = this.levelNode;
  18543. if ( levelNode === null && builder.context.getTextureLevel ) {
  18544. levelNode = builder.context.getTextureLevel( this );
  18545. }
  18546. //
  18547. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  18548. }
  18549. dispose() {
  18550. super.dispose();
  18551. if ( this._generator !== null ) this._generator.dispose();
  18552. }
  18553. }
  18554. /**
  18555. * Returns `true` if the given cube map image has been fully loaded.
  18556. *
  18557. * @private
  18558. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  18559. * @return {boolean} Whether the given cube map is ready or not.
  18560. */
  18561. function isCubeMapReady( image ) {
  18562. if ( image === null || image === undefined ) return false;
  18563. let count = 0;
  18564. const length = 6;
  18565. for ( let i = 0; i < length; i ++ ) {
  18566. if ( image[ i ] !== undefined ) count ++;
  18567. }
  18568. return count === length;
  18569. }
  18570. /**
  18571. * Returns `true` if the given equirectangular image has been fully loaded.
  18572. *
  18573. * @private
  18574. * @param {(Image|Object)} image - The equirectangular image.
  18575. * @return {boolean} Whether the given cube map is ready or not.
  18576. */
  18577. function isEquirectangularMapReady( image ) {
  18578. if ( image === null || image === undefined ) return false;
  18579. return image.height > 0;
  18580. }
  18581. /**
  18582. * TSL function for creating a PMREM node.
  18583. *
  18584. * @tsl
  18585. * @function
  18586. * @param {Texture} value - The input texture.
  18587. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  18588. * @param {?Node<float>} [levelNode=null] - The level node.
  18589. * @returns {PMREMNode}
  18590. */
  18591. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  18592. const _envNodeCache = new WeakMap();
  18593. /**
  18594. * Represents a physical model for Image-based lighting (IBL). The environment
  18595. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  18596. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  18597. *
  18598. * @augments LightingNode
  18599. */
  18600. class EnvironmentNode extends LightingNode {
  18601. static get type() {
  18602. return 'EnvironmentNode';
  18603. }
  18604. /**
  18605. * Constructs a new environment node.
  18606. *
  18607. * @param {Node} [envNode=null] - A node representing the environment.
  18608. */
  18609. constructor( envNode = null ) {
  18610. super();
  18611. /**
  18612. * A node representing the environment.
  18613. *
  18614. * @type {?Node}
  18615. * @default null
  18616. */
  18617. this.envNode = envNode;
  18618. }
  18619. setup( builder ) {
  18620. const { material } = builder;
  18621. let envNode = this.envNode;
  18622. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  18623. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  18624. let cacheEnvNode = _envNodeCache.get( value );
  18625. if ( cacheEnvNode === undefined ) {
  18626. cacheEnvNode = pmremTexture( value );
  18627. _envNodeCache.set( value, cacheEnvNode );
  18628. }
  18629. envNode = cacheEnvNode;
  18630. }
  18631. //
  18632. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  18633. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  18634. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  18635. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  18636. const isolateRadiance = isolate( radiance );
  18637. const isolateIrradiance = isolate( irradiance );
  18638. //
  18639. builder.context.radiance.addAssign( isolateRadiance );
  18640. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  18641. //
  18642. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  18643. if ( clearcoatRadiance ) {
  18644. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  18645. const isolateClearcoatRadiance = isolate( clearcoatRadianceContext );
  18646. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  18647. }
  18648. }
  18649. }
  18650. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  18651. let reflectVec = null;
  18652. return {
  18653. getUV: () => {
  18654. if ( reflectVec === null ) {
  18655. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  18656. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  18657. reflectVec = pow4( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  18658. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  18659. }
  18660. return reflectVec;
  18661. },
  18662. getTextureLevel: () => {
  18663. return roughnessNode;
  18664. }
  18665. };
  18666. };
  18667. const createIrradianceContext = ( normalWorldNode ) => {
  18668. return {
  18669. getUV: () => {
  18670. return normalWorldNode;
  18671. },
  18672. getTextureLevel: () => {
  18673. return float( 1.0 );
  18674. }
  18675. };
  18676. };
  18677. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  18678. /**
  18679. * Node material version of {@link MeshStandardMaterial}.
  18680. *
  18681. * @augments NodeMaterial
  18682. */
  18683. class MeshStandardNodeMaterial extends NodeMaterial {
  18684. static get type() {
  18685. return 'MeshStandardNodeMaterial';
  18686. }
  18687. /**
  18688. * Constructs a new mesh standard node material.
  18689. *
  18690. * @param {Object} [parameters] - The configuration parameter.
  18691. */
  18692. constructor( parameters ) {
  18693. super();
  18694. /**
  18695. * This flag can be used for type testing.
  18696. *
  18697. * @type {boolean}
  18698. * @readonly
  18699. * @default true
  18700. */
  18701. this.isMeshStandardNodeMaterial = true;
  18702. /**
  18703. * Set to `true` because standard materials react on lights.
  18704. *
  18705. * @type {boolean}
  18706. * @default true
  18707. */
  18708. this.lights = true;
  18709. /**
  18710. * The emissive color of standard materials is by default inferred from the `emissive`,
  18711. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  18712. * overwrite the default and define the emissive color with a node instead.
  18713. *
  18714. * If you don't want to overwrite the emissive color but modify the existing
  18715. * value instead, use {@link materialEmissive}.
  18716. *
  18717. * @type {?Node<vec3>}
  18718. * @default null
  18719. */
  18720. this.emissiveNode = null;
  18721. /**
  18722. * The metalness of standard materials is by default inferred from the `metalness`,
  18723. * and `metalnessMap` properties. This node property allows to
  18724. * overwrite the default and define the metalness with a node instead.
  18725. *
  18726. * If you don't want to overwrite the metalness but modify the existing
  18727. * value instead, use {@link materialMetalness}.
  18728. *
  18729. * @type {?Node<float>}
  18730. * @default null
  18731. */
  18732. this.metalnessNode = null;
  18733. /**
  18734. * The roughness of standard materials is by default inferred from the `roughness`,
  18735. * and `roughnessMap` properties. This node property allows to
  18736. * overwrite the default and define the roughness with a node instead.
  18737. *
  18738. * If you don't want to overwrite the roughness but modify the existing
  18739. * value instead, use {@link materialRoughness}.
  18740. *
  18741. * @type {?Node<float>}
  18742. * @default null
  18743. */
  18744. this.roughnessNode = null;
  18745. this.setDefaultValues( _defaultValues$6 );
  18746. this.setValues( parameters );
  18747. }
  18748. /**
  18749. * Overwritten since this type of material uses {@link EnvironmentNode}
  18750. * to implement the PBR (PMREM based) environment mapping. Besides, the
  18751. * method honors `Scene.environment`.
  18752. *
  18753. * @param {NodeBuilder} builder - The current node builder.
  18754. * @return {?EnvironmentNode<vec3>} The environment node.
  18755. */
  18756. setupEnvironment( builder ) {
  18757. let envNode = super.setupEnvironment( builder );
  18758. if ( envNode === null && builder.environmentNode ) {
  18759. envNode = builder.environmentNode;
  18760. }
  18761. return envNode ? new EnvironmentNode( envNode ) : null;
  18762. }
  18763. /**
  18764. * Setups the lighting model.
  18765. *
  18766. * @return {PhysicalLightingModel} The lighting model.
  18767. */
  18768. setupLightingModel( /*builder*/ ) {
  18769. return new PhysicalLightingModel();
  18770. }
  18771. /**
  18772. * Setups the specular related node variables.
  18773. */
  18774. setupSpecular() {
  18775. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  18776. specularColor.assign( vec3( 0.04 ) );
  18777. specularColorBlended.assign( specularColorNode );
  18778. specularF90.assign( 1.0 );
  18779. }
  18780. /**
  18781. * Setups the standard specific node variables.
  18782. *
  18783. * @param {NodeBuilder} builder - The current node builder.
  18784. */
  18785. setupVariants() {
  18786. // METALNESS
  18787. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  18788. metalness.assign( metalnessNode );
  18789. // ROUGHNESS
  18790. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  18791. roughnessNode = getRoughness( { roughness: roughnessNode } );
  18792. roughness.assign( roughnessNode );
  18793. // SPECULAR COLOR
  18794. this.setupSpecular();
  18795. // DIFFUSE COLOR
  18796. diffuseContribution.assign( diffuseColor.rgb.mul( metalnessNode.oneMinus() ) );
  18797. }
  18798. copy( source ) {
  18799. this.emissiveNode = source.emissiveNode;
  18800. this.metalnessNode = source.metalnessNode;
  18801. this.roughnessNode = source.roughnessNode;
  18802. return super.copy( source );
  18803. }
  18804. }
  18805. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  18806. /**
  18807. * Node material version of {@link MeshPhysicalMaterial}.
  18808. *
  18809. * @augments MeshStandardNodeMaterial
  18810. */
  18811. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  18812. static get type() {
  18813. return 'MeshPhysicalNodeMaterial';
  18814. }
  18815. /**
  18816. * Constructs a new mesh physical node material.
  18817. *
  18818. * @param {Object} [parameters] - The configuration parameter.
  18819. */
  18820. constructor( parameters ) {
  18821. super();
  18822. /**
  18823. * This flag can be used for type testing.
  18824. *
  18825. * @type {boolean}
  18826. * @readonly
  18827. * @default true
  18828. */
  18829. this.isMeshPhysicalNodeMaterial = true;
  18830. /**
  18831. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  18832. * and `clearcoatMap` properties. This node property allows to overwrite the default
  18833. * and define the clearcoat with a node instead.
  18834. *
  18835. * If you don't want to overwrite the clearcoat but modify the existing
  18836. * value instead, use {@link materialClearcoat}.
  18837. *
  18838. * @type {?Node<float>}
  18839. * @default null
  18840. */
  18841. this.clearcoatNode = null;
  18842. /**
  18843. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  18844. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  18845. * and define the clearcoat roughness with a node instead.
  18846. *
  18847. * If you don't want to overwrite the clearcoat roughness but modify the existing
  18848. * value instead, use {@link materialClearcoatRoughness}.
  18849. *
  18850. * @type {?Node<float>}
  18851. * @default null
  18852. */
  18853. this.clearcoatRoughnessNode = null;
  18854. /**
  18855. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  18856. * property. This node property allows to overwrite the default
  18857. * and define the clearcoat normal with a node instead.
  18858. *
  18859. * If you don't want to overwrite the clearcoat normal but modify the existing
  18860. * value instead, use {@link materialClearcoatNormal}.
  18861. *
  18862. * @type {?Node<vec3>}
  18863. * @default null
  18864. */
  18865. this.clearcoatNormalNode = null;
  18866. /**
  18867. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  18868. * and `sheenColorMap` properties. This node property allows to overwrite the default
  18869. * and define the sheen with a node instead.
  18870. *
  18871. * If you don't want to overwrite the sheen but modify the existing
  18872. * value instead, use {@link materialSheen}.
  18873. *
  18874. * @type {?Node<vec3>}
  18875. * @default null
  18876. */
  18877. this.sheenNode = null;
  18878. /**
  18879. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  18880. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  18881. * and define the sheen roughness with a node instead.
  18882. *
  18883. * If you don't want to overwrite the sheen roughness but modify the existing
  18884. * value instead, use {@link materialSheenRoughness}.
  18885. *
  18886. * @type {?Node<float>}
  18887. * @default null
  18888. */
  18889. this.sheenRoughnessNode = null;
  18890. /**
  18891. * The iridescence of physical materials is by default inferred from the `iridescence`
  18892. * property. This node property allows to overwrite the default
  18893. * and define the iridescence with a node instead.
  18894. *
  18895. * If you don't want to overwrite the iridescence but modify the existing
  18896. * value instead, use {@link materialIridescence}.
  18897. *
  18898. * @type {?Node<float>}
  18899. * @default null
  18900. */
  18901. this.iridescenceNode = null;
  18902. /**
  18903. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  18904. * property. This node property allows to overwrite the default
  18905. * and define the iridescence IOR with a node instead.
  18906. *
  18907. * If you don't want to overwrite the iridescence IOR but modify the existing
  18908. * value instead, use {@link materialIridescenceIOR}.
  18909. *
  18910. * @type {?Node<float>}
  18911. * @default null
  18912. */
  18913. this.iridescenceIORNode = null;
  18914. /**
  18915. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  18916. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  18917. * and define the iridescence thickness with a node instead.
  18918. *
  18919. * If you don't want to overwrite the iridescence thickness but modify the existing
  18920. * value instead, use {@link materialIridescenceThickness}.
  18921. *
  18922. * @type {?Node<float>}
  18923. * @default null
  18924. */
  18925. this.iridescenceThicknessNode = null;
  18926. /**
  18927. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  18928. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  18929. * and define the specular intensity with a node instead.
  18930. *
  18931. * If you don't want to overwrite the specular intensity but modify the existing
  18932. * value instead, use {@link materialSpecularIntensity}.
  18933. *
  18934. * @type {?Node<float>}
  18935. * @default null
  18936. */
  18937. this.specularIntensityNode = null;
  18938. /**
  18939. * The specular color of physical materials is by default inferred from the `specularColor`
  18940. * and `specularColorMap` properties. This node property allows to overwrite the default
  18941. * and define the specular color with a node instead.
  18942. *
  18943. * If you don't want to overwrite the specular color but modify the existing
  18944. * value instead, use {@link materialSpecularColor}.
  18945. *
  18946. * @type {?Node<vec3>}
  18947. * @default null
  18948. */
  18949. this.specularColorNode = null;
  18950. /**
  18951. * The ior of physical materials is by default inferred from the `ior`
  18952. * property. This node property allows to overwrite the default
  18953. * and define the ior with a node instead.
  18954. *
  18955. * If you don't want to overwrite the ior but modify the existing
  18956. * value instead, use {@link materialIOR}.
  18957. *
  18958. * @type {?Node<float>}
  18959. * @default null
  18960. */
  18961. this.iorNode = null;
  18962. /**
  18963. * The transmission of physical materials is by default inferred from the `transmission` and
  18964. * `transmissionMap` properties. This node property allows to overwrite the default
  18965. * and define the transmission with a node instead.
  18966. *
  18967. * If you don't want to overwrite the transmission but modify the existing
  18968. * value instead, use {@link materialTransmission}.
  18969. *
  18970. * @type {?Node<float>}
  18971. * @default null
  18972. */
  18973. this.transmissionNode = null;
  18974. /**
  18975. * The thickness of physical materials is by default inferred from the `thickness` and
  18976. * `thicknessMap` properties. This node property allows to overwrite the default
  18977. * and define the thickness with a node instead.
  18978. *
  18979. * If you don't want to overwrite the thickness but modify the existing
  18980. * value instead, use {@link materialThickness}.
  18981. *
  18982. * @type {?Node<float>}
  18983. * @default null
  18984. */
  18985. this.thicknessNode = null;
  18986. /**
  18987. * The attenuation distance of physical materials is by default inferred from the
  18988. * `attenuationDistance` property. This node property allows to overwrite the default
  18989. * and define the attenuation distance with a node instead.
  18990. *
  18991. * If you don't want to overwrite the attenuation distance but modify the existing
  18992. * value instead, use {@link materialAttenuationDistance}.
  18993. *
  18994. * @type {?Node<float>}
  18995. * @default null
  18996. */
  18997. this.attenuationDistanceNode = null;
  18998. /**
  18999. * The attenuation color of physical materials is by default inferred from the
  19000. * `attenuationColor` property. This node property allows to overwrite the default
  19001. * and define the attenuation color with a node instead.
  19002. *
  19003. * If you don't want to overwrite the attenuation color but modify the existing
  19004. * value instead, use {@link materialAttenuationColor}.
  19005. *
  19006. * @type {?Node<vec3>}
  19007. * @default null
  19008. */
  19009. this.attenuationColorNode = null;
  19010. /**
  19011. * The dispersion of physical materials is by default inferred from the
  19012. * `dispersion` property. This node property allows to overwrite the default
  19013. * and define the dispersion with a node instead.
  19014. *
  19015. * If you don't want to overwrite the dispersion but modify the existing
  19016. * value instead, use {@link materialDispersion}.
  19017. *
  19018. * @type {?Node<float>}
  19019. * @default null
  19020. */
  19021. this.dispersionNode = null;
  19022. /**
  19023. * The anisotropy of physical materials is by default inferred from the
  19024. * `anisotropy` property. This node property allows to overwrite the default
  19025. * and define the anisotropy with a node instead.
  19026. *
  19027. * If you don't want to overwrite the anisotropy but modify the existing
  19028. * value instead, use {@link materialAnisotropy}.
  19029. *
  19030. * @type {?Node<float>}
  19031. * @default null
  19032. */
  19033. this.anisotropyNode = null;
  19034. this.setDefaultValues( _defaultValues$5 );
  19035. this.setValues( parameters );
  19036. }
  19037. /**
  19038. * Whether the lighting model should use clearcoat or not.
  19039. *
  19040. * @type {boolean}
  19041. * @default true
  19042. */
  19043. get useClearcoat() {
  19044. return this.clearcoat > 0 || this.clearcoatNode !== null;
  19045. }
  19046. /**
  19047. * Whether the lighting model should use iridescence or not.
  19048. *
  19049. * @type {boolean}
  19050. * @default true
  19051. */
  19052. get useIridescence() {
  19053. return this.iridescence > 0 || this.iridescenceNode !== null;
  19054. }
  19055. /**
  19056. * Whether the lighting model should use sheen or not.
  19057. *
  19058. * @type {boolean}
  19059. * @default true
  19060. */
  19061. get useSheen() {
  19062. return this.sheen > 0 || this.sheenNode !== null;
  19063. }
  19064. /**
  19065. * Whether the lighting model should use anisotropy or not.
  19066. *
  19067. * @type {boolean}
  19068. * @default true
  19069. */
  19070. get useAnisotropy() {
  19071. return this.anisotropy > 0 || this.anisotropyNode !== null;
  19072. }
  19073. /**
  19074. * Whether the lighting model should use transmission or not.
  19075. *
  19076. * @type {boolean}
  19077. * @default true
  19078. */
  19079. get useTransmission() {
  19080. return this.transmission > 0 || this.transmissionNode !== null;
  19081. }
  19082. /**
  19083. * Whether the lighting model should use dispersion or not.
  19084. *
  19085. * @type {boolean}
  19086. * @default true
  19087. */
  19088. get useDispersion() {
  19089. return this.dispersion > 0 || this.dispersionNode !== null;
  19090. }
  19091. /**
  19092. * Setups the specular related node variables.
  19093. */
  19094. setupSpecular() {
  19095. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  19096. ior.assign( iorNode );
  19097. specularColor.assign( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ) );
  19098. specularColorBlended.assign( mix( specularColor, diffuseColor.rgb, metalness ) );
  19099. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  19100. }
  19101. /**
  19102. * Setups the lighting model.
  19103. *
  19104. * @return {PhysicalLightingModel} The lighting model.
  19105. */
  19106. setupLightingModel( /*builder*/ ) {
  19107. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  19108. }
  19109. /**
  19110. * Setups the physical specific node variables.
  19111. *
  19112. * @param {NodeBuilder} builder - The current node builder.
  19113. */
  19114. setupVariants( builder ) {
  19115. super.setupVariants( builder );
  19116. // CLEARCOAT
  19117. if ( this.useClearcoat ) {
  19118. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  19119. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  19120. clearcoat.assign( clearcoatNode );
  19121. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  19122. }
  19123. // SHEEN
  19124. if ( this.useSheen ) {
  19125. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  19126. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  19127. sheen.assign( sheenNode );
  19128. sheenRoughness.assign( sheenRoughnessNode );
  19129. }
  19130. // IRIDESCENCE
  19131. if ( this.useIridescence ) {
  19132. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  19133. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  19134. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  19135. iridescence.assign( iridescenceNode );
  19136. iridescenceIOR.assign( iridescenceIORNode );
  19137. iridescenceThickness.assign( iridescenceThicknessNode );
  19138. }
  19139. // ANISOTROPY
  19140. if ( this.useAnisotropy ) {
  19141. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  19142. anisotropy.assign( anisotropyV.length() );
  19143. If( anisotropy.equal( 0.0 ), () => {
  19144. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  19145. } ).Else( () => {
  19146. anisotropyV.divAssign( vec2( anisotropy ) );
  19147. anisotropy.assign( anisotropy.saturate() );
  19148. } );
  19149. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  19150. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  19151. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  19152. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  19153. }
  19154. // TRANSMISSION
  19155. if ( this.useTransmission ) {
  19156. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  19157. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  19158. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  19159. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  19160. transmission.assign( transmissionNode );
  19161. thickness.assign( thicknessNode );
  19162. attenuationDistance.assign( attenuationDistanceNode );
  19163. attenuationColor.assign( attenuationColorNode );
  19164. if ( this.useDispersion ) {
  19165. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  19166. dispersion.assign( dispersionNode );
  19167. }
  19168. }
  19169. }
  19170. /**
  19171. * Setups the clearcoat normal node.
  19172. *
  19173. * @return {Node<vec3>} The clearcoat normal.
  19174. */
  19175. setupClearcoatNormal() {
  19176. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  19177. }
  19178. setup( builder ) {
  19179. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  19180. super.setup( builder );
  19181. }
  19182. copy( source ) {
  19183. this.clearcoatNode = source.clearcoatNode;
  19184. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  19185. this.clearcoatNormalNode = source.clearcoatNormalNode;
  19186. this.sheenNode = source.sheenNode;
  19187. this.sheenRoughnessNode = source.sheenRoughnessNode;
  19188. this.iridescenceNode = source.iridescenceNode;
  19189. this.iridescenceIORNode = source.iridescenceIORNode;
  19190. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  19191. this.specularIntensityNode = source.specularIntensityNode;
  19192. this.specularColorNode = source.specularColorNode;
  19193. this.transmissionNode = source.transmissionNode;
  19194. this.thicknessNode = source.thicknessNode;
  19195. this.attenuationDistanceNode = source.attenuationDistanceNode;
  19196. this.attenuationColorNode = source.attenuationColorNode;
  19197. this.dispersionNode = source.dispersionNode;
  19198. this.anisotropyNode = source.anisotropyNode;
  19199. return super.copy( source );
  19200. }
  19201. }
  19202. /**
  19203. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  19204. *
  19205. * @augments PhysicalLightingModel
  19206. */
  19207. class SSSLightingModel extends PhysicalLightingModel {
  19208. /**
  19209. * Constructs a new physical lighting model.
  19210. *
  19211. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  19212. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  19213. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  19214. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  19215. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  19216. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  19217. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  19218. */
  19219. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  19220. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  19221. /**
  19222. * Whether the lighting model should use SSS or not.
  19223. *
  19224. * @type {boolean}
  19225. * @default false
  19226. */
  19227. this.useSSS = sss;
  19228. }
  19229. /**
  19230. * Extends the default implementation with a SSS term.
  19231. *
  19232. * 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/)
  19233. *
  19234. * @param {Object} input - The input data.
  19235. * @param {NodeBuilder} builder - The current node builder.
  19236. */
  19237. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19238. if ( this.useSSS === true ) {
  19239. const material = builder.material;
  19240. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  19241. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  19242. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  19243. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  19244. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  19245. }
  19246. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  19247. }
  19248. }
  19249. /**
  19250. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  19251. * that implements a Subsurface scattering (SSS) term.
  19252. *
  19253. * @augments MeshPhysicalNodeMaterial
  19254. */
  19255. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  19256. static get type() {
  19257. return 'MeshSSSNodeMaterial';
  19258. }
  19259. /**
  19260. * Constructs a new mesh SSS node material.
  19261. *
  19262. * @param {Object} [parameters] - The configuration parameter.
  19263. */
  19264. constructor( parameters ) {
  19265. super( parameters );
  19266. /**
  19267. * Represents the thickness color.
  19268. *
  19269. * @type {?Node<vec3>}
  19270. * @default null
  19271. */
  19272. this.thicknessColorNode = null;
  19273. /**
  19274. * Represents the distortion factor.
  19275. *
  19276. * @type {?Node<float>}
  19277. */
  19278. this.thicknessDistortionNode = float( 0.1 );
  19279. /**
  19280. * Represents the thickness ambient factor.
  19281. *
  19282. * @type {?Node<float>}
  19283. */
  19284. this.thicknessAmbientNode = float( 0.0 );
  19285. /**
  19286. * Represents the thickness attenuation.
  19287. *
  19288. * @type {?Node<float>}
  19289. */
  19290. this.thicknessAttenuationNode = float( .1 );
  19291. /**
  19292. * Represents the thickness power.
  19293. *
  19294. * @type {?Node<float>}
  19295. */
  19296. this.thicknessPowerNode = float( 2.0 );
  19297. /**
  19298. * Represents the thickness scale.
  19299. *
  19300. * @type {?Node<float>}
  19301. */
  19302. this.thicknessScaleNode = float( 10.0 );
  19303. }
  19304. /**
  19305. * Whether the lighting model should use SSS or not.
  19306. *
  19307. * @type {boolean}
  19308. * @default true
  19309. */
  19310. get useSSS() {
  19311. return this.thicknessColorNode !== null;
  19312. }
  19313. /**
  19314. * Setups the lighting model.
  19315. *
  19316. * @return {SSSLightingModel} The lighting model.
  19317. */
  19318. setupLightingModel( /*builder*/ ) {
  19319. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  19320. }
  19321. copy( source ) {
  19322. this.thicknessColorNode = source.thicknessColorNode;
  19323. this.thicknessDistortionNode = source.thicknessDistortionNode;
  19324. this.thicknessAmbientNode = source.thicknessAmbientNode;
  19325. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  19326. this.thicknessPowerNode = source.thicknessPowerNode;
  19327. this.thicknessScaleNode = source.thicknessScaleNode;
  19328. return super.copy( source );
  19329. }
  19330. }
  19331. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  19332. // dotNL will be from -1.0 to 1.0
  19333. const dotNL = normal.dot( lightDirection );
  19334. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  19335. if ( builder.material.gradientMap ) {
  19336. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  19337. return vec3( gradientMap.r );
  19338. } else {
  19339. const fw = coord.fwidth().mul( 0.5 );
  19340. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  19341. }
  19342. } );
  19343. /**
  19344. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  19345. *
  19346. * @augments LightingModel
  19347. */
  19348. class ToonLightingModel extends LightingModel {
  19349. /**
  19350. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  19351. * reduced to a small number of discrete shades to create a comic-like, flat look.
  19352. *
  19353. * @param {Object} lightData - The light data.
  19354. * @param {NodeBuilder} builder - The current node builder.
  19355. */
  19356. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19357. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  19358. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  19359. }
  19360. /**
  19361. * Implements the indirect lighting.
  19362. *
  19363. * @param {NodeBuilder} builder - The current node builder.
  19364. */
  19365. indirect( builder ) {
  19366. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  19367. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  19368. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  19369. }
  19370. }
  19371. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  19372. /**
  19373. * Node material version of {@link MeshToonMaterial}.
  19374. *
  19375. * @augments NodeMaterial
  19376. */
  19377. class MeshToonNodeMaterial extends NodeMaterial {
  19378. static get type() {
  19379. return 'MeshToonNodeMaterial';
  19380. }
  19381. /**
  19382. * Constructs a new mesh toon node material.
  19383. *
  19384. * @param {Object} [parameters] - The configuration parameter.
  19385. */
  19386. constructor( parameters ) {
  19387. super();
  19388. /**
  19389. * This flag can be used for type testing.
  19390. *
  19391. * @type {boolean}
  19392. * @readonly
  19393. * @default true
  19394. */
  19395. this.isMeshToonNodeMaterial = true;
  19396. /**
  19397. * Set to `true` because toon materials react on lights.
  19398. *
  19399. * @type {boolean}
  19400. * @default true
  19401. */
  19402. this.lights = true;
  19403. this.setDefaultValues( _defaultValues$4 );
  19404. this.setValues( parameters );
  19405. }
  19406. /**
  19407. * Setups the lighting model.
  19408. *
  19409. * @return {ToonLightingModel} The lighting model.
  19410. */
  19411. setupLightingModel( /*builder*/ ) {
  19412. return new ToonLightingModel();
  19413. }
  19414. }
  19415. /**
  19416. * TSL function for creating a matcap uv node.
  19417. *
  19418. * Can be used to compute texture coordinates for projecting a
  19419. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  19420. *
  19421. * @tsl
  19422. * @function
  19423. * @returns {Node<vec2>} The matcap UV coordinates.
  19424. */
  19425. const matcapUV = /*@__PURE__*/ Fn( () => {
  19426. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  19427. const y = positionViewDirection.cross( x );
  19428. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  19429. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  19430. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  19431. /**
  19432. * Node material version of {@link MeshMatcapMaterial}.
  19433. *
  19434. * @augments NodeMaterial
  19435. */
  19436. class MeshMatcapNodeMaterial extends NodeMaterial {
  19437. static get type() {
  19438. return 'MeshMatcapNodeMaterial';
  19439. }
  19440. /**
  19441. * Constructs a new mesh normal node material.
  19442. *
  19443. * @param {Object} [parameters] - The configuration parameter.
  19444. */
  19445. constructor( parameters ) {
  19446. super();
  19447. /**
  19448. * This flag can be used for type testing.
  19449. *
  19450. * @type {boolean}
  19451. * @readonly
  19452. * @default true
  19453. */
  19454. this.isMeshMatcapNodeMaterial = true;
  19455. this.setDefaultValues( _defaultValues$3 );
  19456. this.setValues( parameters );
  19457. }
  19458. /**
  19459. * Setups the matcap specific node variables.
  19460. *
  19461. * @param {NodeBuilder} builder - The current node builder.
  19462. */
  19463. setupVariants( builder ) {
  19464. const uv = matcapUV;
  19465. let matcapColor;
  19466. if ( builder.material.matcap ) {
  19467. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  19468. } else {
  19469. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  19470. }
  19471. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  19472. }
  19473. }
  19474. /**
  19475. * Applies a rotation to the given position node.
  19476. *
  19477. * @augments TempNode
  19478. */
  19479. class RotateNode extends TempNode {
  19480. static get type() {
  19481. return 'RotateNode';
  19482. }
  19483. /**
  19484. * Constructs a new rotate node.
  19485. *
  19486. * @param {Node} positionNode - The position node.
  19487. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19488. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19489. */
  19490. constructor( positionNode, rotationNode ) {
  19491. super();
  19492. /**
  19493. * The position node.
  19494. *
  19495. * @type {Node}
  19496. */
  19497. this.positionNode = positionNode;
  19498. /**
  19499. * Represents the rotation that is applied to the position node.
  19500. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19501. *
  19502. * @type {Node}
  19503. */
  19504. this.rotationNode = rotationNode;
  19505. }
  19506. /**
  19507. * The type of the {@link RotateNode#positionNode} defines the node's type.
  19508. *
  19509. * @param {NodeBuilder} builder - The current node builder.
  19510. * @return {string} The node's type.
  19511. */
  19512. getNodeType( builder ) {
  19513. return this.positionNode.getNodeType( builder );
  19514. }
  19515. setup( builder ) {
  19516. const { rotationNode, positionNode } = this;
  19517. const nodeType = this.getNodeType( builder );
  19518. if ( nodeType === 'vec2' ) {
  19519. const cosAngle = rotationNode.cos();
  19520. const sinAngle = rotationNode.sin();
  19521. const rotationMatrix = mat2(
  19522. cosAngle, sinAngle,
  19523. sinAngle.negate(), cosAngle
  19524. );
  19525. return rotationMatrix.mul( positionNode );
  19526. } else {
  19527. const rotation = rotationNode;
  19528. 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 ) );
  19529. 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 ) );
  19530. 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 ) );
  19531. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  19532. }
  19533. }
  19534. }
  19535. /**
  19536. * TSL function for creating a rotate node.
  19537. *
  19538. * @tsl
  19539. * @function
  19540. * @param {Node} positionNode - The position node.
  19541. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19542. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19543. * @returns {RotateNode}
  19544. */
  19545. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  19546. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  19547. /**
  19548. * Node material version of {@link SpriteMaterial}.
  19549. *
  19550. * @augments NodeMaterial
  19551. */
  19552. class SpriteNodeMaterial extends NodeMaterial {
  19553. static get type() {
  19554. return 'SpriteNodeMaterial';
  19555. }
  19556. /**
  19557. * Constructs a new sprite node material.
  19558. *
  19559. * @param {Object} [parameters] - The configuration parameter.
  19560. */
  19561. constructor( parameters ) {
  19562. super();
  19563. /**
  19564. * This flag can be used for type testing.
  19565. *
  19566. * @type {boolean}
  19567. * @readonly
  19568. * @default true
  19569. */
  19570. this.isSpriteNodeMaterial = true;
  19571. this._useSizeAttenuation = true;
  19572. /**
  19573. * This property makes it possible to define the position of the sprite with a
  19574. * node. That can be useful when the material is used with instanced rendering
  19575. * and node data are defined with an instanced attribute node:
  19576. * ```js
  19577. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  19578. * material.positionNode = instancedBufferAttribute( positionAttribute );
  19579. * ```
  19580. * Another possibility is to compute the instanced data with a compute shader:
  19581. * ```js
  19582. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  19583. * particleMaterial.positionNode = positionBuffer.toAttribute();
  19584. * ```
  19585. *
  19586. * @type {?Node<vec2>}
  19587. * @default null
  19588. */
  19589. this.positionNode = null;
  19590. /**
  19591. * The rotation of sprite materials is by default inferred from the `rotation`,
  19592. * property. This node property allows to overwrite the default and define
  19593. * the rotation with a node instead.
  19594. *
  19595. * If you don't want to overwrite the rotation but modify the existing
  19596. * value instead, use {@link materialRotation}.
  19597. *
  19598. * @type {?Node<float>}
  19599. * @default null
  19600. */
  19601. this.rotationNode = null;
  19602. /**
  19603. * This node property provides an additional way to scale sprites next to
  19604. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  19605. * is multiplied with the scale value of this node in the vertex shader.
  19606. *
  19607. * @type {?Node<vec2>}
  19608. * @default null
  19609. */
  19610. this.scaleNode = null;
  19611. /**
  19612. * In Sprites, the transparent property is enabled by default.
  19613. *
  19614. * @type {boolean}
  19615. * @default true
  19616. */
  19617. this.transparent = true;
  19618. this.setDefaultValues( _defaultValues$2 );
  19619. this.setValues( parameters );
  19620. }
  19621. /**
  19622. * Setups the position node in view space. This method implements
  19623. * the sprite specific vertex shader.
  19624. *
  19625. * @param {NodeBuilder} builder - The current node builder.
  19626. * @return {Node<vec3>} The position in view space.
  19627. */
  19628. setupPositionView( builder ) {
  19629. const { object, camera } = builder;
  19630. const { positionNode, rotationNode, scaleNode, sizeAttenuation } = this;
  19631. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  19632. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  19633. if ( scaleNode !== null ) {
  19634. scale = scale.mul( vec2( scaleNode ) );
  19635. }
  19636. if ( camera.isPerspectiveCamera && sizeAttenuation === false ) {
  19637. scale = scale.mul( mvPosition.z.negate() );
  19638. }
  19639. let alignedPosition = positionGeometry.xy;
  19640. if ( object.center && object.center.isVector2 === true ) {
  19641. const center = reference$1( 'center', 'vec2', object );
  19642. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  19643. }
  19644. alignedPosition = alignedPosition.mul( scale );
  19645. const rotation = float( rotationNode || materialRotation );
  19646. const rotatedPosition = rotate( alignedPosition, rotation );
  19647. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  19648. }
  19649. copy( source ) {
  19650. this.positionNode = source.positionNode;
  19651. this.rotationNode = source.rotationNode;
  19652. this.scaleNode = source.scaleNode;
  19653. return super.copy( source );
  19654. }
  19655. /**
  19656. * Whether to use size attenuation or not.
  19657. *
  19658. * @type {boolean}
  19659. * @default true
  19660. */
  19661. get sizeAttenuation() {
  19662. return this._useSizeAttenuation;
  19663. }
  19664. set sizeAttenuation( value ) {
  19665. if ( this._useSizeAttenuation !== value ) {
  19666. this._useSizeAttenuation = value;
  19667. this.needsUpdate = true;
  19668. }
  19669. }
  19670. }
  19671. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  19672. const _size$4 = /*@__PURE__*/ new Vector2();
  19673. /**
  19674. * Node material version of {@link PointsMaterial}.
  19675. *
  19676. * This material can be used in two ways:
  19677. *
  19678. * - By rendering point primitives with {@link Points}. Since WebGPU only supports point primitives
  19679. * with a pixel size of `1`, it's not possible to define a size.
  19680. *
  19681. * ```js
  19682. * const pointCloud = new THREE.Points( geometry, new THREE.PointsNodeMaterial() );
  19683. * ```
  19684. *
  19685. * - By rendering point primitives with {@link Sprites}. In this case, size is honored,
  19686. * see {@link PointsNodeMaterial#sizeNode}.
  19687. *
  19688. * ```js
  19689. * const instancedPoints = new THREE.Sprite( new THREE.PointsNodeMaterial( { positionNode: instancedBufferAttribute( positionAttribute ) } ) );
  19690. * ```
  19691. *
  19692. * @augments SpriteNodeMaterial
  19693. */
  19694. class PointsNodeMaterial extends SpriteNodeMaterial {
  19695. static get type() {
  19696. return 'PointsNodeMaterial';
  19697. }
  19698. /**
  19699. * Constructs a new points node material.
  19700. *
  19701. * @param {Object} [parameters] - The configuration parameter.
  19702. */
  19703. constructor( parameters ) {
  19704. super();
  19705. /**
  19706. * This node property provides an additional way to set the point size.
  19707. *
  19708. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  19709. * this node has no effect when the material is used with {@link Points} and a WebGPU
  19710. * backend. If an application wants to render points with a size larger than 1 pixel,
  19711. * the material should be used with {@link Sprite} and instancing.
  19712. *
  19713. * @type {?Node<vec2>}
  19714. * @default null
  19715. */
  19716. this.sizeNode = null;
  19717. /**
  19718. * This flag can be used for type testing.
  19719. *
  19720. * @type {boolean}
  19721. * @readonly
  19722. * @default true
  19723. */
  19724. this.isPointsNodeMaterial = true;
  19725. this.setDefaultValues( _defaultValues$1 );
  19726. this.setValues( parameters );
  19727. }
  19728. setupPositionView() {
  19729. const { positionNode } = this;
  19730. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  19731. }
  19732. setupVertexSprite( builder ) {
  19733. const { material, camera } = builder;
  19734. const { rotationNode, scaleNode, sizeNode, sizeAttenuation } = this;
  19735. let mvp = super.setupVertex( builder );
  19736. // skip further processing if the material is not a node material
  19737. if ( material.isNodeMaterial !== true ) {
  19738. return mvp;
  19739. }
  19740. // point size
  19741. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  19742. pointSize = pointSize.mul( screenDPR );
  19743. // size attenuation
  19744. if ( camera.isPerspectiveCamera && sizeAttenuation === true ) {
  19745. // follow WebGLRenderer's implementation, and scale by half the canvas height in logical units
  19746. pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
  19747. }
  19748. // scale
  19749. if ( scaleNode && scaleNode.isNode ) {
  19750. pointSize = pointSize.mul( vec2( scaleNode ) );
  19751. }
  19752. // compute offset
  19753. let offset = positionGeometry.xy;
  19754. // apply rotation
  19755. if ( rotationNode && rotationNode.isNode ) {
  19756. const rotation = float( rotationNode );
  19757. offset = rotate( offset, rotation );
  19758. }
  19759. // account for point size
  19760. offset = offset.mul( pointSize );
  19761. // scale by viewport size
  19762. offset = offset.div( viewportSize.div( 2 ) );
  19763. // compensate for the perspective divide
  19764. offset = offset.mul( mvp.w );
  19765. // add offset
  19766. mvp = mvp.add( vec4( offset, 0, 0 ) );
  19767. return mvp;
  19768. }
  19769. setupVertex( builder ) {
  19770. if ( builder.object.isPoints ) {
  19771. return super.setupVertex( builder );
  19772. } else {
  19773. return this.setupVertexSprite( builder );
  19774. }
  19775. }
  19776. /**
  19777. * Whether alpha to coverage should be used or not.
  19778. *
  19779. * @type {boolean}
  19780. * @default true
  19781. */
  19782. get alphaToCoverage() {
  19783. return this._useAlphaToCoverage;
  19784. }
  19785. set alphaToCoverage( value ) {
  19786. if ( this._useAlphaToCoverage !== value ) {
  19787. this._useAlphaToCoverage = value;
  19788. this.needsUpdate = true;
  19789. }
  19790. }
  19791. }
  19792. const scale = /*@__PURE__*/ uniform( 1 ).onFrameUpdate( function ( { renderer } ) {
  19793. const size = renderer.getSize( _size$4 ); // logical units
  19794. this.value = 0.5 * size.y;
  19795. } );
  19796. /**
  19797. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  19798. *
  19799. * @augments LightingModel
  19800. */
  19801. class ShadowMaskModel extends LightingModel {
  19802. /**
  19803. * Constructs a new shadow mask model.
  19804. */
  19805. constructor() {
  19806. super();
  19807. /**
  19808. * The shadow mask node.
  19809. *
  19810. * @type {Node}
  19811. */
  19812. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  19813. }
  19814. /**
  19815. * Only used to save the shadow mask.
  19816. *
  19817. * @param {Object} input - The input data.
  19818. */
  19819. direct( { lightNode } ) {
  19820. if ( lightNode.shadowNode !== null ) {
  19821. this.shadowNode.mulAssign( lightNode.shadowNode );
  19822. }
  19823. }
  19824. /**
  19825. * Uses the shadow mask to produce the final color.
  19826. *
  19827. * @param {NodeBuilder} builder - The current node builder.
  19828. */
  19829. finish( { context } ) {
  19830. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  19831. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  19832. }
  19833. }
  19834. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  19835. /**
  19836. * Node material version of {@link ShadowMaterial}.
  19837. *
  19838. * @augments NodeMaterial
  19839. */
  19840. class ShadowNodeMaterial extends NodeMaterial {
  19841. static get type() {
  19842. return 'ShadowNodeMaterial';
  19843. }
  19844. /**
  19845. * Constructs a new shadow node material.
  19846. *
  19847. * @param {Object} [parameters] - The configuration parameter.
  19848. */
  19849. constructor( parameters ) {
  19850. super();
  19851. /**
  19852. * This flag can be used for type testing.
  19853. *
  19854. * @type {boolean}
  19855. * @readonly
  19856. * @default true
  19857. */
  19858. this.isShadowNodeMaterial = true;
  19859. /**
  19860. * Set to `true` because so it's possible to implement
  19861. * the shadow mask effect.
  19862. *
  19863. * @type {boolean}
  19864. * @default true
  19865. */
  19866. this.lights = true;
  19867. /**
  19868. * Overwritten since shadow materials are transparent
  19869. * by default.
  19870. *
  19871. * @type {boolean}
  19872. * @default true
  19873. */
  19874. this.transparent = true;
  19875. this.setDefaultValues( _defaultValues );
  19876. this.setValues( parameters );
  19877. }
  19878. /**
  19879. * Setups the lighting model.
  19880. *
  19881. * @return {ShadowMaskModel} The lighting model.
  19882. */
  19883. setupLightingModel( /*builder*/ ) {
  19884. return new ShadowMaskModel();
  19885. }
  19886. }
  19887. const scatteringDensity = property( 'vec3' );
  19888. const linearDepthRay = property( 'vec3' );
  19889. const outgoingRayLight = property( 'vec3' );
  19890. /**
  19891. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  19892. * This model calculates the scattering and transmittance of light through a volumetric medium.
  19893. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  19894. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  19895. *
  19896. * @augments LightingModel
  19897. */
  19898. class VolumetricLightingModel extends LightingModel {
  19899. constructor() {
  19900. super();
  19901. }
  19902. start( builder ) {
  19903. const { material } = builder;
  19904. const startPos = property( 'vec3' );
  19905. const endPos = property( 'vec3' );
  19906. // This approach dynamically changes the direction of the ray,
  19907. // 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.
  19908. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  19909. startPos.assign( cameraPosition );
  19910. endPos.assign( positionWorld );
  19911. } ).Else( () => {
  19912. startPos.assign( positionWorld );
  19913. endPos.assign( cameraPosition );
  19914. } );
  19915. //
  19916. const viewVector = endPos.sub( startPos );
  19917. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  19918. const stepSize = viewVector.length().div( steps ).toVar();
  19919. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  19920. const distTravelled = float( 0.0 ).toVar();
  19921. const transmittance = vec3( 1 ).toVar();
  19922. if ( material.offsetNode ) {
  19923. // reduce banding
  19924. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  19925. }
  19926. Loop( steps, () => {
  19927. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  19928. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  19929. if ( material.depthNode !== null ) {
  19930. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  19931. builder.context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  19932. }
  19933. builder.context.positionWorld = positionRay;
  19934. builder.context.shadowPositionWorld = positionRay;
  19935. builder.context.positionView = positionViewRay;
  19936. scatteringDensity.assign( 0 );
  19937. let scatteringNode;
  19938. if ( material.scatteringNode ) {
  19939. scatteringNode = material.scatteringNode( {
  19940. positionRay
  19941. } );
  19942. }
  19943. super.start( builder );
  19944. if ( scatteringNode ) {
  19945. scatteringDensity.mulAssign( scatteringNode );
  19946. }
  19947. // beer's law
  19948. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  19949. transmittance.mulAssign( falloff );
  19950. // move along the ray
  19951. distTravelled.addAssign( stepSize );
  19952. } );
  19953. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  19954. }
  19955. scatteringLight( lightColor, builder ) {
  19956. const sceneDepthNode = builder.context.sceneDepthNode;
  19957. if ( sceneDepthNode ) {
  19958. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  19959. scatteringDensity.addAssign( lightColor );
  19960. } );
  19961. } else {
  19962. scatteringDensity.addAssign( lightColor );
  19963. }
  19964. }
  19965. direct( { lightNode, lightColor }, builder ) {
  19966. // Ignore lights with infinite distance
  19967. if ( lightNode.light.distance === undefined ) return;
  19968. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  19969. const directLight = lightColor.xyz.toVar();
  19970. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  19971. this.scatteringLight( directLight, builder );
  19972. }
  19973. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  19974. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  19975. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  19976. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  19977. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  19978. const P = builder.context.positionView;
  19979. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  19980. this.scatteringLight( directLight, builder );
  19981. }
  19982. finish( builder ) {
  19983. builder.context.outgoingLight.assign( outgoingRayLight );
  19984. }
  19985. }
  19986. /**
  19987. * Volume node material.
  19988. *
  19989. * @augments NodeMaterial
  19990. */
  19991. class VolumeNodeMaterial extends NodeMaterial {
  19992. static get type() {
  19993. return 'VolumeNodeMaterial';
  19994. }
  19995. /**
  19996. * Constructs a new volume node material.
  19997. *
  19998. * @param {Object} [parameters] - The configuration parameter.
  19999. */
  20000. constructor( parameters ) {
  20001. super();
  20002. /**
  20003. * This flag can be used for type testing.
  20004. *
  20005. * @type {boolean}
  20006. * @readonly
  20007. * @default true
  20008. */
  20009. this.isVolumeNodeMaterial = true;
  20010. /**
  20011. * Number of steps used for raymarching.
  20012. *
  20013. * @type {number}
  20014. * @default 25
  20015. */
  20016. this.steps = 25;
  20017. /**
  20018. * Offsets the distance a ray has been traveled through a volume.
  20019. * Can be used to implement dithering to reduce banding.
  20020. *
  20021. * @type {Node<float>}
  20022. * @default null
  20023. */
  20024. this.offsetNode = null;
  20025. /**
  20026. * Node used for scattering calculations.
  20027. *
  20028. * @type {Function|FunctionNode<vec4>}
  20029. * @default null
  20030. */
  20031. this.scatteringNode = null;
  20032. this.lights = true;
  20033. this.transparent = true;
  20034. this.side = BackSide;
  20035. this.depthTest = false;
  20036. this.depthWrite = false;
  20037. this.setValues( parameters );
  20038. }
  20039. setupLightingModel() {
  20040. return new VolumetricLightingModel();
  20041. }
  20042. }
  20043. /**
  20044. * This module manages the internal animation loop of the renderer.
  20045. *
  20046. * @private
  20047. */
  20048. class Animation {
  20049. /**
  20050. * Constructs a new animation loop management component.
  20051. *
  20052. * @param {Renderer} renderer - A reference to the main renderer.
  20053. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20054. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20055. */
  20056. constructor( renderer, nodes, info ) {
  20057. /**
  20058. * A reference to the main renderer.
  20059. *
  20060. * @type {Renderer}
  20061. */
  20062. this.renderer = renderer;
  20063. /**
  20064. * Renderer component for managing nodes related logic.
  20065. *
  20066. * @type {Nodes}
  20067. */
  20068. this.nodes = nodes;
  20069. /**
  20070. * Renderer component for managing metrics and monitoring data.
  20071. *
  20072. * @type {Info}
  20073. */
  20074. this.info = info;
  20075. /**
  20076. * A reference to the context from `requestAnimationFrame()` can
  20077. * be called (usually `window`).
  20078. *
  20079. * @type {?(Window|XRSession)}
  20080. */
  20081. this._context = typeof self !== 'undefined' ? self : null;
  20082. /**
  20083. * The user-defined animation loop.
  20084. *
  20085. * @type {?Function}
  20086. * @default null
  20087. */
  20088. this._animationLoop = null;
  20089. /**
  20090. * The requestId which is returned from the `requestAnimationFrame()` call.
  20091. * Can be used to cancel the stop the animation loop.
  20092. *
  20093. * @type {?number}
  20094. * @default null
  20095. */
  20096. this._requestId = null;
  20097. }
  20098. /**
  20099. * Starts the internal animation loop.
  20100. */
  20101. start() {
  20102. const update = ( time, xrFrame ) => {
  20103. this._requestId = this._context.requestAnimationFrame( update );
  20104. if ( this.info.autoReset === true ) this.info.reset();
  20105. this.nodes.nodeFrame.update();
  20106. this.info.frame = this.nodes.nodeFrame.frameId;
  20107. this.renderer._inspector.begin();
  20108. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  20109. this.renderer._inspector.finish();
  20110. };
  20111. update();
  20112. }
  20113. /**
  20114. * Stops the internal animation loop.
  20115. */
  20116. stop() {
  20117. this._context.cancelAnimationFrame( this._requestId );
  20118. this._requestId = null;
  20119. }
  20120. /**
  20121. * Returns the user-level animation loop.
  20122. *
  20123. * @return {?Function} The animation loop.
  20124. */
  20125. getAnimationLoop() {
  20126. return this._animationLoop;
  20127. }
  20128. /**
  20129. * Defines the user-level animation loop.
  20130. *
  20131. * @param {?Function} callback - The animation loop.
  20132. */
  20133. setAnimationLoop( callback ) {
  20134. this._animationLoop = callback;
  20135. }
  20136. /**
  20137. * Returns the animation context.
  20138. *
  20139. * @return {Window|XRSession} The animation context.
  20140. */
  20141. getContext() {
  20142. return this._context;
  20143. }
  20144. /**
  20145. * Defines the context in which `requestAnimationFrame()` is executed.
  20146. *
  20147. * @param {Window|XRSession} context - The context to set.
  20148. */
  20149. setContext( context ) {
  20150. this._context = context;
  20151. }
  20152. /**
  20153. * Frees all internal resources and stops the animation loop.
  20154. */
  20155. dispose() {
  20156. this.stop();
  20157. }
  20158. }
  20159. /**
  20160. * Data structure for the renderer. It allows defining values
  20161. * with chained, hierarchical keys. Keys are meant to be
  20162. * objects since the module internally works with Weak Maps
  20163. * for performance reasons.
  20164. *
  20165. * @private
  20166. */
  20167. class ChainMap {
  20168. /**
  20169. * Constructs a new Chain Map.
  20170. */
  20171. constructor() {
  20172. /**
  20173. * The root Weak Map.
  20174. *
  20175. * @type {WeakMap<Object, WeakMap>}
  20176. */
  20177. this.weakMap = new WeakMap();
  20178. }
  20179. /**
  20180. * Returns the value for the given array of keys.
  20181. *
  20182. * @param {Array<Object>} keys - List of keys.
  20183. * @return {any} The value. Returns `undefined` if no value was found.
  20184. */
  20185. get( keys ) {
  20186. let map = this.weakMap;
  20187. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20188. map = map.get( keys[ i ] );
  20189. if ( map === undefined ) return undefined;
  20190. }
  20191. return map.get( keys[ keys.length - 1 ] );
  20192. }
  20193. /**
  20194. * Sets the value for the given keys.
  20195. *
  20196. * @param {Array<Object>} keys - List of keys.
  20197. * @param {any} value - The value to set.
  20198. * @return {ChainMap} A reference to this Chain Map.
  20199. */
  20200. set( keys, value ) {
  20201. let map = this.weakMap;
  20202. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20203. const key = keys[ i ];
  20204. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  20205. map = map.get( key );
  20206. }
  20207. map.set( keys[ keys.length - 1 ], value );
  20208. return this;
  20209. }
  20210. /**
  20211. * Deletes a value for the given keys.
  20212. *
  20213. * @param {Array<Object>} keys - The keys.
  20214. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  20215. */
  20216. delete( keys ) {
  20217. let map = this.weakMap;
  20218. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20219. map = map.get( keys[ i ] );
  20220. if ( map === undefined ) return false;
  20221. }
  20222. return map.delete( keys[ keys.length - 1 ] );
  20223. }
  20224. }
  20225. let _id$a = 0;
  20226. function getKeys( obj ) {
  20227. const keys = Object.keys( obj );
  20228. let proto = Object.getPrototypeOf( obj );
  20229. while ( proto ) {
  20230. const descriptors = Object.getOwnPropertyDescriptors( proto );
  20231. for ( const key in descriptors ) {
  20232. if ( descriptors[ key ] !== undefined ) {
  20233. const descriptor = descriptors[ key ];
  20234. if ( descriptor && typeof descriptor.get === 'function' ) {
  20235. keys.push( key );
  20236. }
  20237. }
  20238. }
  20239. proto = Object.getPrototypeOf( proto );
  20240. }
  20241. return keys;
  20242. }
  20243. /**
  20244. * A render object is the renderer's representation of single entity that gets drawn
  20245. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  20246. * scene since render objects also depend from the used material, the current render context
  20247. * and the current scene's lighting.
  20248. *
  20249. * In general, the basic process of the renderer is:
  20250. *
  20251. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  20252. * - Process the render lists by calling one or more render commands for each render item.
  20253. * - For each render command, request a render object and perform the draw.
  20254. *
  20255. * The module provides an interface to get data required for the draw command like the actual
  20256. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  20257. * creating render objects should only be done when necessary.
  20258. *
  20259. * @private
  20260. */
  20261. class RenderObject {
  20262. /**
  20263. * Constructs a new render object.
  20264. *
  20265. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20266. * @param {Geometries} geometries - Renderer component for managing geometries.
  20267. * @param {Renderer} renderer - The renderer.
  20268. * @param {Object3D} object - The 3D object.
  20269. * @param {Material} material - The 3D object's material.
  20270. * @param {Scene} scene - The scene the 3D object belongs to.
  20271. * @param {Camera} camera - The camera the object should be rendered with.
  20272. * @param {LightsNode} lightsNode - The lights node.
  20273. * @param {RenderContext} renderContext - The render context.
  20274. * @param {ClippingContext} clippingContext - The clipping context.
  20275. */
  20276. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  20277. this.id = _id$a ++;
  20278. /**
  20279. * Renderer component for managing nodes related logic.
  20280. *
  20281. * @type {Nodes}
  20282. * @private
  20283. */
  20284. this._nodes = nodes;
  20285. /**
  20286. * Renderer component for managing geometries.
  20287. *
  20288. * @type {Geometries}
  20289. * @private
  20290. */
  20291. this._geometries = geometries;
  20292. /**
  20293. * The renderer.
  20294. *
  20295. * @type {Renderer}
  20296. */
  20297. this.renderer = renderer;
  20298. /**
  20299. * The 3D object.
  20300. *
  20301. * @type {Object3D}
  20302. */
  20303. this.object = object;
  20304. /**
  20305. * The 3D object's material.
  20306. *
  20307. * @type {Material}
  20308. */
  20309. this.material = material;
  20310. /**
  20311. * The scene the 3D object belongs to.
  20312. *
  20313. * @type {Scene}
  20314. */
  20315. this.scene = scene;
  20316. /**
  20317. * The camera the 3D object should be rendered with.
  20318. *
  20319. * @type {Camera}
  20320. */
  20321. this.camera = camera;
  20322. /**
  20323. * The lights node.
  20324. *
  20325. * @type {LightsNode}
  20326. */
  20327. this.lightsNode = lightsNode;
  20328. /**
  20329. * The render context.
  20330. *
  20331. * @type {RenderContext}
  20332. */
  20333. this.context = renderContext;
  20334. /**
  20335. * The 3D object's geometry.
  20336. *
  20337. * @type {BufferGeometry}
  20338. */
  20339. this.geometry = object.geometry;
  20340. /**
  20341. * The render object's version.
  20342. *
  20343. * @type {number}
  20344. */
  20345. this.version = material.version;
  20346. /**
  20347. * The draw range of the geometry.
  20348. *
  20349. * @type {?Object}
  20350. * @default null
  20351. */
  20352. this.drawRange = null;
  20353. /**
  20354. * An array holding the buffer attributes
  20355. * of the render object. This entails attribute
  20356. * definitions on geometry and node level.
  20357. *
  20358. * @type {?Array<BufferAttribute>}
  20359. * @default null
  20360. */
  20361. this.attributes = null;
  20362. /**
  20363. * An object holding the version of the
  20364. * attributes. The keys are the attribute names
  20365. * and the values are the attribute versions.
  20366. *
  20367. * @type {?Object<string, number>}
  20368. * @default null
  20369. */
  20370. this.attributesId = null;
  20371. /**
  20372. * A reference to a render pipeline the render
  20373. * object is processed with.
  20374. *
  20375. * @type {RenderPipeline}
  20376. * @default null
  20377. */
  20378. this.pipeline = null;
  20379. /**
  20380. * Only relevant for objects using
  20381. * multiple materials. This represents a group entry
  20382. * from the respective `BufferGeometry`.
  20383. *
  20384. * @type {?{start: number, count: number}}
  20385. * @default null
  20386. */
  20387. this.group = null;
  20388. /**
  20389. * An array holding the vertex buffers which can
  20390. * be buffer attributes but also interleaved buffers.
  20391. *
  20392. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  20393. * @default null
  20394. */
  20395. this.vertexBuffers = null;
  20396. /**
  20397. * The parameters for the draw command.
  20398. *
  20399. * @type {?Object}
  20400. * @default null
  20401. */
  20402. this.drawParams = null;
  20403. /**
  20404. * If this render object is used inside a render bundle,
  20405. * this property points to the respective bundle group.
  20406. *
  20407. * @type {?BundleGroup}
  20408. * @default null
  20409. */
  20410. this.bundle = null;
  20411. /**
  20412. * The clipping context.
  20413. *
  20414. * @type {ClippingContext}
  20415. */
  20416. this.clippingContext = clippingContext;
  20417. /**
  20418. * The clipping context's cache key.
  20419. *
  20420. * @type {string}
  20421. */
  20422. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  20423. /**
  20424. * The initial node cache key.
  20425. *
  20426. * @type {number}
  20427. */
  20428. this.initialNodesCacheKey = this.getDynamicCacheKey();
  20429. /**
  20430. * The initial cache key.
  20431. *
  20432. * @type {number}
  20433. */
  20434. this.initialCacheKey = this.getCacheKey();
  20435. /**
  20436. * The node builder state.
  20437. *
  20438. * @type {?NodeBuilderState}
  20439. * @private
  20440. * @default null
  20441. */
  20442. this._nodeBuilderState = null;
  20443. /**
  20444. * An array of bindings.
  20445. *
  20446. * @type {?Array<BindGroup>}
  20447. * @private
  20448. * @default null
  20449. */
  20450. this._bindings = null;
  20451. /**
  20452. * Reference to the node material observer.
  20453. *
  20454. * @type {?NodeMaterialObserver}
  20455. * @private
  20456. * @default null
  20457. */
  20458. this._monitor = null;
  20459. /**
  20460. * An event listener which is defined by `RenderObjects`. It performs
  20461. * clean up tasks when `dispose()` on this render object.
  20462. *
  20463. * @method
  20464. */
  20465. this.onDispose = null;
  20466. /**
  20467. * This flag can be used for type testing.
  20468. *
  20469. * @type {boolean}
  20470. * @readonly
  20471. * @default true
  20472. */
  20473. this.isRenderObject = true;
  20474. /**
  20475. * An event listener which is executed when `dispose()` is called on
  20476. * the material of this render object.
  20477. *
  20478. * @method
  20479. */
  20480. this.onMaterialDispose = () => {
  20481. this.dispose();
  20482. };
  20483. /**
  20484. * An event listener which is executed when `dispose()` is called on
  20485. * the geometry of this render object.
  20486. *
  20487. * @method
  20488. */
  20489. this.onGeometryDispose = () => {
  20490. // clear geometry cache attributes
  20491. this.attributes = null;
  20492. this.attributesId = null;
  20493. };
  20494. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  20495. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  20496. }
  20497. /**
  20498. * Updates the clipping context.
  20499. *
  20500. * @param {ClippingContext} context - The clipping context to set.
  20501. */
  20502. updateClipping( context ) {
  20503. this.clippingContext = context;
  20504. }
  20505. /**
  20506. * Whether the clipping requires an update or not.
  20507. *
  20508. * @type {boolean}
  20509. * @readonly
  20510. */
  20511. get clippingNeedsUpdate() {
  20512. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  20513. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  20514. return true;
  20515. }
  20516. /**
  20517. * The number of clipping planes defined in context of hardware clipping.
  20518. *
  20519. * @type {number}
  20520. * @readonly
  20521. */
  20522. get hardwareClippingPlanes() {
  20523. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  20524. }
  20525. /**
  20526. * Returns the node builder state of this render object.
  20527. *
  20528. * @return {NodeBuilderState} The node builder state.
  20529. */
  20530. getNodeBuilderState() {
  20531. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  20532. }
  20533. /**
  20534. * Returns the node material observer of this render object.
  20535. *
  20536. * @return {NodeMaterialObserver} The node material observer.
  20537. */
  20538. getMonitor() {
  20539. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  20540. }
  20541. /**
  20542. * Returns an array of bind groups of this render object.
  20543. *
  20544. * @return {Array<BindGroup>} The bindings.
  20545. */
  20546. getBindings() {
  20547. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  20548. }
  20549. /**
  20550. * Returns a binding group by group name of this render object.
  20551. *
  20552. * @param {string} name - The name of the binding group.
  20553. * @return {?BindGroup} The bindings.
  20554. */
  20555. getBindingGroup( name ) {
  20556. for ( const bindingGroup of this.getBindings() ) {
  20557. if ( bindingGroup.name === name ) {
  20558. return bindingGroup;
  20559. }
  20560. }
  20561. }
  20562. /**
  20563. * Returns the index of the render object's geometry.
  20564. *
  20565. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20566. */
  20567. getIndex() {
  20568. return this._geometries.getIndex( this );
  20569. }
  20570. /**
  20571. * Returns the indirect buffer attribute.
  20572. *
  20573. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20574. */
  20575. getIndirect() {
  20576. return this._geometries.getIndirect( this );
  20577. }
  20578. /**
  20579. * Returns an array that acts as a key for identifying the render object in a chain map.
  20580. *
  20581. * @return {Array<Object>} An array with object references.
  20582. */
  20583. getChainArray() {
  20584. return [ this.object, this.material, this.context, this.lightsNode ];
  20585. }
  20586. /**
  20587. * This method is used when the geometry of a 3D object has been exchanged and the
  20588. * respective render object now requires an update.
  20589. *
  20590. * @param {BufferGeometry} geometry - The geometry to set.
  20591. */
  20592. setGeometry( geometry ) {
  20593. this.geometry = geometry;
  20594. this.attributes = null;
  20595. this.attributesId = null;
  20596. }
  20597. /**
  20598. * Returns the buffer attributes of the render object. The returned array holds
  20599. * attribute definitions on geometry and node level.
  20600. *
  20601. * @return {Array<BufferAttribute>} An array with buffer attributes.
  20602. */
  20603. getAttributes() {
  20604. if ( this.attributes !== null ) return this.attributes;
  20605. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  20606. const geometry = this.geometry;
  20607. const attributes = [];
  20608. const vertexBuffers = new Set();
  20609. const attributesId = {};
  20610. for ( const nodeAttribute of nodeAttributes ) {
  20611. let attribute;
  20612. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  20613. // node attribute
  20614. attribute = nodeAttribute.node.attribute;
  20615. } else {
  20616. // geometry attribute
  20617. attribute = geometry.getAttribute( nodeAttribute.name );
  20618. attributesId[ nodeAttribute.name ] = attribute.version;
  20619. }
  20620. if ( attribute === undefined ) continue;
  20621. attributes.push( attribute );
  20622. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  20623. vertexBuffers.add( bufferAttribute );
  20624. }
  20625. this.attributes = attributes;
  20626. this.attributesId = attributesId;
  20627. this.vertexBuffers = Array.from( vertexBuffers.values() );
  20628. return attributes;
  20629. }
  20630. /**
  20631. * Returns the vertex buffers of the render object.
  20632. *
  20633. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  20634. */
  20635. getVertexBuffers() {
  20636. if ( this.vertexBuffers === null ) this.getAttributes();
  20637. return this.vertexBuffers;
  20638. }
  20639. /**
  20640. * Returns the draw parameters for the render object.
  20641. *
  20642. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  20643. */
  20644. getDrawParameters() {
  20645. const { object, material, geometry, group, drawRange } = this;
  20646. const drawParams = this.drawParams || ( this.drawParams = {
  20647. vertexCount: 0,
  20648. firstVertex: 0,
  20649. instanceCount: 0,
  20650. firstInstance: 0
  20651. } );
  20652. const index = this.getIndex();
  20653. const hasIndex = ( index !== null );
  20654. let instanceCount = 1;
  20655. if ( geometry.isInstancedBufferGeometry === true ) {
  20656. instanceCount = geometry.instanceCount;
  20657. } else if ( object.count !== undefined ) {
  20658. instanceCount = Math.max( 0, object.count );
  20659. }
  20660. if ( instanceCount === 0 ) return null;
  20661. drawParams.instanceCount = instanceCount;
  20662. if ( object.isBatchedMesh === true ) return drawParams;
  20663. let rangeFactor = 1;
  20664. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  20665. rangeFactor = 2;
  20666. }
  20667. let firstVertex = drawRange.start * rangeFactor;
  20668. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  20669. if ( group !== null ) {
  20670. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  20671. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  20672. }
  20673. const position = geometry.attributes.position;
  20674. let itemCount = Infinity;
  20675. if ( hasIndex ) {
  20676. itemCount = index.count;
  20677. } else if ( position !== undefined && position !== null ) {
  20678. itemCount = position.count;
  20679. }
  20680. firstVertex = Math.max( firstVertex, 0 );
  20681. lastVertex = Math.min( lastVertex, itemCount );
  20682. const count = lastVertex - firstVertex;
  20683. if ( count < 0 || count === Infinity ) return null;
  20684. drawParams.vertexCount = count;
  20685. drawParams.firstVertex = firstVertex;
  20686. return drawParams;
  20687. }
  20688. /**
  20689. * Returns the render object's geometry cache key.
  20690. *
  20691. * The geometry cache key is part of the material cache key.
  20692. *
  20693. * @return {string} The geometry cache key.
  20694. */
  20695. getGeometryCacheKey() {
  20696. const { geometry } = this;
  20697. let cacheKey = '';
  20698. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  20699. const attribute = geometry.attributes[ name ];
  20700. cacheKey += name + ',';
  20701. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  20702. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  20703. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  20704. if ( attribute.normalized ) cacheKey += 'n,';
  20705. }
  20706. // structural equality isn't sufficient for morph targets since the
  20707. // data are maintained in textures. only if the targets are all equal
  20708. // the texture and thus the instance of `MorphNode` can be shared.
  20709. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  20710. const targets = geometry.morphAttributes[ name ];
  20711. cacheKey += 'morph-' + name + ',';
  20712. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  20713. const attribute = targets[ i ];
  20714. cacheKey += attribute.id + ',';
  20715. }
  20716. }
  20717. if ( geometry.index ) {
  20718. cacheKey += 'index,';
  20719. }
  20720. return cacheKey;
  20721. }
  20722. /**
  20723. * Returns the render object's material cache key.
  20724. *
  20725. * The material cache key is part of the render object cache key.
  20726. *
  20727. * @return {number} The material cache key.
  20728. */
  20729. getMaterialCacheKey() {
  20730. const { object, material, renderer } = this;
  20731. let cacheKey = material.customProgramCacheKey();
  20732. for ( const property of getKeys( material ) ) {
  20733. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  20734. const value = material[ property ];
  20735. let valueKey;
  20736. if ( value !== null ) {
  20737. // some material values require a formatting
  20738. const type = typeof value;
  20739. if ( type === 'number' ) {
  20740. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  20741. } else if ( type === 'object' ) {
  20742. valueKey = '{';
  20743. if ( value.isTexture ) {
  20744. valueKey += value.mapping;
  20745. // WebGPU must honor the sampler data because they are part of the bindings
  20746. if ( renderer.backend.isWebGPUBackend === true ) {
  20747. valueKey += value.magFilter;
  20748. valueKey += value.minFilter;
  20749. valueKey += value.wrapS;
  20750. valueKey += value.wrapT;
  20751. valueKey += value.wrapR;
  20752. }
  20753. }
  20754. valueKey += '}';
  20755. } else {
  20756. valueKey = String( value );
  20757. }
  20758. } else {
  20759. valueKey = String( value );
  20760. }
  20761. cacheKey += /*property + ':' +*/ valueKey + ',';
  20762. }
  20763. cacheKey += this.clippingContextCacheKey + ',';
  20764. if ( object.geometry ) {
  20765. cacheKey += this.getGeometryCacheKey();
  20766. }
  20767. if ( object.skeleton ) {
  20768. cacheKey += object.skeleton.bones.length + ',';
  20769. }
  20770. if ( object.isBatchedMesh ) {
  20771. cacheKey += object._matricesTexture.uuid + ',';
  20772. if ( object._colorsTexture !== null ) {
  20773. cacheKey += object._colorsTexture.uuid + ',';
  20774. }
  20775. }
  20776. if ( object.isInstancedMesh || object.count > 1 || Array.isArray( object.morphTargetInfluences ) ) {
  20777. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  20778. cacheKey += object.uuid + ',';
  20779. }
  20780. cacheKey += this.context.id + ',';
  20781. cacheKey += object.receiveShadow + ',';
  20782. return hashString( cacheKey );
  20783. }
  20784. /**
  20785. * Whether the geometry requires an update or not.
  20786. *
  20787. * @type {boolean}
  20788. * @readonly
  20789. */
  20790. get needsGeometryUpdate() {
  20791. if ( this.geometry.id !== this.object.geometry.id ) return true;
  20792. if ( this.attributes !== null ) {
  20793. const attributesId = this.attributesId;
  20794. for ( const name in attributesId ) {
  20795. const attribute = this.geometry.getAttribute( name );
  20796. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  20797. return true;
  20798. }
  20799. }
  20800. }
  20801. return false;
  20802. }
  20803. /**
  20804. * Whether the render object requires an update or not.
  20805. *
  20806. * Note: There are two distinct places where render objects are checked for an update.
  20807. *
  20808. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  20809. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  20810. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  20811. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  20812. * a need for a refresh due to material, geometry or object related value changes.
  20813. *
  20814. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  20815. * that performs the 'needsUpdate' check.
  20816. *
  20817. * @type {boolean}
  20818. * @readonly
  20819. */
  20820. get needsUpdate() {
  20821. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  20822. }
  20823. /**
  20824. * Returns the dynamic cache key which represents a key that is computed per draw command.
  20825. *
  20826. * @return {number} The cache key.
  20827. */
  20828. getDynamicCacheKey() {
  20829. let cacheKey = 0;
  20830. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  20831. // the renderer is inside a shadow pass.
  20832. if ( this.material.isShadowPassMaterial !== true ) {
  20833. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  20834. }
  20835. if ( this.camera.isArrayCamera ) {
  20836. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  20837. }
  20838. if ( this.object.receiveShadow ) {
  20839. cacheKey = hash$1( cacheKey, 1 );
  20840. }
  20841. cacheKey = hash$1( cacheKey, this.camera.id, this.renderer.contextNode.id, this.renderer.contextNode.version );
  20842. return cacheKey;
  20843. }
  20844. /**
  20845. * Returns the render object's cache key.
  20846. *
  20847. * @return {number} The cache key.
  20848. */
  20849. getCacheKey() {
  20850. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  20851. }
  20852. /**
  20853. * Frees internal resources.
  20854. */
  20855. dispose() {
  20856. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  20857. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  20858. this.onDispose();
  20859. }
  20860. }
  20861. const _chainKeys$5 = [];
  20862. /**
  20863. * This module manages the render objects of the renderer.
  20864. *
  20865. * @private
  20866. */
  20867. class RenderObjects {
  20868. /**
  20869. * Constructs a new render object management component.
  20870. *
  20871. * @param {Renderer} renderer - The renderer.
  20872. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20873. * @param {Geometries} geometries - Renderer component for managing geometries.
  20874. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  20875. * @param {Bindings} bindings - Renderer component for managing bindings.
  20876. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20877. */
  20878. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  20879. /**
  20880. * The renderer.
  20881. *
  20882. * @type {Renderer}
  20883. */
  20884. this.renderer = renderer;
  20885. /**
  20886. * Renderer component for managing nodes related logic.
  20887. *
  20888. * @type {Nodes}
  20889. */
  20890. this.nodes = nodes;
  20891. /**
  20892. * Renderer component for managing geometries.
  20893. *
  20894. * @type {Geometries}
  20895. */
  20896. this.geometries = geometries;
  20897. /**
  20898. * Renderer component for managing pipelines.
  20899. *
  20900. * @type {Pipelines}
  20901. */
  20902. this.pipelines = pipelines;
  20903. /**
  20904. * Renderer component for managing bindings.
  20905. *
  20906. * @type {Bindings}
  20907. */
  20908. this.bindings = bindings;
  20909. /**
  20910. * Renderer component for managing metrics and monitoring data.
  20911. *
  20912. * @type {Info}
  20913. */
  20914. this.info = info;
  20915. /**
  20916. * A dictionary that manages render contexts in chain maps
  20917. * for each pass ID.
  20918. *
  20919. * @type {Object<string,ChainMap>}
  20920. */
  20921. this.chainMaps = {};
  20922. }
  20923. /**
  20924. * Returns a render object for the given object and state data.
  20925. *
  20926. * @param {Object3D} object - The 3D object.
  20927. * @param {Material} material - The 3D object's material.
  20928. * @param {Scene} scene - The scene the 3D object belongs to.
  20929. * @param {Camera} camera - The camera the 3D object should be rendered with.
  20930. * @param {LightsNode} lightsNode - The lights node.
  20931. * @param {RenderContext} renderContext - The render context.
  20932. * @param {ClippingContext} clippingContext - The clipping context.
  20933. * @param {string} [passId] - An optional ID for identifying the pass.
  20934. * @return {RenderObject} The render object.
  20935. */
  20936. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  20937. const chainMap = this.getChainMap( passId );
  20938. // reuse chainArray
  20939. _chainKeys$5[ 0 ] = object;
  20940. _chainKeys$5[ 1 ] = material;
  20941. _chainKeys$5[ 2 ] = renderContext;
  20942. _chainKeys$5[ 3 ] = lightsNode;
  20943. let renderObject = chainMap.get( _chainKeys$5 );
  20944. if ( renderObject === undefined ) {
  20945. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20946. chainMap.set( _chainKeys$5, renderObject );
  20947. } else {
  20948. renderObject.updateClipping( clippingContext );
  20949. if ( renderObject.needsGeometryUpdate ) {
  20950. renderObject.setGeometry( object.geometry );
  20951. }
  20952. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  20953. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  20954. renderObject.dispose();
  20955. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20956. } else {
  20957. renderObject.version = material.version;
  20958. }
  20959. }
  20960. }
  20961. _chainKeys$5.length = 0;
  20962. return renderObject;
  20963. }
  20964. /**
  20965. * Returns a chain map for the given pass ID.
  20966. *
  20967. * @param {string} [passId='default'] - The pass ID.
  20968. * @return {ChainMap} The chain map.
  20969. */
  20970. getChainMap( passId = 'default' ) {
  20971. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  20972. }
  20973. /**
  20974. * Frees internal resources.
  20975. */
  20976. dispose() {
  20977. this.chainMaps = {};
  20978. }
  20979. /**
  20980. * Factory method for creating render objects with the given list of parameters.
  20981. *
  20982. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20983. * @param {Geometries} geometries - Renderer component for managing geometries.
  20984. * @param {Renderer} renderer - The renderer.
  20985. * @param {Object3D} object - The 3D object.
  20986. * @param {Material} material - The object's material.
  20987. * @param {Scene} scene - The scene the 3D object belongs to.
  20988. * @param {Camera} camera - The camera the object should be rendered with.
  20989. * @param {LightsNode} lightsNode - The lights node.
  20990. * @param {RenderContext} renderContext - The render context.
  20991. * @param {ClippingContext} clippingContext - The clipping context.
  20992. * @param {string} [passId] - An optional ID for identifying the pass.
  20993. * @return {RenderObject} The render object.
  20994. */
  20995. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  20996. const chainMap = this.getChainMap( passId );
  20997. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  20998. renderObject.onDispose = () => {
  20999. this.pipelines.delete( renderObject );
  21000. this.bindings.deleteForRender( renderObject );
  21001. this.nodes.delete( renderObject );
  21002. chainMap.delete( renderObject.getChainArray() );
  21003. };
  21004. return renderObject;
  21005. }
  21006. }
  21007. /**
  21008. * Data structure for the renderer. It is intended to manage
  21009. * data of objects in dictionaries.
  21010. *
  21011. * @private
  21012. */
  21013. class DataMap {
  21014. /**
  21015. * Constructs a new data map.
  21016. */
  21017. constructor() {
  21018. /**
  21019. * `DataMap` internally uses a weak map
  21020. * to manage its data.
  21021. *
  21022. * @type {WeakMap<Object, Object>}
  21023. */
  21024. this.data = new WeakMap();
  21025. }
  21026. /**
  21027. * Returns the dictionary for the given object.
  21028. *
  21029. * @param {Object} object - The object.
  21030. * @return {Object} The dictionary.
  21031. */
  21032. get( object ) {
  21033. let map = this.data.get( object );
  21034. if ( map === undefined ) {
  21035. map = {};
  21036. this.data.set( object, map );
  21037. }
  21038. return map;
  21039. }
  21040. /**
  21041. * Deletes the dictionary for the given object.
  21042. *
  21043. * @param {Object} object - The object.
  21044. * @return {?Object} The deleted dictionary.
  21045. */
  21046. delete( object ) {
  21047. let map = null;
  21048. if ( this.data.has( object ) ) {
  21049. map = this.data.get( object );
  21050. this.data.delete( object );
  21051. }
  21052. return map;
  21053. }
  21054. /**
  21055. * Returns `true` if the given object has a dictionary defined.
  21056. *
  21057. * @param {Object} object - The object to test.
  21058. * @return {boolean} Whether a dictionary is defined or not.
  21059. */
  21060. has( object ) {
  21061. return this.data.has( object );
  21062. }
  21063. /**
  21064. * Frees internal resources.
  21065. */
  21066. dispose() {
  21067. this.data = new WeakMap();
  21068. }
  21069. }
  21070. const AttributeType = {
  21071. VERTEX: 1,
  21072. INDEX: 2,
  21073. STORAGE: 3,
  21074. INDIRECT: 4
  21075. };
  21076. // size of a chunk in bytes (STD140 layout)
  21077. const GPU_CHUNK_BYTES = 16;
  21078. // @TODO: Move to src/constants.js
  21079. const BlendColorFactor = 211;
  21080. const OneMinusBlendColorFactor = 212;
  21081. /**
  21082. * This renderer module manages geometry attributes.
  21083. *
  21084. * @private
  21085. * @augments DataMap
  21086. */
  21087. class Attributes extends DataMap {
  21088. /**
  21089. * Constructs a new attribute management component.
  21090. *
  21091. * @param {Backend} backend - The renderer's backend.
  21092. */
  21093. constructor( backend ) {
  21094. super();
  21095. /**
  21096. * The renderer's backend.
  21097. *
  21098. * @type {Backend}
  21099. */
  21100. this.backend = backend;
  21101. }
  21102. /**
  21103. * Deletes the data for the given attribute.
  21104. *
  21105. * @param {BufferAttribute} attribute - The attribute.
  21106. * @return {?Object} The deleted attribute data.
  21107. */
  21108. delete( attribute ) {
  21109. const attributeData = super.delete( attribute );
  21110. if ( attributeData !== null ) {
  21111. this.backend.destroyAttribute( attribute );
  21112. }
  21113. return attributeData;
  21114. }
  21115. /**
  21116. * Updates the given attribute. This method creates attribute buffers
  21117. * for new attributes and updates data for existing ones.
  21118. *
  21119. * @param {BufferAttribute} attribute - The attribute to update.
  21120. * @param {number} type - The attribute type.
  21121. */
  21122. update( attribute, type ) {
  21123. const data = this.get( attribute );
  21124. if ( data.version === undefined ) {
  21125. if ( type === AttributeType.VERTEX ) {
  21126. this.backend.createAttribute( attribute );
  21127. } else if ( type === AttributeType.INDEX ) {
  21128. this.backend.createIndexAttribute( attribute );
  21129. } else if ( type === AttributeType.STORAGE ) {
  21130. this.backend.createStorageAttribute( attribute );
  21131. } else if ( type === AttributeType.INDIRECT ) {
  21132. this.backend.createIndirectStorageAttribute( attribute );
  21133. }
  21134. data.version = this._getBufferAttribute( attribute ).version;
  21135. } else {
  21136. const bufferAttribute = this._getBufferAttribute( attribute );
  21137. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  21138. this.backend.updateAttribute( attribute );
  21139. data.version = bufferAttribute.version;
  21140. }
  21141. }
  21142. }
  21143. /**
  21144. * Utility method for handling interleaved buffer attributes correctly.
  21145. * To process them, their `InterleavedBuffer` is returned.
  21146. *
  21147. * @param {BufferAttribute} attribute - The attribute.
  21148. * @return {BufferAttribute|InterleavedBuffer}
  21149. */
  21150. _getBufferAttribute( attribute ) {
  21151. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  21152. return attribute;
  21153. }
  21154. }
  21155. /**
  21156. * Returns the wireframe version for the given geometry.
  21157. *
  21158. * @private
  21159. * @function
  21160. * @param {BufferGeometry} geometry - The geometry.
  21161. * @return {number} The version.
  21162. */
  21163. function getWireframeVersion( geometry ) {
  21164. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  21165. }
  21166. /**
  21167. * Returns a wireframe index attribute for the given geometry.
  21168. *
  21169. * @private
  21170. * @function
  21171. * @param {BufferGeometry} geometry - The geometry.
  21172. * @return {BufferAttribute} The wireframe index attribute.
  21173. */
  21174. function getWireframeIndex( geometry ) {
  21175. const indices = [];
  21176. const geometryIndex = geometry.index;
  21177. const geometryPosition = geometry.attributes.position;
  21178. if ( geometryIndex !== null ) {
  21179. const array = geometryIndex.array;
  21180. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  21181. const a = array[ i + 0 ];
  21182. const b = array[ i + 1 ];
  21183. const c = array[ i + 2 ];
  21184. indices.push( a, b, b, c, c, a );
  21185. }
  21186. } else {
  21187. const array = geometryPosition.array;
  21188. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  21189. const a = i + 0;
  21190. const b = i + 1;
  21191. const c = i + 2;
  21192. indices.push( a, b, b, c, c, a );
  21193. }
  21194. }
  21195. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  21196. attribute.version = getWireframeVersion( geometry );
  21197. return attribute;
  21198. }
  21199. /**
  21200. * This renderer module manages geometries.
  21201. *
  21202. * @private
  21203. * @augments DataMap
  21204. */
  21205. class Geometries extends DataMap {
  21206. /**
  21207. * Constructs a new geometry management component.
  21208. *
  21209. * @param {Attributes} attributes - Renderer component for managing attributes.
  21210. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21211. */
  21212. constructor( attributes, info ) {
  21213. super();
  21214. /**
  21215. * Renderer component for managing attributes.
  21216. *
  21217. * @type {Attributes}
  21218. */
  21219. this.attributes = attributes;
  21220. /**
  21221. * Renderer component for managing metrics and monitoring data.
  21222. *
  21223. * @type {Info}
  21224. */
  21225. this.info = info;
  21226. /**
  21227. * Weak Map for managing attributes for wireframe rendering.
  21228. *
  21229. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  21230. */
  21231. this.wireframes = new WeakMap();
  21232. /**
  21233. * This Weak Map is used to make sure buffer attributes are
  21234. * updated only once per render call.
  21235. *
  21236. * @type {WeakMap<BufferAttribute,number>}
  21237. */
  21238. this.attributeCall = new WeakMap();
  21239. /**
  21240. * Stores the event listeners attached to geometries.
  21241. *
  21242. * @private
  21243. * @type {Map<BufferGeometry,Function>}
  21244. */
  21245. this._geometryDisposeListeners = new Map();
  21246. }
  21247. /**
  21248. * Returns `true` if the given render object has an initialized geometry.
  21249. *
  21250. * @param {RenderObject} renderObject - The render object.
  21251. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  21252. */
  21253. has( renderObject ) {
  21254. const geometry = renderObject.geometry;
  21255. return super.has( geometry ) && this.get( geometry ).initialized === true;
  21256. }
  21257. /**
  21258. * Prepares the geometry of the given render object for rendering.
  21259. *
  21260. * @param {RenderObject} renderObject - The render object.
  21261. */
  21262. updateForRender( renderObject ) {
  21263. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  21264. this.updateAttributes( renderObject );
  21265. }
  21266. /**
  21267. * Initializes the geometry of the given render object.
  21268. *
  21269. * @param {RenderObject} renderObject - The render object.
  21270. */
  21271. initGeometry( renderObject ) {
  21272. const geometry = renderObject.geometry;
  21273. const geometryData = this.get( geometry );
  21274. geometryData.initialized = true;
  21275. this.info.memory.geometries ++;
  21276. const onDispose = () => {
  21277. this.info.memory.geometries --;
  21278. const index = geometry.index;
  21279. const geometryAttributes = renderObject.getAttributes();
  21280. if ( index !== null ) {
  21281. this.attributes.delete( index );
  21282. }
  21283. for ( const geometryAttribute of geometryAttributes ) {
  21284. this.attributes.delete( geometryAttribute );
  21285. }
  21286. const wireframeAttribute = this.wireframes.get( geometry );
  21287. if ( wireframeAttribute !== undefined ) {
  21288. this.attributes.delete( wireframeAttribute );
  21289. }
  21290. geometry.removeEventListener( 'dispose', onDispose );
  21291. this._geometryDisposeListeners.delete( geometry );
  21292. };
  21293. geometry.addEventListener( 'dispose', onDispose );
  21294. // see #31798 why tracking separate remove listeners is required right now
  21295. // TODO: Re-evaluate how onDispose() is managed in this component
  21296. this._geometryDisposeListeners.set( geometry, onDispose );
  21297. }
  21298. /**
  21299. * Updates the geometry attributes of the given render object.
  21300. *
  21301. * @param {RenderObject} renderObject - The render object.
  21302. */
  21303. updateAttributes( renderObject ) {
  21304. // attributes
  21305. const attributes = renderObject.getAttributes();
  21306. for ( const attribute of attributes ) {
  21307. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  21308. this.updateAttribute( attribute, AttributeType.STORAGE );
  21309. } else {
  21310. this.updateAttribute( attribute, AttributeType.VERTEX );
  21311. }
  21312. }
  21313. // indexes
  21314. const index = this.getIndex( renderObject );
  21315. if ( index !== null ) {
  21316. this.updateAttribute( index, AttributeType.INDEX );
  21317. }
  21318. // indirect
  21319. const indirect = renderObject.geometry.indirect;
  21320. if ( indirect !== null ) {
  21321. this.updateAttribute( indirect, AttributeType.INDIRECT );
  21322. }
  21323. }
  21324. /**
  21325. * Updates the given attribute.
  21326. *
  21327. * @param {BufferAttribute} attribute - The attribute to update.
  21328. * @param {number} type - The attribute type.
  21329. */
  21330. updateAttribute( attribute, type ) {
  21331. const callId = this.info.render.calls;
  21332. if ( ! attribute.isInterleavedBufferAttribute ) {
  21333. if ( this.attributeCall.get( attribute ) !== callId ) {
  21334. this.attributes.update( attribute, type );
  21335. this.attributeCall.set( attribute, callId );
  21336. }
  21337. } else {
  21338. if ( this.attributeCall.get( attribute ) === undefined ) {
  21339. this.attributes.update( attribute, type );
  21340. this.attributeCall.set( attribute, callId );
  21341. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  21342. this.attributes.update( attribute, type );
  21343. this.attributeCall.set( attribute.data, callId );
  21344. this.attributeCall.set( attribute, callId );
  21345. }
  21346. }
  21347. }
  21348. /**
  21349. * Returns the indirect buffer attribute of the given render object.
  21350. *
  21351. * @param {RenderObject} renderObject - The render object.
  21352. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  21353. */
  21354. getIndirect( renderObject ) {
  21355. return renderObject.geometry.indirect;
  21356. }
  21357. /**
  21358. * Returns the index of the given render object's geometry. This is implemented
  21359. * in a method to return a wireframe index if necessary.
  21360. *
  21361. * @param {RenderObject} renderObject - The render object.
  21362. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  21363. */
  21364. getIndex( renderObject ) {
  21365. const { geometry, material } = renderObject;
  21366. let index = geometry.index;
  21367. if ( material.wireframe === true ) {
  21368. const wireframes = this.wireframes;
  21369. let wireframeAttribute = wireframes.get( geometry );
  21370. if ( wireframeAttribute === undefined ) {
  21371. wireframeAttribute = getWireframeIndex( geometry );
  21372. wireframes.set( geometry, wireframeAttribute );
  21373. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  21374. this.attributes.delete( wireframeAttribute );
  21375. wireframeAttribute = getWireframeIndex( geometry );
  21376. wireframes.set( geometry, wireframeAttribute );
  21377. }
  21378. index = wireframeAttribute;
  21379. }
  21380. return index;
  21381. }
  21382. dispose() {
  21383. for ( const [ geometry, onDispose ] of this._geometryDisposeListeners.entries() ) {
  21384. geometry.removeEventListener( 'dispose', onDispose );
  21385. }
  21386. this._geometryDisposeListeners.clear();
  21387. }
  21388. }
  21389. /**
  21390. * This renderer module provides a series of statistical information
  21391. * about the GPU memory and the rendering process. Useful for debugging
  21392. * and monitoring.
  21393. */
  21394. class Info {
  21395. /**
  21396. * Constructs a new info component.
  21397. */
  21398. constructor() {
  21399. /**
  21400. * Whether frame related metrics should automatically
  21401. * be resetted or not. This property should be set to `false`
  21402. * by apps which manage their own animation loop. They must
  21403. * then call `renderer.info.reset()` once per frame manually.
  21404. *
  21405. * @type {boolean}
  21406. * @default true
  21407. */
  21408. this.autoReset = true;
  21409. /**
  21410. * The current frame ID. This ID is managed
  21411. * by `NodeFrame`.
  21412. *
  21413. * @type {number}
  21414. * @readonly
  21415. * @default 0
  21416. */
  21417. this.frame = 0;
  21418. /**
  21419. * The number of render calls since the
  21420. * app has been started.
  21421. *
  21422. * @type {number}
  21423. * @readonly
  21424. * @default 0
  21425. */
  21426. this.calls = 0;
  21427. /**
  21428. * Render related metrics.
  21429. *
  21430. * @type {Object}
  21431. * @readonly
  21432. * @property {number} calls - The number of render calls since the app has been started.
  21433. * @property {number} frameCalls - The number of render calls of the current frame.
  21434. * @property {number} drawCalls - The number of draw calls of the current frame.
  21435. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  21436. * @property {number} points - The number of rendered point primitives of the current frame.
  21437. * @property {number} lines - The number of rendered line primitives of the current frame.
  21438. * @property {number} timestamp - The timestamp of the frame.
  21439. */
  21440. this.render = {
  21441. calls: 0,
  21442. frameCalls: 0,
  21443. drawCalls: 0,
  21444. triangles: 0,
  21445. points: 0,
  21446. lines: 0,
  21447. timestamp: 0,
  21448. };
  21449. /**
  21450. * Compute related metrics.
  21451. *
  21452. * @type {Object}
  21453. * @readonly
  21454. * @property {number} calls - The number of compute calls since the app has been started.
  21455. * @property {number} frameCalls - The number of compute calls of the current frame.
  21456. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  21457. */
  21458. this.compute = {
  21459. calls: 0,
  21460. frameCalls: 0,
  21461. timestamp: 0
  21462. };
  21463. /**
  21464. * Memory related metrics.
  21465. *
  21466. * @type {Object}
  21467. * @readonly
  21468. * @property {number} geometries - The number of active geometries.
  21469. * @property {number} frameCalls - The number of active textures.
  21470. */
  21471. this.memory = {
  21472. geometries: 0,
  21473. textures: 0
  21474. };
  21475. }
  21476. /**
  21477. * This method should be executed per draw call and updates the corresponding metrics.
  21478. *
  21479. * @param {Object3D} object - The 3D object that is going to be rendered.
  21480. * @param {number} count - The vertex or index count.
  21481. * @param {number} instanceCount - The instance count.
  21482. */
  21483. update( object, count, instanceCount ) {
  21484. this.render.drawCalls ++;
  21485. if ( object.isMesh || object.isSprite ) {
  21486. this.render.triangles += instanceCount * ( count / 3 );
  21487. } else if ( object.isPoints ) {
  21488. this.render.points += instanceCount * count;
  21489. } else if ( object.isLineSegments ) {
  21490. this.render.lines += instanceCount * ( count / 2 );
  21491. } else if ( object.isLine ) {
  21492. this.render.lines += instanceCount * ( count - 1 );
  21493. } else {
  21494. error( 'WebGPUInfo: Unknown object type.' );
  21495. }
  21496. }
  21497. /**
  21498. * Resets frame related metrics.
  21499. */
  21500. reset() {
  21501. this.render.drawCalls = 0;
  21502. this.render.frameCalls = 0;
  21503. this.compute.frameCalls = 0;
  21504. this.render.triangles = 0;
  21505. this.render.points = 0;
  21506. this.render.lines = 0;
  21507. }
  21508. /**
  21509. * Performs a complete reset of the object.
  21510. */
  21511. dispose() {
  21512. this.reset();
  21513. this.calls = 0;
  21514. this.render.calls = 0;
  21515. this.compute.calls = 0;
  21516. this.render.timestamp = 0;
  21517. this.compute.timestamp = 0;
  21518. this.memory.geometries = 0;
  21519. this.memory.textures = 0;
  21520. }
  21521. }
  21522. /**
  21523. * Abstract class for representing pipelines.
  21524. *
  21525. * @private
  21526. * @abstract
  21527. */
  21528. class Pipeline {
  21529. /**
  21530. * Constructs a new pipeline.
  21531. *
  21532. * @param {string} cacheKey - The pipeline's cache key.
  21533. */
  21534. constructor( cacheKey ) {
  21535. /**
  21536. * The pipeline's cache key.
  21537. *
  21538. * @type {string}
  21539. */
  21540. this.cacheKey = cacheKey;
  21541. /**
  21542. * How often the pipeline is currently in use.
  21543. *
  21544. * @type {number}
  21545. * @default 0
  21546. */
  21547. this.usedTimes = 0;
  21548. }
  21549. }
  21550. /**
  21551. * Class for representing render pipelines.
  21552. *
  21553. * @private
  21554. * @augments Pipeline
  21555. */
  21556. class RenderPipeline extends Pipeline {
  21557. /**
  21558. * Constructs a new render pipeline.
  21559. *
  21560. * @param {string} cacheKey - The pipeline's cache key.
  21561. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  21562. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  21563. */
  21564. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  21565. super( cacheKey );
  21566. /**
  21567. * The pipeline's vertex shader.
  21568. *
  21569. * @type {ProgrammableStage}
  21570. */
  21571. this.vertexProgram = vertexProgram;
  21572. /**
  21573. * The pipeline's fragment shader.
  21574. *
  21575. * @type {ProgrammableStage}
  21576. */
  21577. this.fragmentProgram = fragmentProgram;
  21578. }
  21579. }
  21580. /**
  21581. * Class for representing compute pipelines.
  21582. *
  21583. * @private
  21584. * @augments Pipeline
  21585. */
  21586. class ComputePipeline extends Pipeline {
  21587. /**
  21588. * Constructs a new render pipeline.
  21589. *
  21590. * @param {string} cacheKey - The pipeline's cache key.
  21591. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  21592. */
  21593. constructor( cacheKey, computeProgram ) {
  21594. super( cacheKey );
  21595. /**
  21596. * The pipeline's compute shader.
  21597. *
  21598. * @type {ProgrammableStage}
  21599. */
  21600. this.computeProgram = computeProgram;
  21601. /**
  21602. * This flag can be used for type testing.
  21603. *
  21604. * @type {boolean}
  21605. * @readonly
  21606. * @default true
  21607. */
  21608. this.isComputePipeline = true;
  21609. }
  21610. }
  21611. let _id$9 = 0;
  21612. /**
  21613. * Class for representing programmable stages which are vertex,
  21614. * fragment or compute shaders. Unlike fixed-function states (like blending),
  21615. * they represent the programmable part of a pipeline.
  21616. *
  21617. * @private
  21618. */
  21619. class ProgrammableStage {
  21620. /**
  21621. * Constructs a new programmable stage.
  21622. *
  21623. * @param {string} code - The shader code.
  21624. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  21625. * @param {string} name - The name of the shader.
  21626. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21627. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21628. */
  21629. constructor( code, stage, name, transforms = null, attributes = null ) {
  21630. /**
  21631. * The id of the programmable stage.
  21632. *
  21633. * @type {number}
  21634. */
  21635. this.id = _id$9 ++;
  21636. /**
  21637. * The shader code.
  21638. *
  21639. * @type {string}
  21640. */
  21641. this.code = code;
  21642. /**
  21643. * The type of stage.
  21644. *
  21645. * @type {string}
  21646. */
  21647. this.stage = stage;
  21648. /**
  21649. * The name of the stage.
  21650. * This is used for debugging purposes.
  21651. *
  21652. * @type {string}
  21653. */
  21654. this.name = name;
  21655. /**
  21656. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21657. *
  21658. * @type {?Array<Object>}
  21659. */
  21660. this.transforms = transforms;
  21661. /**
  21662. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21663. *
  21664. * @type {?Array<Object>}
  21665. */
  21666. this.attributes = attributes;
  21667. /**
  21668. * How often the programmable stage is currently in use.
  21669. *
  21670. * @type {number}
  21671. * @default 0
  21672. */
  21673. this.usedTimes = 0;
  21674. }
  21675. }
  21676. /**
  21677. * This renderer module manages the pipelines of the renderer.
  21678. *
  21679. * @private
  21680. * @augments DataMap
  21681. */
  21682. class Pipelines extends DataMap {
  21683. /**
  21684. * Constructs a new pipeline management component.
  21685. *
  21686. * @param {Backend} backend - The renderer's backend.
  21687. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21688. */
  21689. constructor( backend, nodes ) {
  21690. super();
  21691. /**
  21692. * The renderer's backend.
  21693. *
  21694. * @type {Backend}
  21695. */
  21696. this.backend = backend;
  21697. /**
  21698. * Renderer component for managing nodes related logic.
  21699. *
  21700. * @type {Nodes}
  21701. */
  21702. this.nodes = nodes;
  21703. /**
  21704. * A references to the bindings management component.
  21705. * This reference will be set inside the `Bindings`
  21706. * constructor.
  21707. *
  21708. * @type {?Bindings}
  21709. * @default null
  21710. */
  21711. this.bindings = null;
  21712. /**
  21713. * Internal cache for maintaining pipelines.
  21714. * The key of the map is a cache key, the value the pipeline.
  21715. *
  21716. * @type {Map<string,Pipeline>}
  21717. */
  21718. this.caches = new Map();
  21719. /**
  21720. * This dictionary maintains for each shader stage type (vertex,
  21721. * fragment and compute) the programmable stage objects which
  21722. * represent the actual shader code.
  21723. *
  21724. * @type {Object<string,Map<string, ProgrammableStage>>}
  21725. */
  21726. this.programs = {
  21727. vertex: new Map(),
  21728. fragment: new Map(),
  21729. compute: new Map()
  21730. };
  21731. }
  21732. /**
  21733. * Returns a compute pipeline for the given compute node.
  21734. *
  21735. * @param {Node} computeNode - The compute node.
  21736. * @param {Array<BindGroup>} bindings - The bindings.
  21737. * @return {ComputePipeline} The compute pipeline.
  21738. */
  21739. getForCompute( computeNode, bindings ) {
  21740. const { backend } = this;
  21741. const data = this.get( computeNode );
  21742. if ( this._needsComputeUpdate( computeNode ) ) {
  21743. const previousPipeline = data.pipeline;
  21744. if ( previousPipeline ) {
  21745. previousPipeline.usedTimes --;
  21746. previousPipeline.computeProgram.usedTimes --;
  21747. }
  21748. // get shader
  21749. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  21750. // programmable stage
  21751. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  21752. if ( stageCompute === undefined ) {
  21753. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  21754. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  21755. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  21756. backend.createProgram( stageCompute );
  21757. }
  21758. // determine compute pipeline
  21759. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  21760. let pipeline = this.caches.get( cacheKey );
  21761. if ( pipeline === undefined ) {
  21762. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21763. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  21764. }
  21765. // keep track of all used times
  21766. pipeline.usedTimes ++;
  21767. stageCompute.usedTimes ++;
  21768. //
  21769. data.version = computeNode.version;
  21770. data.pipeline = pipeline;
  21771. }
  21772. return data.pipeline;
  21773. }
  21774. /**
  21775. * Returns a render pipeline for the given render object.
  21776. *
  21777. * @param {RenderObject} renderObject - The render object.
  21778. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21779. * @return {RenderPipeline} The render pipeline.
  21780. */
  21781. getForRender( renderObject, promises = null ) {
  21782. const { backend } = this;
  21783. const data = this.get( renderObject );
  21784. if ( this._needsRenderUpdate( renderObject ) ) {
  21785. const previousPipeline = data.pipeline;
  21786. if ( previousPipeline ) {
  21787. previousPipeline.usedTimes --;
  21788. previousPipeline.vertexProgram.usedTimes --;
  21789. previousPipeline.fragmentProgram.usedTimes --;
  21790. }
  21791. // get shader
  21792. const nodeBuilderState = renderObject.getNodeBuilderState();
  21793. const name = renderObject.material ? renderObject.material.name : '';
  21794. // programmable stages
  21795. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  21796. if ( stageVertex === undefined ) {
  21797. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  21798. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  21799. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  21800. backend.createProgram( stageVertex );
  21801. }
  21802. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  21803. if ( stageFragment === undefined ) {
  21804. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  21805. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  21806. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  21807. backend.createProgram( stageFragment );
  21808. }
  21809. // determine render pipeline
  21810. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21811. let pipeline = this.caches.get( cacheKey );
  21812. if ( pipeline === undefined ) {
  21813. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21814. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  21815. } else {
  21816. renderObject.pipeline = pipeline;
  21817. }
  21818. // keep track of all used times
  21819. pipeline.usedTimes ++;
  21820. stageVertex.usedTimes ++;
  21821. stageFragment.usedTimes ++;
  21822. //
  21823. data.pipeline = pipeline;
  21824. }
  21825. return data.pipeline;
  21826. }
  21827. /**
  21828. * Deletes the pipeline for the given render object.
  21829. *
  21830. * @param {RenderObject} object - The render object.
  21831. * @return {?Object} The deleted dictionary.
  21832. */
  21833. delete( object ) {
  21834. const pipeline = this.get( object ).pipeline;
  21835. if ( pipeline ) {
  21836. // pipeline
  21837. pipeline.usedTimes --;
  21838. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  21839. // programs
  21840. if ( pipeline.isComputePipeline ) {
  21841. pipeline.computeProgram.usedTimes --;
  21842. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  21843. } else {
  21844. pipeline.fragmentProgram.usedTimes --;
  21845. pipeline.vertexProgram.usedTimes --;
  21846. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  21847. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  21848. }
  21849. }
  21850. return super.delete( object );
  21851. }
  21852. /**
  21853. * Frees internal resources.
  21854. */
  21855. dispose() {
  21856. super.dispose();
  21857. this.caches = new Map();
  21858. this.programs = {
  21859. vertex: new Map(),
  21860. fragment: new Map(),
  21861. compute: new Map()
  21862. };
  21863. }
  21864. /**
  21865. * Updates the pipeline for the given render object.
  21866. *
  21867. * @param {RenderObject} renderObject - The render object.
  21868. */
  21869. updateForRender( renderObject ) {
  21870. this.getForRender( renderObject );
  21871. }
  21872. /**
  21873. * Returns a compute pipeline for the given parameters.
  21874. *
  21875. * @private
  21876. * @param {Node} computeNode - The compute node.
  21877. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21878. * @param {string} cacheKey - The cache key.
  21879. * @param {Array<BindGroup>} bindings - The bindings.
  21880. * @return {ComputePipeline} The compute pipeline.
  21881. */
  21882. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  21883. // check for existing pipeline
  21884. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  21885. let pipeline = this.caches.get( cacheKey );
  21886. if ( pipeline === undefined ) {
  21887. pipeline = new ComputePipeline( cacheKey, stageCompute );
  21888. this.caches.set( cacheKey, pipeline );
  21889. this.backend.createComputePipeline( pipeline, bindings );
  21890. }
  21891. return pipeline;
  21892. }
  21893. /**
  21894. * Returns a render pipeline for the given parameters.
  21895. *
  21896. * @private
  21897. * @param {RenderObject} renderObject - The render object.
  21898. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21899. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21900. * @param {string} cacheKey - The cache key.
  21901. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21902. * @return {ComputePipeline} The compute pipeline.
  21903. */
  21904. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  21905. // check for existing pipeline
  21906. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21907. let pipeline = this.caches.get( cacheKey );
  21908. if ( pipeline === undefined ) {
  21909. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  21910. this.caches.set( cacheKey, pipeline );
  21911. renderObject.pipeline = pipeline;
  21912. // The `promises` array is `null` by default and only set to an empty array when
  21913. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  21914. // pending promises that resolve when the render pipelines are ready for rendering.
  21915. this.backend.createRenderPipeline( renderObject, promises );
  21916. }
  21917. return pipeline;
  21918. }
  21919. /**
  21920. * Computes a cache key representing a compute pipeline.
  21921. *
  21922. * @private
  21923. * @param {Node} computeNode - The compute node.
  21924. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21925. * @return {string} The cache key.
  21926. */
  21927. _getComputeCacheKey( computeNode, stageCompute ) {
  21928. return computeNode.id + ',' + stageCompute.id;
  21929. }
  21930. /**
  21931. * Computes a cache key representing a render pipeline.
  21932. *
  21933. * @private
  21934. * @param {RenderObject} renderObject - The render object.
  21935. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21936. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21937. * @return {string} The cache key.
  21938. */
  21939. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  21940. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  21941. }
  21942. /**
  21943. * Releases the given pipeline.
  21944. *
  21945. * @private
  21946. * @param {Pipeline} pipeline - The pipeline to release.
  21947. */
  21948. _releasePipeline( pipeline ) {
  21949. this.caches.delete( pipeline.cacheKey );
  21950. }
  21951. /**
  21952. * Releases the shader program.
  21953. *
  21954. * @private
  21955. * @param {Object} program - The shader program to release.
  21956. */
  21957. _releaseProgram( program ) {
  21958. const code = program.code;
  21959. const stage = program.stage;
  21960. this.programs[ stage ].delete( code );
  21961. }
  21962. /**
  21963. * Returns `true` if the compute pipeline for the given compute node requires an update.
  21964. *
  21965. * @private
  21966. * @param {Node} computeNode - The compute node.
  21967. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  21968. */
  21969. _needsComputeUpdate( computeNode ) {
  21970. const data = this.get( computeNode );
  21971. return data.pipeline === undefined || data.version !== computeNode.version;
  21972. }
  21973. /**
  21974. * Returns `true` if the render pipeline for the given render object requires an update.
  21975. *
  21976. * @private
  21977. * @param {RenderObject} renderObject - The render object.
  21978. * @return {boolean} Whether the render object for the given render object requires an update or not.
  21979. */
  21980. _needsRenderUpdate( renderObject ) {
  21981. const data = this.get( renderObject );
  21982. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  21983. }
  21984. }
  21985. /**
  21986. * This renderer module manages the bindings of the renderer.
  21987. *
  21988. * @private
  21989. * @augments DataMap
  21990. */
  21991. class Bindings extends DataMap {
  21992. /**
  21993. * Constructs a new bindings management component.
  21994. *
  21995. * @param {Backend} backend - The renderer's backend.
  21996. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21997. * @param {Textures} textures - Renderer component for managing textures.
  21998. * @param {Attributes} attributes - Renderer component for managing attributes.
  21999. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  22000. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22001. */
  22002. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  22003. super();
  22004. /**
  22005. * The renderer's backend.
  22006. *
  22007. * @type {Backend}
  22008. */
  22009. this.backend = backend;
  22010. /**
  22011. * Renderer component for managing textures.
  22012. *
  22013. * @type {Textures}
  22014. */
  22015. this.textures = textures;
  22016. /**
  22017. * Renderer component for managing pipelines.
  22018. *
  22019. * @type {Pipelines}
  22020. */
  22021. this.pipelines = pipelines;
  22022. /**
  22023. * Renderer component for managing attributes.
  22024. *
  22025. * @type {Attributes}
  22026. */
  22027. this.attributes = attributes;
  22028. /**
  22029. * Renderer component for managing nodes related logic.
  22030. *
  22031. * @type {Nodes}
  22032. */
  22033. this.nodes = nodes;
  22034. /**
  22035. * Renderer component for managing metrics and monitoring data.
  22036. *
  22037. * @type {Info}
  22038. */
  22039. this.info = info;
  22040. this.pipelines.bindings = this; // assign bindings to pipelines
  22041. }
  22042. /**
  22043. * Returns the bind groups for the given render object.
  22044. *
  22045. * @param {RenderObject} renderObject - The render object.
  22046. * @return {Array<BindGroup>} The bind groups.
  22047. */
  22048. getForRender( renderObject ) {
  22049. const bindings = renderObject.getBindings();
  22050. for ( const bindGroup of bindings ) {
  22051. const groupData = this.get( bindGroup );
  22052. if ( groupData.bindGroup === undefined ) {
  22053. // each object defines an array of bindings (ubos, textures, samplers etc.)
  22054. this._init( bindGroup );
  22055. this.backend.createBindings( bindGroup, bindings, 0 );
  22056. groupData.bindGroup = bindGroup;
  22057. }
  22058. }
  22059. return bindings;
  22060. }
  22061. /**
  22062. * Returns the bind groups for the given compute node.
  22063. *
  22064. * @param {Node} computeNode - The compute node.
  22065. * @return {Array<BindGroup>} The bind groups.
  22066. */
  22067. getForCompute( computeNode ) {
  22068. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22069. for ( const bindGroup of bindings ) {
  22070. const groupData = this.get( bindGroup );
  22071. if ( groupData.bindGroup === undefined ) {
  22072. this._init( bindGroup );
  22073. this.backend.createBindings( bindGroup, bindings, 0 );
  22074. groupData.bindGroup = bindGroup;
  22075. }
  22076. }
  22077. return bindings;
  22078. }
  22079. /**
  22080. * Updates the bindings for the given compute node.
  22081. *
  22082. * @param {Node} computeNode - The compute node.
  22083. */
  22084. updateForCompute( computeNode ) {
  22085. this._updateBindings( this.getForCompute( computeNode ) );
  22086. }
  22087. /**
  22088. * Updates the bindings for the given render object.
  22089. *
  22090. * @param {RenderObject} renderObject - The render object.
  22091. */
  22092. updateForRender( renderObject ) {
  22093. this._updateBindings( this.getForRender( renderObject ) );
  22094. }
  22095. /**
  22096. * Deletes the bindings for the given compute node.
  22097. *
  22098. * @param {Node} computeNode - The compute node.
  22099. */
  22100. deleteForCompute( computeNode ) {
  22101. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22102. for ( const bindGroup of bindings ) {
  22103. this.delete( bindGroup );
  22104. }
  22105. }
  22106. /**
  22107. * Deletes the bindings for the given renderObject node.
  22108. *
  22109. * @param {RenderObject} renderObject - The renderObject.
  22110. */
  22111. deleteForRender( renderObject ) {
  22112. const bindings = renderObject.getBindings();
  22113. for ( const bindGroup of bindings ) {
  22114. this.delete( bindGroup );
  22115. }
  22116. }
  22117. /**
  22118. * Updates the given array of bindings.
  22119. *
  22120. * @param {Array<BindGroup>} bindings - The bind groups.
  22121. */
  22122. _updateBindings( bindings ) {
  22123. for ( const bindGroup of bindings ) {
  22124. this._update( bindGroup, bindings );
  22125. }
  22126. }
  22127. /**
  22128. * Initializes the given bind group.
  22129. *
  22130. * @param {BindGroup} bindGroup - The bind group to initialize.
  22131. */
  22132. _init( bindGroup ) {
  22133. for ( const binding of bindGroup.bindings ) {
  22134. if ( binding.isSampledTexture ) {
  22135. this.textures.updateTexture( binding.texture );
  22136. } else if ( binding.isSampler ) {
  22137. this.textures.updateSampler( binding.texture );
  22138. } else if ( binding.isStorageBuffer ) {
  22139. const attribute = binding.attribute;
  22140. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  22141. this.attributes.update( attribute, attributeType );
  22142. }
  22143. }
  22144. }
  22145. /**
  22146. * Updates the given bind group.
  22147. *
  22148. * @param {BindGroup} bindGroup - The bind group to update.
  22149. * @param {Array<BindGroup>} bindings - The bind groups.
  22150. */
  22151. _update( bindGroup, bindings ) {
  22152. const { backend } = this;
  22153. let needsBindingsUpdate = false;
  22154. let cacheBindings = true;
  22155. let cacheIndex = 0;
  22156. let version = 0;
  22157. // iterate over all bindings and check if buffer updates or a new binding group is required
  22158. for ( const binding of bindGroup.bindings ) {
  22159. const updatedGroup = this.nodes.updateGroup( binding );
  22160. // every uniforms group is a uniform buffer. So if no update is required,
  22161. // we move one with the next binding. Otherwise the next if block will update the group.
  22162. if ( updatedGroup === false ) continue;
  22163. //
  22164. if ( binding.isStorageBuffer ) {
  22165. const attribute = binding.attribute;
  22166. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  22167. this.attributes.update( attribute, attributeType );
  22168. }
  22169. if ( binding.isUniformBuffer ) {
  22170. const updated = binding.update();
  22171. if ( updated ) {
  22172. backend.updateBinding( binding );
  22173. }
  22174. } else if ( binding.isSampledTexture ) {
  22175. const updated = binding.update();
  22176. // get the texture data after the update, to sync the texture reference from node
  22177. const texture = binding.texture;
  22178. const texturesTextureData = this.textures.get( texture );
  22179. if ( updated ) {
  22180. // version: update the texture data or create a new one
  22181. this.textures.updateTexture( texture );
  22182. // generation: update the bindings if a new texture has been created
  22183. if ( binding.generation !== texturesTextureData.generation ) {
  22184. binding.generation = texturesTextureData.generation;
  22185. needsBindingsUpdate = true;
  22186. cacheBindings = false;
  22187. }
  22188. }
  22189. const textureData = backend.get( texture );
  22190. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  22191. cacheBindings = false;
  22192. } else {
  22193. cacheIndex = cacheIndex * 10 + texture.id;
  22194. version += texture.version;
  22195. }
  22196. if ( texture.isStorageTexture === true && texture.mipmapsAutoUpdate === true ) {
  22197. const textureData = this.get( texture );
  22198. if ( binding.store === true ) {
  22199. textureData.needsMipmap = true;
  22200. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  22201. this.backend.generateMipmaps( texture );
  22202. textureData.needsMipmap = false;
  22203. }
  22204. }
  22205. } else if ( binding.isSampler ) {
  22206. const updated = binding.update();
  22207. if ( updated ) {
  22208. const samplerKey = this.textures.updateSampler( binding.texture );
  22209. if ( binding.samplerKey !== samplerKey ) {
  22210. binding.samplerKey = samplerKey;
  22211. needsBindingsUpdate = true;
  22212. cacheBindings = false;
  22213. }
  22214. }
  22215. }
  22216. }
  22217. if ( needsBindingsUpdate === true ) {
  22218. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  22219. }
  22220. }
  22221. }
  22222. /**
  22223. * Default sorting function for opaque render items.
  22224. *
  22225. * @private
  22226. * @function
  22227. * @param {Object} a - The first render item.
  22228. * @param {Object} b - The second render item.
  22229. * @return {number} A numeric value which defines the sort order.
  22230. */
  22231. function painterSortStable( a, b ) {
  22232. if ( a.groupOrder !== b.groupOrder ) {
  22233. return a.groupOrder - b.groupOrder;
  22234. } else if ( a.renderOrder !== b.renderOrder ) {
  22235. return a.renderOrder - b.renderOrder;
  22236. } else if ( a.z !== b.z ) {
  22237. return a.z - b.z;
  22238. } else {
  22239. return a.id - b.id;
  22240. }
  22241. }
  22242. /**
  22243. * Default sorting function for transparent render items.
  22244. *
  22245. * @private
  22246. * @function
  22247. * @param {Object} a - The first render item.
  22248. * @param {Object} b - The second render item.
  22249. * @return {number} A numeric value which defines the sort order.
  22250. */
  22251. function reversePainterSortStable( a, b ) {
  22252. if ( a.groupOrder !== b.groupOrder ) {
  22253. return a.groupOrder - b.groupOrder;
  22254. } else if ( a.renderOrder !== b.renderOrder ) {
  22255. return a.renderOrder - b.renderOrder;
  22256. } else if ( a.z !== b.z ) {
  22257. return b.z - a.z;
  22258. } else {
  22259. return a.id - b.id;
  22260. }
  22261. }
  22262. /**
  22263. * Returns `true` if the given transparent material requires a double pass.
  22264. *
  22265. * @private
  22266. * @function
  22267. * @param {Material} material - The transparent material.
  22268. * @return {boolean} Whether the given material requires a double pass or not.
  22269. */
  22270. function needsDoublePass( material ) {
  22271. const hasTransmission = material.transmission > 0 || ( material.transmissionNode && material.transmissionNode.isNode );
  22272. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  22273. }
  22274. /**
  22275. * When the renderer analyzes the scene at the beginning of a render call,
  22276. * it stores 3D object for further processing in render lists. Depending on the
  22277. * properties of a 3D objects (like their transformation or material state), the
  22278. * objects are maintained in ordered lists for the actual rendering.
  22279. *
  22280. * Render lists are unique per scene and camera combination.
  22281. *
  22282. * @private
  22283. * @augments Pipeline
  22284. */
  22285. class RenderList {
  22286. /**
  22287. * Constructs a render list.
  22288. *
  22289. * @param {Lighting} lighting - The lighting management component.
  22290. * @param {Scene} scene - The scene.
  22291. * @param {Camera} camera - The camera the scene is rendered with.
  22292. */
  22293. constructor( lighting, scene, camera ) {
  22294. /**
  22295. * 3D objects are transformed into render items and stored in this array.
  22296. *
  22297. * @type {Array<Object>}
  22298. */
  22299. this.renderItems = [];
  22300. /**
  22301. * The current render items index.
  22302. *
  22303. * @type {number}
  22304. * @default 0
  22305. */
  22306. this.renderItemsIndex = 0;
  22307. /**
  22308. * A list with opaque render items.
  22309. *
  22310. * @type {Array<Object>}
  22311. */
  22312. this.opaque = [];
  22313. /**
  22314. * A list with transparent render items which require
  22315. * double pass rendering (e.g. transmissive objects).
  22316. *
  22317. * @type {Array<Object>}
  22318. */
  22319. this.transparentDoublePass = [];
  22320. /**
  22321. * A list with transparent render items.
  22322. *
  22323. * @type {Array<Object>}
  22324. */
  22325. this.transparent = [];
  22326. /**
  22327. * A list with transparent render bundle data.
  22328. *
  22329. * @type {Array<Object>}
  22330. */
  22331. this.bundles = [];
  22332. /**
  22333. * The render list's lights node. This node is later
  22334. * relevant for the actual analytical light nodes which
  22335. * compute the scene's lighting in the shader.
  22336. *
  22337. * @type {LightsNode}
  22338. */
  22339. this.lightsNode = lighting.getNode( scene, camera );
  22340. /**
  22341. * The scene's lights stored in an array. This array
  22342. * is used to setup the lights node.
  22343. *
  22344. * @type {Array<Light>}
  22345. */
  22346. this.lightsArray = [];
  22347. /**
  22348. * The scene.
  22349. *
  22350. * @type {Scene}
  22351. */
  22352. this.scene = scene;
  22353. /**
  22354. * The camera the scene is rendered with.
  22355. *
  22356. * @type {Camera}
  22357. */
  22358. this.camera = camera;
  22359. /**
  22360. * How many objects perform occlusion query tests.
  22361. *
  22362. * @type {number}
  22363. * @default 0
  22364. */
  22365. this.occlusionQueryCount = 0;
  22366. }
  22367. /**
  22368. * This method is called right at the beginning of a render call
  22369. * before the scene is analyzed. It prepares the internal data
  22370. * structures for the upcoming render lists generation.
  22371. *
  22372. * @return {RenderList} A reference to this render list.
  22373. */
  22374. begin() {
  22375. this.renderItemsIndex = 0;
  22376. this.opaque.length = 0;
  22377. this.transparentDoublePass.length = 0;
  22378. this.transparent.length = 0;
  22379. this.bundles.length = 0;
  22380. this.lightsArray.length = 0;
  22381. this.occlusionQueryCount = 0;
  22382. return this;
  22383. }
  22384. /**
  22385. * Returns a render item for the giving render item state. The state is defined
  22386. * by a series of object-related parameters.
  22387. *
  22388. * The method avoids object creation by holding render items and reusing them in
  22389. * subsequent render calls (just with different property values).
  22390. *
  22391. * @param {Object3D} object - The 3D object.
  22392. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22393. * @param {Material} material - The 3D object's material.
  22394. * @param {number} groupOrder - The current group order.
  22395. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22396. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22397. * @param {ClippingContext} clippingContext - The current clipping context.
  22398. * @return {Object} The render item.
  22399. */
  22400. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22401. let renderItem = this.renderItems[ this.renderItemsIndex ];
  22402. if ( renderItem === undefined ) {
  22403. renderItem = {
  22404. id: object.id,
  22405. object: object,
  22406. geometry: geometry,
  22407. material: material,
  22408. groupOrder: groupOrder,
  22409. renderOrder: object.renderOrder,
  22410. z: z,
  22411. group: group,
  22412. clippingContext: clippingContext
  22413. };
  22414. this.renderItems[ this.renderItemsIndex ] = renderItem;
  22415. } else {
  22416. renderItem.id = object.id;
  22417. renderItem.object = object;
  22418. renderItem.geometry = geometry;
  22419. renderItem.material = material;
  22420. renderItem.groupOrder = groupOrder;
  22421. renderItem.renderOrder = object.renderOrder;
  22422. renderItem.z = z;
  22423. renderItem.group = group;
  22424. renderItem.clippingContext = clippingContext;
  22425. }
  22426. this.renderItemsIndex ++;
  22427. return renderItem;
  22428. }
  22429. /**
  22430. * Pushes the given object as a render item to the internal render lists.
  22431. * The selected lists depend on the object properties.
  22432. *
  22433. * @param {Object3D} object - The 3D object.
  22434. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22435. * @param {Material} material - The 3D object's material.
  22436. * @param {number} groupOrder - The current group order.
  22437. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22438. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22439. * @param {ClippingContext} clippingContext - The current clipping context.
  22440. */
  22441. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22442. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  22443. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  22444. if ( material.transparent === true || material.transmission > 0 ||
  22445. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  22446. ( material.backdropNode && material.backdropNode.isNode ) ) {
  22447. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  22448. this.transparent.push( renderItem );
  22449. } else {
  22450. this.opaque.push( renderItem );
  22451. }
  22452. }
  22453. /**
  22454. * Inserts the given object as a render item at the start of the internal render lists.
  22455. * The selected lists depend on the object properties.
  22456. *
  22457. * @param {Object3D} object - The 3D object.
  22458. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22459. * @param {Material} material - The 3D object's material.
  22460. * @param {number} groupOrder - The current group order.
  22461. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22462. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22463. * @param {ClippingContext} clippingContext - The current clipping context.
  22464. */
  22465. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22466. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  22467. if ( material.transparent === true || material.transmission > 0 ||
  22468. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  22469. ( material.backdropNode && material.backdropNode.isNode ) ) {
  22470. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  22471. this.transparent.unshift( renderItem );
  22472. } else {
  22473. this.opaque.unshift( renderItem );
  22474. }
  22475. }
  22476. /**
  22477. * Pushes render bundle group data into the render list.
  22478. *
  22479. * @param {Object} group - Bundle group data.
  22480. */
  22481. pushBundle( group ) {
  22482. this.bundles.push( group );
  22483. }
  22484. /**
  22485. * Pushes a light into the render list.
  22486. *
  22487. * @param {Light} light - The light.
  22488. */
  22489. pushLight( light ) {
  22490. this.lightsArray.push( light );
  22491. }
  22492. /**
  22493. * Sorts the internal render lists.
  22494. *
  22495. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  22496. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  22497. */
  22498. sort( customOpaqueSort, customTransparentSort ) {
  22499. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  22500. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  22501. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  22502. }
  22503. /**
  22504. * This method performs finalizing tasks right after the render lists
  22505. * have been generated.
  22506. */
  22507. finish() {
  22508. // update lights
  22509. this.lightsNode.setLights( this.lightsArray );
  22510. // Clear references from inactive renderItems in the list
  22511. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  22512. const renderItem = this.renderItems[ i ];
  22513. if ( renderItem.id === null ) break;
  22514. renderItem.id = null;
  22515. renderItem.object = null;
  22516. renderItem.geometry = null;
  22517. renderItem.material = null;
  22518. renderItem.groupOrder = null;
  22519. renderItem.renderOrder = null;
  22520. renderItem.z = null;
  22521. renderItem.group = null;
  22522. renderItem.clippingContext = null;
  22523. }
  22524. }
  22525. }
  22526. const _chainKeys$4 = [];
  22527. /**
  22528. * This renderer module manages the render lists which are unique
  22529. * per scene and camera combination.
  22530. *
  22531. * @private
  22532. */
  22533. class RenderLists {
  22534. /**
  22535. * Constructs a render lists management component.
  22536. *
  22537. * @param {Lighting} lighting - The lighting management component.
  22538. */
  22539. constructor( lighting ) {
  22540. /**
  22541. * The lighting management component.
  22542. *
  22543. * @type {Lighting}
  22544. */
  22545. this.lighting = lighting;
  22546. /**
  22547. * The internal chain map which holds the render lists.
  22548. *
  22549. * @type {ChainMap}
  22550. */
  22551. this.lists = new ChainMap();
  22552. }
  22553. /**
  22554. * Returns a render list for the given scene and camera.
  22555. *
  22556. * @param {Scene} scene - The scene.
  22557. * @param {Camera} camera - The camera.
  22558. * @return {RenderList} The render list.
  22559. */
  22560. get( scene, camera ) {
  22561. const lists = this.lists;
  22562. _chainKeys$4[ 0 ] = scene;
  22563. _chainKeys$4[ 1 ] = camera;
  22564. let list = lists.get( _chainKeys$4 );
  22565. if ( list === undefined ) {
  22566. list = new RenderList( this.lighting, scene, camera );
  22567. lists.set( _chainKeys$4, list );
  22568. }
  22569. _chainKeys$4.length = 0;
  22570. return list;
  22571. }
  22572. /**
  22573. * Frees all internal resources.
  22574. */
  22575. dispose() {
  22576. this.lists = new ChainMap();
  22577. }
  22578. }
  22579. let _id$8 = 0;
  22580. /**
  22581. * Any render or compute command is executed in a specific context that defines
  22582. * the state of the renderer and its backend. Typical examples for such context
  22583. * data are the current clear values or data from the active framebuffer. This
  22584. * module is used to represent these contexts as objects.
  22585. *
  22586. * @private
  22587. */
  22588. class RenderContext {
  22589. /**
  22590. * Constructs a new render context.
  22591. */
  22592. constructor() {
  22593. /**
  22594. * The context's ID.
  22595. *
  22596. * @type {number}
  22597. */
  22598. this.id = _id$8 ++;
  22599. /**
  22600. * Whether the current active framebuffer has a color attachment.
  22601. *
  22602. * @type {boolean}
  22603. * @default true
  22604. */
  22605. this.color = true;
  22606. /**
  22607. * Whether the color attachment should be cleared or not.
  22608. *
  22609. * @type {boolean}
  22610. * @default true
  22611. */
  22612. this.clearColor = true;
  22613. /**
  22614. * The clear color value.
  22615. *
  22616. * @type {Object}
  22617. * @default true
  22618. */
  22619. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  22620. /**
  22621. * Whether the current active framebuffer has a depth attachment.
  22622. *
  22623. * @type {boolean}
  22624. * @default true
  22625. */
  22626. this.depth = true;
  22627. /**
  22628. * Whether the depth attachment should be cleared or not.
  22629. *
  22630. * @type {boolean}
  22631. * @default true
  22632. */
  22633. this.clearDepth = true;
  22634. /**
  22635. * The clear depth value.
  22636. *
  22637. * @type {number}
  22638. * @default 1
  22639. */
  22640. this.clearDepthValue = 1;
  22641. /**
  22642. * Whether the current active framebuffer has a stencil attachment.
  22643. *
  22644. * @type {boolean}
  22645. * @default false
  22646. */
  22647. this.stencil = false;
  22648. /**
  22649. * Whether the stencil attachment should be cleared or not.
  22650. *
  22651. * @type {boolean}
  22652. * @default true
  22653. */
  22654. this.clearStencil = true;
  22655. /**
  22656. * The clear stencil value.
  22657. *
  22658. * @type {number}
  22659. * @default 1
  22660. */
  22661. this.clearStencilValue = 1;
  22662. /**
  22663. * By default the viewport encloses the entire framebuffer If a smaller
  22664. * viewport is manually defined, this property is to `true` by the renderer.
  22665. *
  22666. * @type {boolean}
  22667. * @default false
  22668. */
  22669. this.viewport = false;
  22670. /**
  22671. * The viewport value. This value is in physical pixels meaning it incorporates
  22672. * the renderer's pixel ratio. The viewport property of render targets or
  22673. * the renderer is in logical pixels.
  22674. *
  22675. * @type {Vector4}
  22676. */
  22677. this.viewportValue = new Vector4();
  22678. /**
  22679. * When the scissor test is active and scissor rectangle smaller than the
  22680. * framebuffers dimensions, this property is to `true` by the renderer.
  22681. *
  22682. * @type {boolean}
  22683. * @default false
  22684. */
  22685. this.scissor = false;
  22686. /**
  22687. * The scissor rectangle.
  22688. *
  22689. * @type {Vector4}
  22690. */
  22691. this.scissorValue = new Vector4();
  22692. /**
  22693. * The active render target.
  22694. *
  22695. * @type {?RenderTarget}
  22696. * @default null
  22697. */
  22698. this.renderTarget = null;
  22699. /**
  22700. * The textures of the active render target.
  22701. * `null` when no render target is set.
  22702. *
  22703. * @type {?Array<Texture>}
  22704. * @default null
  22705. */
  22706. this.textures = null;
  22707. /**
  22708. * The depth texture of the active render target.
  22709. * `null` when no render target is set.
  22710. *
  22711. * @type {?DepthTexture}
  22712. * @default null
  22713. */
  22714. this.depthTexture = null;
  22715. /**
  22716. * The active cube face.
  22717. *
  22718. * @type {number}
  22719. * @default 0
  22720. */
  22721. this.activeCubeFace = 0;
  22722. /**
  22723. * The active mipmap level.
  22724. *
  22725. * @type {number}
  22726. * @default 0
  22727. */
  22728. this.activeMipmapLevel = 0;
  22729. /**
  22730. * The number of MSAA samples. This value is always `1` when
  22731. * MSAA isn't used.
  22732. *
  22733. * @type {number}
  22734. * @default 1
  22735. */
  22736. this.sampleCount = 1;
  22737. /**
  22738. * The active render target's width in physical pixels.
  22739. *
  22740. * @type {number}
  22741. * @default 0
  22742. */
  22743. this.width = 0;
  22744. /**
  22745. * The active render target's height in physical pixels.
  22746. *
  22747. * @type {number}
  22748. * @default 0
  22749. */
  22750. this.height = 0;
  22751. /**
  22752. * The occlusion query count.
  22753. *
  22754. * @type {number}
  22755. * @default 0
  22756. */
  22757. this.occlusionQueryCount = 0;
  22758. /**
  22759. * The current clipping context.
  22760. *
  22761. * @type {?ClippingContext}
  22762. * @default null
  22763. */
  22764. this.clippingContext = null;
  22765. /**
  22766. * This flag can be used for type testing.
  22767. *
  22768. * @type {boolean}
  22769. * @readonly
  22770. * @default true
  22771. */
  22772. this.isRenderContext = true;
  22773. }
  22774. /**
  22775. * Returns the cache key of this render context.
  22776. *
  22777. * @return {number} The cache key.
  22778. */
  22779. getCacheKey() {
  22780. return getCacheKey( this );
  22781. }
  22782. }
  22783. /**
  22784. * Computes a cache key for the given render context. This key
  22785. * should identify the render target state so it is possible to
  22786. * configure the correct attachments in the respective backend.
  22787. *
  22788. * @param {RenderContext} renderContext - The render context.
  22789. * @return {number} The cache key.
  22790. */
  22791. function getCacheKey( renderContext ) {
  22792. const { textures, activeCubeFace, activeMipmapLevel } = renderContext;
  22793. const values = [ activeCubeFace, activeMipmapLevel ];
  22794. for ( const texture of textures ) {
  22795. values.push( texture.id );
  22796. }
  22797. return hashArray( values );
  22798. }
  22799. const _chainKeys$3 = [];
  22800. const _defaultScene = /*@__PURE__*/ new Scene();
  22801. const _defaultCamera = /*@__PURE__*/ new Camera();
  22802. /**
  22803. * This module manages the render contexts of the renderer.
  22804. *
  22805. * @private
  22806. */
  22807. class RenderContexts {
  22808. /**
  22809. * Constructs a new render context management component.
  22810. */
  22811. constructor() {
  22812. /**
  22813. * A dictionary that manages render contexts in chain maps
  22814. * for each attachment state.
  22815. *
  22816. * @type {Object<string,ChainMap>}
  22817. */
  22818. this.chainMaps = {};
  22819. }
  22820. /**
  22821. * Returns a render context for the given scene, camera and render target.
  22822. *
  22823. * @param {Scene} scene - The scene.
  22824. * @param {Camera} camera - The camera that is used to render the scene.
  22825. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22826. * @param {?MRT} [mrt=null] - The active multiple render target.
  22827. * @return {RenderContext} The render context.
  22828. */
  22829. get( scene, camera, renderTarget = null, mrt = null ) {
  22830. let index = 0;
  22831. if ( mrt !== null ) {
  22832. // TODO: Improve ChainMap so that it only matches submaps corresponding to the key lengths.
  22833. // For we use: if ( mrt !== null ) _chainKeys[ 2 ] = mrt;
  22834. _chainKeys$3[ index ++ ] = mrt;
  22835. }
  22836. _chainKeys$3[ index ++ ] = scene;
  22837. _chainKeys$3[ index ++ ] = camera;
  22838. let attachmentState;
  22839. if ( renderTarget === null ) {
  22840. attachmentState = 'default';
  22841. } else {
  22842. const format = renderTarget.texture.format;
  22843. const count = renderTarget.textures.length;
  22844. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  22845. }
  22846. const chainMap = this._getChainMap( attachmentState );
  22847. let renderState = chainMap.get( _chainKeys$3 );
  22848. if ( renderState === undefined ) {
  22849. renderState = new RenderContext();
  22850. chainMap.set( _chainKeys$3, renderState );
  22851. }
  22852. _chainKeys$3.length = 0;
  22853. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22854. return renderState;
  22855. }
  22856. /**
  22857. * Returns a render context intended for clear operations.
  22858. *
  22859. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22860. * @return {RenderContext} The render context.
  22861. */
  22862. getForClear( renderTarget = null ) {
  22863. return this.get( _defaultScene, _defaultCamera, renderTarget );
  22864. }
  22865. /**
  22866. * Returns a chain map for the given attachment state.
  22867. *
  22868. * @private
  22869. * @param {string} attachmentState - The attachment state.
  22870. * @return {ChainMap} The chain map.
  22871. */
  22872. _getChainMap( attachmentState ) {
  22873. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  22874. }
  22875. /**
  22876. * Frees internal resources.
  22877. */
  22878. dispose() {
  22879. this.chainMaps = {};
  22880. }
  22881. }
  22882. const _size$3 = /*@__PURE__*/ new Vector3();
  22883. /**
  22884. * This module manages the textures of the renderer.
  22885. *
  22886. * @private
  22887. * @augments DataMap
  22888. */
  22889. class Textures extends DataMap {
  22890. /**
  22891. * Constructs a new texture management component.
  22892. *
  22893. * @param {Renderer} renderer - The renderer.
  22894. * @param {Backend} backend - The renderer's backend.
  22895. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22896. */
  22897. constructor( renderer, backend, info ) {
  22898. super();
  22899. /**
  22900. * The renderer.
  22901. *
  22902. * @type {Renderer}
  22903. */
  22904. this.renderer = renderer;
  22905. /**
  22906. * The backend.
  22907. *
  22908. * @type {Backend}
  22909. */
  22910. this.backend = backend;
  22911. /**
  22912. * Renderer component for managing metrics and monitoring data.
  22913. *
  22914. * @type {Info}
  22915. */
  22916. this.info = info;
  22917. }
  22918. /**
  22919. * Updates the given render target. Based on the given render target configuration,
  22920. * it updates the texture states representing the attachments of the framebuffer.
  22921. *
  22922. * @param {RenderTarget} renderTarget - The render target to update.
  22923. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  22924. */
  22925. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  22926. const renderTargetData = this.get( renderTarget );
  22927. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22928. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  22929. const textures = renderTarget.textures;
  22930. const size = this.getSize( textures[ 0 ] );
  22931. const mipWidth = size.width >> activeMipmapLevel;
  22932. const mipHeight = size.height >> activeMipmapLevel;
  22933. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  22934. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  22935. let textureNeedsUpdate = false;
  22936. if ( depthTexture === undefined && useDepthTexture ) {
  22937. depthTexture = new DepthTexture();
  22938. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  22939. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  22940. depthTexture.image.width = mipWidth;
  22941. depthTexture.image.height = mipHeight;
  22942. depthTexture.image.depth = size.depth;
  22943. depthTexture.renderTarget = renderTarget;
  22944. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  22945. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  22946. }
  22947. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  22948. textureNeedsUpdate = true;
  22949. if ( depthTexture ) {
  22950. depthTexture.needsUpdate = true;
  22951. depthTexture.image.width = mipWidth;
  22952. depthTexture.image.height = mipHeight;
  22953. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  22954. }
  22955. }
  22956. renderTargetData.width = size.width;
  22957. renderTargetData.height = size.height;
  22958. renderTargetData.textures = textures;
  22959. renderTargetData.depthTexture = depthTexture || null;
  22960. renderTargetData.depth = renderTarget.depthBuffer;
  22961. renderTargetData.stencil = renderTarget.stencilBuffer;
  22962. renderTargetData.renderTarget = renderTarget;
  22963. if ( renderTargetData.sampleCount !== sampleCount ) {
  22964. textureNeedsUpdate = true;
  22965. if ( depthTexture ) {
  22966. depthTexture.needsUpdate = true;
  22967. }
  22968. renderTargetData.sampleCount = sampleCount;
  22969. }
  22970. //
  22971. const options = { sampleCount };
  22972. // XR render targets require no texture updates
  22973. if ( renderTarget.isXRRenderTarget !== true ) {
  22974. for ( let i = 0; i < textures.length; i ++ ) {
  22975. const texture = textures[ i ];
  22976. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  22977. this.updateTexture( texture, options );
  22978. }
  22979. if ( depthTexture ) {
  22980. this.updateTexture( depthTexture, options );
  22981. }
  22982. }
  22983. // dispose handler
  22984. if ( renderTargetData.initialized !== true ) {
  22985. renderTargetData.initialized = true;
  22986. // dispose
  22987. renderTargetData.onDispose = () => {
  22988. this._destroyRenderTarget( renderTarget );
  22989. };
  22990. renderTarget.addEventListener( 'dispose', renderTargetData.onDispose );
  22991. }
  22992. }
  22993. /**
  22994. * Updates the given texture. Depending on the texture state, this method
  22995. * triggers the upload of texture data to the GPU memory. If the texture data are
  22996. * not yet ready for the upload, it uses default texture data for as a placeholder.
  22997. *
  22998. * @param {Texture} texture - The texture to update.
  22999. * @param {Object} [options={}] - The options.
  23000. */
  23001. updateTexture( texture, options = {} ) {
  23002. const textureData = this.get( texture );
  23003. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  23004. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  23005. const backend = this.backend;
  23006. if ( isRenderTarget && textureData.initialized === true ) {
  23007. // it's an update
  23008. backend.destroyTexture( texture );
  23009. }
  23010. //
  23011. if ( texture.isFramebufferTexture ) {
  23012. const renderTarget = this.renderer.getRenderTarget();
  23013. if ( renderTarget ) {
  23014. texture.type = renderTarget.texture.type;
  23015. } else {
  23016. texture.type = UnsignedByteType;
  23017. }
  23018. }
  23019. //
  23020. const { width, height, depth } = this.getSize( texture );
  23021. options.width = width;
  23022. options.height = height;
  23023. options.depth = depth;
  23024. options.needsMipmaps = this.needsMipmaps( texture );
  23025. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  23026. // TODO: Uniformly handle mipmap definitions
  23027. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  23028. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  23029. if ( texture.isCubeTexture && texture.mipmaps.length > 0 ) options.levels ++;
  23030. //
  23031. if ( isRenderTarget || texture.isStorageTexture === true || texture.isExternalTexture === true ) {
  23032. backend.createTexture( texture, options );
  23033. textureData.generation = texture.version;
  23034. } else {
  23035. if ( texture.version > 0 ) {
  23036. const image = texture.image;
  23037. if ( image === undefined ) {
  23038. warn( 'Renderer: Texture marked for update but image is undefined.' );
  23039. } else if ( image.complete === false ) {
  23040. warn( 'Renderer: Texture marked for update but image is incomplete.' );
  23041. } else {
  23042. if ( texture.images ) {
  23043. const images = [];
  23044. for ( const image of texture.images ) {
  23045. images.push( image );
  23046. }
  23047. options.images = images;
  23048. } else {
  23049. options.image = image;
  23050. }
  23051. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  23052. backend.createTexture( texture, options );
  23053. textureData.isDefaultTexture = false;
  23054. textureData.generation = texture.version;
  23055. }
  23056. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  23057. const skipAutoGeneration = texture.isStorageTexture === true && texture.mipmapsAutoUpdate === false;
  23058. if ( options.needsMipmaps && texture.mipmaps.length === 0 && ! skipAutoGeneration ) {
  23059. backend.generateMipmaps( texture );
  23060. }
  23061. if ( texture.onUpdate ) texture.onUpdate( texture );
  23062. }
  23063. } else {
  23064. // async update
  23065. backend.createDefaultTexture( texture );
  23066. textureData.isDefaultTexture = true;
  23067. textureData.generation = texture.version;
  23068. }
  23069. }
  23070. // dispose handler
  23071. if ( textureData.initialized !== true ) {
  23072. textureData.initialized = true;
  23073. textureData.generation = texture.version;
  23074. //
  23075. this.info.memory.textures ++;
  23076. //
  23077. if ( texture.isVideoTexture && ColorManagement.getTransfer( texture.colorSpace ) !== SRGBTransfer ) {
  23078. warn( 'WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.' );
  23079. }
  23080. // dispose
  23081. textureData.onDispose = () => {
  23082. this._destroyTexture( texture );
  23083. };
  23084. texture.addEventListener( 'dispose', textureData.onDispose );
  23085. }
  23086. //
  23087. textureData.version = texture.version;
  23088. }
  23089. /**
  23090. * Updates the sampler for the given texture. This method has no effect
  23091. * for the WebGL backend since it has no concept of samplers. Texture
  23092. * parameters are configured with the `texParameter()` command for each
  23093. * texture.
  23094. *
  23095. * In WebGPU, samplers are objects like textures and it's possible to share
  23096. * them when the texture parameters match.
  23097. *
  23098. * @param {Texture} texture - The texture to update the sampler for.
  23099. * @return {string} The current sampler key.
  23100. */
  23101. updateSampler( texture ) {
  23102. return this.backend.updateSampler( texture );
  23103. }
  23104. /**
  23105. * Computes the size of the given texture and writes the result
  23106. * into the target vector. This vector is also returned by the
  23107. * method.
  23108. *
  23109. * If no texture data are available for the compute yet, the method
  23110. * returns default size values.
  23111. *
  23112. * @param {Texture} texture - The texture to compute the size for.
  23113. * @param {Vector3} target - The target vector.
  23114. * @return {Vector3} The target vector.
  23115. */
  23116. getSize( texture, target = _size$3 ) {
  23117. let image = texture.images ? texture.images[ 0 ] : texture.image;
  23118. if ( image ) {
  23119. if ( image.image !== undefined ) image = image.image;
  23120. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( image instanceof HTMLVideoElement ) ) {
  23121. target.width = image.videoWidth || 1;
  23122. target.height = image.videoHeight || 1;
  23123. target.depth = 1;
  23124. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( image instanceof VideoFrame ) ) {
  23125. target.width = image.displayWidth || 1;
  23126. target.height = image.displayHeight || 1;
  23127. target.depth = 1;
  23128. } else {
  23129. target.width = image.width || 1;
  23130. target.height = image.height || 1;
  23131. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  23132. }
  23133. } else {
  23134. target.width = target.height = target.depth = 1;
  23135. }
  23136. return target;
  23137. }
  23138. /**
  23139. * Computes the number of mipmap levels for the given texture.
  23140. *
  23141. * @param {Texture} texture - The texture.
  23142. * @param {number} width - The texture's width.
  23143. * @param {number} height - The texture's height.
  23144. * @return {number} The number of mipmap levels.
  23145. */
  23146. getMipLevels( texture, width, height ) {
  23147. let mipLevelCount;
  23148. if ( texture.mipmaps.length > 0 ) {
  23149. mipLevelCount = texture.mipmaps.length;
  23150. } else {
  23151. if ( texture.isCompressedTexture === true ) {
  23152. // it is not possible to compute mipmaps for compressed textures. So
  23153. // when no mipmaps are defined in "texture.mipmaps", force a texture
  23154. // level of 1
  23155. mipLevelCount = 1;
  23156. } else {
  23157. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  23158. }
  23159. }
  23160. return mipLevelCount;
  23161. }
  23162. /**
  23163. * Returns `true` if the given texture makes use of mipmapping.
  23164. *
  23165. * @param {Texture} texture - The texture.
  23166. * @return {boolean} Whether mipmaps are required or not.
  23167. */
  23168. needsMipmaps( texture ) {
  23169. return texture.generateMipmaps === true || texture.mipmaps.length > 0;
  23170. }
  23171. /**
  23172. * Frees internal resources when the given render target isn't
  23173. * required anymore.
  23174. *
  23175. * @param {RenderTarget} renderTarget - The render target to destroy.
  23176. */
  23177. _destroyRenderTarget( renderTarget ) {
  23178. if ( this.has( renderTarget ) === true ) {
  23179. const renderTargetData = this.get( renderTarget );
  23180. const textures = renderTargetData.textures;
  23181. const depthTexture = renderTargetData.depthTexture;
  23182. //
  23183. renderTarget.removeEventListener( 'dispose', renderTargetData.onDispose );
  23184. //
  23185. for ( let i = 0; i < textures.length; i ++ ) {
  23186. this._destroyTexture( textures[ i ] );
  23187. }
  23188. if ( depthTexture ) {
  23189. this._destroyTexture( depthTexture );
  23190. }
  23191. this.delete( renderTarget );
  23192. this.backend.delete( renderTarget );
  23193. }
  23194. }
  23195. /**
  23196. * Frees internal resource when the given texture isn't
  23197. * required anymore.
  23198. *
  23199. * @param {Texture} texture - The texture to destroy.
  23200. */
  23201. _destroyTexture( texture ) {
  23202. if ( this.has( texture ) === true ) {
  23203. const textureData = this.get( texture );
  23204. //
  23205. texture.removeEventListener( 'dispose', textureData.onDispose );
  23206. // if a texture is not ready for use, it falls back to a default texture so it's possible
  23207. // to use it for rendering. If a texture in this state is disposed, it's important to
  23208. // not destroy/delete the underlying GPU texture object since it is cached and shared with
  23209. // other textures.
  23210. const isDefaultTexture = textureData.isDefaultTexture;
  23211. this.backend.destroyTexture( texture, isDefaultTexture );
  23212. this.delete( texture );
  23213. this.info.memory.textures --;
  23214. }
  23215. }
  23216. }
  23217. /**
  23218. * A four-component version of {@link Color} which is internally
  23219. * used by the renderer to represents clear color with alpha as
  23220. * one object.
  23221. *
  23222. * @private
  23223. * @augments Color
  23224. */
  23225. class Color4 extends Color {
  23226. /**
  23227. * Constructs a new four-component color.
  23228. * You can also pass a single THREE.Color, hex or
  23229. * string argument to this constructor.
  23230. *
  23231. * @param {number|string} [r=1] - The red value.
  23232. * @param {number} [g=1] - The green value.
  23233. * @param {number} [b=1] - The blue value.
  23234. * @param {number} [a=1] - The alpha value.
  23235. */
  23236. constructor( r, g, b, a = 1 ) {
  23237. super( r, g, b );
  23238. this.a = a;
  23239. }
  23240. /**
  23241. * Overwrites the default to honor alpha.
  23242. * You can also pass a single THREE.Color, hex or
  23243. * string argument to this method.
  23244. *
  23245. * @param {number|string|Color} r - The red value.
  23246. * @param {number} [g] - The green value.
  23247. * @param {number} [b] - The blue value.
  23248. * @param {number} [a=1] - The alpha value.
  23249. * @return {Color4} A reference to this object.
  23250. */
  23251. set( r, g, b, a = 1 ) {
  23252. this.a = a;
  23253. return super.set( r, g, b );
  23254. }
  23255. /**
  23256. * Overwrites the default to honor alpha.
  23257. *
  23258. * @param {Color4} color - The color to copy.
  23259. * @return {Color4} A reference to this object.
  23260. */
  23261. copy( color ) {
  23262. if ( color.a !== undefined ) this.a = color.a;
  23263. return super.copy( color );
  23264. }
  23265. /**
  23266. * Overwrites the default to honor alpha.
  23267. *
  23268. * @return {Color4} The cloned color.
  23269. */
  23270. clone() {
  23271. return new this.constructor( this.r, this.g, this.b, this.a );
  23272. }
  23273. }
  23274. /**
  23275. * Special version of {@link PropertyNode} which is used for parameters.
  23276. *
  23277. * @augments PropertyNode
  23278. */
  23279. class ParameterNode extends PropertyNode {
  23280. static get type() {
  23281. return 'ParameterNode';
  23282. }
  23283. /**
  23284. * Constructs a new parameter node.
  23285. *
  23286. * @param {string} nodeType - The type of the node.
  23287. * @param {?string} [name=null] - The name of the parameter in the shader.
  23288. */
  23289. constructor( nodeType, name = null ) {
  23290. super( nodeType, name );
  23291. /**
  23292. * This flag can be used for type testing.
  23293. *
  23294. * @type {boolean}
  23295. * @readonly
  23296. * @default true
  23297. */
  23298. this.isParameterNode = true;
  23299. }
  23300. /**
  23301. * Gets the type of a member variable in the parameter node.
  23302. *
  23303. * @param {NodeBuilder} builder - The node builder.
  23304. * @param {string} name - The name of the member variable.
  23305. * @returns {string}
  23306. */
  23307. getMemberType( builder, name ) {
  23308. const type = this.getNodeType( builder );
  23309. const struct = builder.getStructTypeNode( type );
  23310. let memberType;
  23311. if ( struct !== null ) {
  23312. memberType = struct.getMemberType( builder, name );
  23313. } else {
  23314. error( `TSL: Member "${ name }" not found in struct "${ type }".` );
  23315. memberType = 'float';
  23316. }
  23317. return memberType;
  23318. }
  23319. getHash() {
  23320. return this.uuid;
  23321. }
  23322. generate() {
  23323. return this.name;
  23324. }
  23325. }
  23326. /**
  23327. * TSL function for creating a parameter node.
  23328. *
  23329. * @tsl
  23330. * @function
  23331. * @param {string} type - The type of the node.
  23332. * @param {?string} name - The name of the parameter in the shader.
  23333. * @returns {ParameterNode}
  23334. */
  23335. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  23336. /**
  23337. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  23338. * They are usually needed in cases like `If`, `Else`.
  23339. *
  23340. * @augments Node
  23341. */
  23342. class StackNode extends Node {
  23343. static get type() {
  23344. return 'StackNode';
  23345. }
  23346. /**
  23347. * Constructs a new stack node.
  23348. *
  23349. * @param {?StackNode} [parent=null] - The parent stack node.
  23350. */
  23351. constructor( parent = null ) {
  23352. super();
  23353. /**
  23354. * List of nodes.
  23355. *
  23356. * @type {Array<Node>}
  23357. */
  23358. this.nodes = [];
  23359. /**
  23360. * The output node.
  23361. *
  23362. * @type {?Node}
  23363. * @default null
  23364. */
  23365. this.outputNode = null;
  23366. /**
  23367. * The parent stack node.
  23368. *
  23369. * @type {?StackNode}
  23370. * @default null
  23371. */
  23372. this.parent = parent;
  23373. /**
  23374. * The current conditional node.
  23375. *
  23376. * @private
  23377. * @type {ConditionalNode}
  23378. * @default null
  23379. */
  23380. this._currentCond = null;
  23381. /**
  23382. * The expression node. Only
  23383. * relevant for Switch/Case.
  23384. *
  23385. * @private
  23386. * @type {Node}
  23387. * @default null
  23388. */
  23389. this._expressionNode = null;
  23390. /**
  23391. * This flag can be used for type testing.
  23392. *
  23393. * @type {boolean}
  23394. * @readonly
  23395. * @default true
  23396. */
  23397. this.isStackNode = true;
  23398. }
  23399. getElementType( builder ) {
  23400. return this.hasOutput ? this.outputNode.getElementType( builder ) : 'void';
  23401. }
  23402. getNodeType( builder ) {
  23403. return this.hasOutput ? this.outputNode.getNodeType( builder ) : 'void';
  23404. }
  23405. getMemberType( builder, name ) {
  23406. return this.hasOutput ? this.outputNode.getMemberType( builder, name ) : 'void';
  23407. }
  23408. /**
  23409. * Adds a node to this stack.
  23410. *
  23411. * @param {Node} node - The node to add.
  23412. * @return {StackNode} A reference to this stack node.
  23413. */
  23414. addToStack( node ) {
  23415. if ( node.isNode !== true ) {
  23416. error( 'TSL: Invalid node added to stack.' );
  23417. return this;
  23418. }
  23419. this.nodes.push( node );
  23420. return this;
  23421. }
  23422. /**
  23423. * Represent an `if` statement in TSL.
  23424. *
  23425. * @param {Node} boolNode - Represents the condition.
  23426. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23427. * @return {StackNode} A reference to this stack node.
  23428. */
  23429. If( boolNode, method ) {
  23430. const methodNode = new ShaderNode( method );
  23431. this._currentCond = select( boolNode, methodNode );
  23432. return this.addToStack( this._currentCond );
  23433. }
  23434. /**
  23435. * Represent an `elseif` statement in TSL.
  23436. *
  23437. * @param {Node} boolNode - Represents the condition.
  23438. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23439. * @return {StackNode} A reference to this stack node.
  23440. */
  23441. ElseIf( boolNode, method ) {
  23442. const methodNode = new ShaderNode( method );
  23443. const ifNode = select( boolNode, methodNode );
  23444. this._currentCond.elseNode = ifNode;
  23445. this._currentCond = ifNode;
  23446. return this;
  23447. }
  23448. /**
  23449. * Represent an `else` statement in TSL.
  23450. *
  23451. * @param {Function} method - TSL code which is executed in the `else` case.
  23452. * @return {StackNode} A reference to this stack node.
  23453. */
  23454. Else( method ) {
  23455. this._currentCond.elseNode = new ShaderNode( method );
  23456. return this;
  23457. }
  23458. /**
  23459. * Represents a `switch` statement in TSL.
  23460. *
  23461. * @param {any} expression - Represents the expression.
  23462. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23463. * @return {StackNode} A reference to this stack node.
  23464. */
  23465. Switch( expression ) {
  23466. this._expressionNode = nodeObject( expression );
  23467. return this;
  23468. }
  23469. /**
  23470. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  23471. * The last parameter must be the callback method that should be executed in the `true` case.
  23472. *
  23473. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  23474. * @return {StackNode} A reference to this stack node.
  23475. */
  23476. Case( ...params ) {
  23477. const caseNodes = [];
  23478. // extract case nodes from the parameter list
  23479. if ( params.length >= 2 ) {
  23480. for ( let i = 0; i < params.length - 1; i ++ ) {
  23481. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  23482. }
  23483. } else {
  23484. error( 'TSL: Invalid parameter length. Case() requires at least two parameters.' );
  23485. }
  23486. // extract method
  23487. const method = params[ params.length - 1 ];
  23488. const methodNode = new ShaderNode( method );
  23489. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  23490. let caseNode = caseNodes[ 0 ];
  23491. for ( let i = 1; i < caseNodes.length; i ++ ) {
  23492. caseNode = caseNode.or( caseNodes[ i ] );
  23493. }
  23494. // build condition
  23495. const condNode = select( caseNode, methodNode );
  23496. if ( this._currentCond === null ) {
  23497. this._currentCond = condNode;
  23498. return this.addToStack( this._currentCond );
  23499. } else {
  23500. this._currentCond.elseNode = condNode;
  23501. this._currentCond = condNode;
  23502. return this;
  23503. }
  23504. }
  23505. /**
  23506. * Represents the default code block of a Switch/Case statement.
  23507. *
  23508. * @param {Function} method - TSL code which is executed in the `else` case.
  23509. * @return {StackNode} A reference to this stack node.
  23510. */
  23511. Default( method ) {
  23512. this.Else( method );
  23513. return this;
  23514. }
  23515. setup( builder ) {
  23516. const nodeProperties = builder.getNodeProperties( this );
  23517. let index = 0;
  23518. for ( const childNode of this.getChildren() ) {
  23519. if ( childNode.isVarNode && childNode.intent === true ) {
  23520. if ( childNode.isAssign( builder ) !== true ) {
  23521. continue;
  23522. }
  23523. }
  23524. nodeProperties[ 'node' + index ++ ] = childNode;
  23525. }
  23526. // return a outputNode if exists or null
  23527. return nodeProperties.outputNode || null;
  23528. }
  23529. get hasOutput() {
  23530. return this.outputNode && this.outputNode.isNode;
  23531. }
  23532. build( builder, ...params ) {
  23533. const previousStack = getCurrentStack();
  23534. setCurrentStack( this );
  23535. builder.setActiveStack( this );
  23536. const buildStage = builder.buildStage;
  23537. for ( const node of this.nodes ) {
  23538. if ( node.isVarNode && node.intent === true ) {
  23539. if ( node.isAssign( builder ) !== true ) {
  23540. continue;
  23541. }
  23542. }
  23543. if ( buildStage === 'setup' ) {
  23544. node.build( builder );
  23545. } else if ( buildStage === 'analyze' ) {
  23546. node.build( builder, this );
  23547. } else if ( buildStage === 'generate' ) {
  23548. const stages = builder.getDataFromNode( node, 'any' ).stages;
  23549. const parents = stages && stages[ builder.shaderStage ];
  23550. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  23551. continue; // skip var nodes that are only used in .toVarying()
  23552. }
  23553. node.build( builder, 'void' );
  23554. }
  23555. }
  23556. //
  23557. let result;
  23558. if ( this.hasOutput ) {
  23559. result = this.outputNode.build( builder, ...params );
  23560. } else {
  23561. result = super.build( builder, ...params );
  23562. }
  23563. setCurrentStack( previousStack );
  23564. builder.removeActiveStack( this );
  23565. return result;
  23566. }
  23567. }
  23568. /**
  23569. * TSL function for creating a stack node.
  23570. *
  23571. * @tsl
  23572. * @function
  23573. * @param {?StackNode} [parent=null] - The parent stack node.
  23574. * @returns {StackNode}
  23575. */
  23576. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  23577. /**
  23578. * Generates a layout for struct members.
  23579. * This function takes an object representing struct members and returns an array of member layouts.
  23580. * Each member layout includes the member's name, type, and whether it is atomic.
  23581. *
  23582. * @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.
  23583. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  23584. */
  23585. function getMembersLayout( members ) {
  23586. return Object.entries( members ).map( ( [ name, value ] ) => {
  23587. if ( typeof value === 'string' ) {
  23588. return { name, type: value, atomic: false };
  23589. }
  23590. return { name, type: value.type, atomic: value.atomic || false };
  23591. } );
  23592. }
  23593. /**
  23594. * Represents a struct type node in the node-based system.
  23595. * This class is used to define and manage the layout and types of struct members.
  23596. * It extends the base Node class and provides methods to get the length of the struct,
  23597. * retrieve member types, and generate the struct type for a builder.
  23598. *
  23599. * @augments Node
  23600. */
  23601. class StructTypeNode extends Node {
  23602. static get type() {
  23603. return 'StructTypeNode';
  23604. }
  23605. /**
  23606. * Creates an instance of StructTypeNode.
  23607. *
  23608. * @param {Object} membersLayout - The layout of the members for the struct.
  23609. * @param {?string} [name=null] - The optional name of the struct.
  23610. */
  23611. constructor( membersLayout, name = null ) {
  23612. super( 'struct' );
  23613. /**
  23614. * The layout of the members for the struct
  23615. *
  23616. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  23617. */
  23618. this.membersLayout = getMembersLayout( membersLayout );
  23619. /**
  23620. * The name of the struct.
  23621. *
  23622. * @type {?string}
  23623. * @default null
  23624. */
  23625. this.name = name;
  23626. /**
  23627. * This flag can be used for type testing.
  23628. *
  23629. * @type {boolean}
  23630. * @readonly
  23631. * @default true
  23632. */
  23633. this.isStructLayoutNode = true;
  23634. }
  23635. /**
  23636. * Returns the length of the struct.
  23637. * The length is calculated by summing the lengths of the struct's members.
  23638. *
  23639. * @returns {number} The length of the struct.
  23640. */
  23641. getLength() {
  23642. const GPU_CHUNK_BYTES = 8;
  23643. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  23644. let offset = 0; // global buffer offset in bytes
  23645. for ( const member of this.membersLayout ) {
  23646. const type = member.type;
  23647. const itemSize = getMemoryLengthFromType( type ) * BYTES_PER_ELEMENT;
  23648. const boundary = getByteBoundaryFromType( type );
  23649. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  23650. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  23651. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  23652. offset += chunkPadding;
  23653. // Check for chunk overflow
  23654. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  23655. // Add padding to the end of the chunk
  23656. offset += ( GPU_CHUNK_BYTES - chunkStart );
  23657. }
  23658. offset += itemSize;
  23659. }
  23660. return ( Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES ) / BYTES_PER_ELEMENT;
  23661. }
  23662. getMemberType( builder, name ) {
  23663. const member = this.membersLayout.find( m => m.name === name );
  23664. return member ? member.type : 'void';
  23665. }
  23666. getNodeType( builder ) {
  23667. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23668. return structType.name;
  23669. }
  23670. setup( builder ) {
  23671. builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23672. builder.addInclude( this );
  23673. }
  23674. generate( builder ) {
  23675. return this.getNodeType( builder );
  23676. }
  23677. }
  23678. /**
  23679. * StructNode allows to create custom structures with multiple members.
  23680. * This can also be used to define structures in attribute and uniform data.
  23681. *
  23682. * ```js
  23683. * // Define a custom struct
  23684. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  23685. *
  23686. * // Create a new instance of the struct
  23687. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  23688. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  23689. *
  23690. * // Access the struct members
  23691. * const min = bb.get( 'min' );
  23692. *
  23693. * // Assign a new value to a member
  23694. * min.assign( vec3() );
  23695. * ```
  23696. * @augments Node
  23697. */
  23698. class StructNode extends Node {
  23699. static get type() {
  23700. return 'StructNode';
  23701. }
  23702. constructor( structTypeNode, values ) {
  23703. super( 'vec3' );
  23704. this.structTypeNode = structTypeNode;
  23705. this.values = values;
  23706. this.isStructNode = true;
  23707. }
  23708. getNodeType( builder ) {
  23709. return this.structTypeNode.getNodeType( builder );
  23710. }
  23711. getMemberType( builder, name ) {
  23712. return this.structTypeNode.getMemberType( builder, name );
  23713. }
  23714. generate( builder ) {
  23715. const nodeVar = builder.getVarFromNode( this );
  23716. const structType = nodeVar.type;
  23717. const propertyName = builder.getPropertyName( nodeVar );
  23718. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structTypeNode.membersLayout, this.values ) }`, this );
  23719. return nodeVar.name;
  23720. }
  23721. }
  23722. /**
  23723. * TSL function for creating a struct node.
  23724. *
  23725. * @tsl
  23726. * @function
  23727. * @param {Object} membersLayout - The layout of the struct members.
  23728. * @param {?string} [name=null] - The name of the struct.
  23729. * @returns {Function} The struct function.
  23730. */
  23731. const struct = ( membersLayout, name = null ) => {
  23732. const structLayout = new StructTypeNode( membersLayout, name );
  23733. const struct = ( ...params ) => {
  23734. let values = null;
  23735. if ( params.length > 0 ) {
  23736. if ( params[ 0 ].isNode ) {
  23737. values = {};
  23738. const names = Object.keys( membersLayout );
  23739. for ( let i = 0; i < params.length; i ++ ) {
  23740. values[ names[ i ] ] = params[ i ];
  23741. }
  23742. } else {
  23743. values = params[ 0 ];
  23744. }
  23745. }
  23746. return nodeObject( new StructNode( structLayout, values ) );
  23747. };
  23748. struct.layout = structLayout;
  23749. struct.isStruct = true;
  23750. return struct;
  23751. };
  23752. /**
  23753. * This node can be used to define multiple outputs in a shader programs.
  23754. *
  23755. * @augments Node
  23756. */
  23757. class OutputStructNode extends Node {
  23758. static get type() {
  23759. return 'OutputStructNode';
  23760. }
  23761. /**
  23762. * Constructs a new output struct node. The constructor can be invoked with an
  23763. * arbitrary number of nodes representing the members.
  23764. *
  23765. * @param {...Node} members - A parameter list of nodes.
  23766. */
  23767. constructor( ...members ) {
  23768. super();
  23769. /**
  23770. * An array of nodes which defines the output.
  23771. *
  23772. * @type {Array<Node>}
  23773. */
  23774. this.members = members;
  23775. /**
  23776. * This flag can be used for type testing.
  23777. *
  23778. * @type {boolean}
  23779. * @readonly
  23780. * @default true
  23781. */
  23782. this.isOutputStructNode = true;
  23783. }
  23784. getNodeType( builder ) {
  23785. const properties = builder.getNodeProperties( this );
  23786. if ( properties.membersLayout === undefined ) {
  23787. const members = this.members;
  23788. const membersLayout = [];
  23789. for ( let i = 0; i < members.length; i ++ ) {
  23790. const name = 'm' + i;
  23791. const type = members[ i ].getNodeType( builder );
  23792. membersLayout.push( { name, type, index: i } );
  23793. }
  23794. properties.membersLayout = membersLayout;
  23795. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  23796. }
  23797. return properties.structType.name;
  23798. }
  23799. generate( builder ) {
  23800. const propertyName = builder.getOutputStructName();
  23801. const members = this.members;
  23802. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  23803. for ( let i = 0; i < members.length; i ++ ) {
  23804. const snippet = members[ i ].build( builder );
  23805. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  23806. }
  23807. return propertyName;
  23808. }
  23809. }
  23810. /**
  23811. * TSL function for creating an output struct node.
  23812. *
  23813. * @tsl
  23814. * @function
  23815. * @param {...Node} members - A parameter list of nodes.
  23816. * @returns {OutputStructNode}
  23817. */
  23818. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  23819. /**
  23820. * Returns the MRT texture index for the given name.
  23821. *
  23822. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  23823. * @param {string} name - The name of the MRT texture which index is requested.
  23824. * @return {number} The texture index.
  23825. */
  23826. function getTextureIndex( textures, name ) {
  23827. for ( let i = 0; i < textures.length; i ++ ) {
  23828. if ( textures[ i ].name === name ) {
  23829. return i;
  23830. }
  23831. }
  23832. return -1;
  23833. }
  23834. /**
  23835. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  23836. * post-processing is shown below:
  23837. * ```js
  23838. * const mrtNode = mrt( {
  23839. * output: output,
  23840. * normal: normalView
  23841. * } ) );
  23842. * ```
  23843. * The MRT output is defined as a dictionary.
  23844. *
  23845. * @augments OutputStructNode
  23846. */
  23847. class MRTNode extends OutputStructNode {
  23848. static get type() {
  23849. return 'MRTNode';
  23850. }
  23851. /**
  23852. * Constructs a new output struct node.
  23853. *
  23854. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  23855. */
  23856. constructor( outputNodes ) {
  23857. super();
  23858. /**
  23859. * A dictionary representing the MRT outputs. The key
  23860. * is the name of the output, the value the node which produces
  23861. * the output result.
  23862. *
  23863. * @type {Object<string, Node>}
  23864. */
  23865. this.outputNodes = outputNodes;
  23866. /**
  23867. * This flag can be used for type testing.
  23868. *
  23869. * @type {boolean}
  23870. * @readonly
  23871. * @default true
  23872. */
  23873. this.isMRTNode = true;
  23874. }
  23875. /**
  23876. * Returns `true` if the MRT node has an output with the given name.
  23877. *
  23878. * @param {string} name - The name of the output.
  23879. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  23880. */
  23881. has( name ) {
  23882. return this.outputNodes[ name ] !== undefined;
  23883. }
  23884. /**
  23885. * Returns the output node for the given name.
  23886. *
  23887. * @param {string} name - The name of the output.
  23888. * @return {Node} The output node.
  23889. */
  23890. get( name ) {
  23891. return this.outputNodes[ name ];
  23892. }
  23893. /**
  23894. * Merges the outputs of the given MRT node with the outputs of this node.
  23895. *
  23896. * @param {MRTNode} mrtNode - The MRT to merge.
  23897. * @return {MRTNode} A new MRT node with merged outputs..
  23898. */
  23899. merge( mrtNode ) {
  23900. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  23901. return mrt( outputs );
  23902. }
  23903. setup( builder ) {
  23904. const outputNodes = this.outputNodes;
  23905. const mrt = builder.renderer.getRenderTarget();
  23906. const members = [];
  23907. const textures = mrt.textures;
  23908. for ( const name in outputNodes ) {
  23909. const index = getTextureIndex( textures, name );
  23910. members[ index ] = vec4( outputNodes[ name ] );
  23911. }
  23912. this.members = members;
  23913. return super.setup( builder );
  23914. }
  23915. }
  23916. /**
  23917. * TSL function for creating a MRT node.
  23918. *
  23919. * @tsl
  23920. * @function
  23921. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  23922. * @returns {MRTNode}
  23923. */
  23924. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  23925. /**
  23926. * This node represents an operation that reinterprets the bit representation of a value
  23927. * in one type as a value in another type.
  23928. *
  23929. * @augments TempNode
  23930. */
  23931. class BitcastNode extends TempNode {
  23932. static get type() {
  23933. return 'BitcastNode';
  23934. }
  23935. /**
  23936. * Constructs a new bitcast node.
  23937. *
  23938. * @param {Node} valueNode - The value to convert.
  23939. * @param {string} conversionType - The type to convert to.
  23940. * @param {?string} [inputType = null] - The expected input data type of the bitcast operation.
  23941. */
  23942. constructor( valueNode, conversionType, inputType = null ) {
  23943. super();
  23944. /**
  23945. * The data to bitcast to a new type.
  23946. *
  23947. * @type {Node}
  23948. */
  23949. this.valueNode = valueNode;
  23950. /**
  23951. * The type the value will be converted to.
  23952. *
  23953. * @type {string}
  23954. */
  23955. this.conversionType = conversionType;
  23956. /**
  23957. * The expected input data type of the bitcast operation.
  23958. *
  23959. *
  23960. * @type {string}
  23961. * @default null
  23962. */
  23963. this.inputType = inputType;
  23964. /**
  23965. * This flag can be used for type testing.
  23966. *
  23967. * @type {boolean}
  23968. * @readonly
  23969. * @default true
  23970. */
  23971. this.isBitcastNode = true;
  23972. }
  23973. getNodeType( builder ) {
  23974. // GLSL aliasing
  23975. if ( this.inputType !== null ) {
  23976. const valueType = this.valueNode.getNodeType( builder );
  23977. const valueLength = builder.getTypeLength( valueType );
  23978. return builder.getTypeFromLength( valueLength, this.conversionType );
  23979. }
  23980. return this.conversionType;
  23981. }
  23982. generate( builder ) {
  23983. const type = this.getNodeType( builder );
  23984. let inputType = '';
  23985. if ( this.inputType !== null ) {
  23986. const valueType = this.valueNode.getNodeType( builder );
  23987. const valueTypeLength = builder.getTypeLength( valueType );
  23988. inputType = valueTypeLength === 1 ? this.inputType : builder.changeComponentType( valueType, this.inputType );
  23989. } else {
  23990. inputType = this.valueNode.getNodeType( builder );
  23991. }
  23992. return `${ builder.getBitcastMethod( type, inputType ) }( ${ this.valueNode.build( builder, inputType ) } )`;
  23993. }
  23994. }
  23995. /**
  23996. * Reinterpret the bit representation of a value in one type as a value in another type.
  23997. *
  23998. * @tsl
  23999. * @function
  24000. * @param {Node | number} x - The parameter.
  24001. * @param {string} y - The new type.
  24002. * @returns {Node}
  24003. */
  24004. const bitcast = /*@__PURE__*/ nodeProxyIntent( BitcastNode ).setParameterLength( 2 );
  24005. /**
  24006. * Bitcasts a float or a vector of floats to a corresponding integer type with the same element size.
  24007. *
  24008. * @tsl
  24009. * @function
  24010. * @param {Node<float>} value - The float or vector of floats to bitcast.
  24011. * @returns {BitcastNode}
  24012. */
  24013. const floatBitsToInt = ( value ) => new BitcastNode( value, 'int', 'float' );
  24014. /**
  24015. * Bitcasts a float or a vector of floats to a corresponding unsigned integer type with the same element size.
  24016. *
  24017. * @tsl
  24018. * @function
  24019. * @param {Node<float>} value - The float or vector of floats to bitcast.
  24020. * @returns {BitcastNode}
  24021. */
  24022. const floatBitsToUint = ( value ) => new BitcastNode( value, 'uint', 'float' );
  24023. /**
  24024. * Bitcasts an integer or a vector of integers to a corresponding float type with the same element size.
  24025. *
  24026. * @tsl
  24027. * @function
  24028. * @param {Node<int>} value - The integer or vector of integers to bitcast.
  24029. * @returns {BitcastNode}
  24030. */
  24031. const intBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'int' );
  24032. /**
  24033. * Bitcast an unsigned integer or a vector of unsigned integers to a corresponding float type with the same element size.
  24034. *
  24035. * @tsl
  24036. * @function
  24037. * @param {Node<uint>} value - The unsigned integer or vector of unsigned integers to bitcast.
  24038. * @returns {BitcastNode}
  24039. */
  24040. const uintBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'uint' );
  24041. const registeredBitcountFunctions = {};
  24042. /**
  24043. * This node represents an operation that counts the bits of a piece of shader data.
  24044. *
  24045. * @augments MathNode
  24046. */
  24047. class BitcountNode extends MathNode {
  24048. static get type() {
  24049. return 'BitcountNode';
  24050. }
  24051. /**
  24052. * Constructs a new math node.
  24053. *
  24054. * @param {'countTrailingZeros'|'countLeadingZeros'|'countOneBits'} method - The method name.
  24055. * @param {Node} aNode - The first input.
  24056. */
  24057. constructor( method, aNode ) {
  24058. super( method, aNode );
  24059. /**
  24060. * This flag can be used for type testing.
  24061. *
  24062. * @type {boolean}
  24063. * @readonly
  24064. * @default true
  24065. */
  24066. this.isBitcountNode = true;
  24067. }
  24068. /**
  24069. * Casts the input value of the function to an integer if necessary.
  24070. *
  24071. * @private
  24072. * @param {Node<uint>|Node<int>} inputNode - The input value.
  24073. * @param {Node<uint>} outputNode - The output value.
  24074. * @param {string} elementType - The type of the input value.
  24075. */
  24076. _resolveElementType( inputNode, outputNode, elementType ) {
  24077. if ( elementType === 'int' ) {
  24078. outputNode.assign( bitcast( inputNode, 'uint' ) );
  24079. } else {
  24080. outputNode.assign( inputNode );
  24081. }
  24082. }
  24083. _returnDataNode( inputType ) {
  24084. switch ( inputType ) {
  24085. case 'uint': {
  24086. return uint;
  24087. }
  24088. case 'int': {
  24089. return int;
  24090. }
  24091. case 'uvec2': {
  24092. return uvec2;
  24093. }
  24094. case 'uvec3': {
  24095. return uvec3;
  24096. }
  24097. case 'uvec4': {
  24098. return uvec4;
  24099. }
  24100. case 'ivec2': {
  24101. return ivec2;
  24102. }
  24103. case 'ivec3': {
  24104. return ivec3;
  24105. }
  24106. case 'ivec4': {
  24107. return ivec4;
  24108. }
  24109. }
  24110. }
  24111. /**
  24112. * Creates and registers a reusable GLSL function that emulates the behavior of countTrailingZeros.
  24113. *
  24114. * @private
  24115. * @param {string} method - The name of the function to create.
  24116. * @param {string} elementType - The type of the input value.
  24117. * @returns {Function} - The generated function
  24118. */
  24119. _createTrailingZerosBaseLayout( method, elementType ) {
  24120. const outputConvertNode = this._returnDataNode( elementType );
  24121. const fnDef = Fn( ( [ value ] ) => {
  24122. const v = uint( 0.0 );
  24123. this._resolveElementType( value, v, elementType );
  24124. const f = float( v.bitAnd( negate( v ) ) );
  24125. const uintBits = floatBitsToUint( f );
  24126. const numTrailingZeros = ( uintBits.shiftRight( 23 ) ).sub( 127 );
  24127. return outputConvertNode( numTrailingZeros );
  24128. } ).setLayout( {
  24129. name: method,
  24130. type: elementType,
  24131. inputs: [
  24132. { name: 'value', type: elementType }
  24133. ]
  24134. } );
  24135. return fnDef;
  24136. }
  24137. /**
  24138. * Creates and registers a reusable GLSL function that emulates the behavior of countLeadingZeros.
  24139. *
  24140. * @private
  24141. * @param {string} method - The name of the function to create.
  24142. * @param {string} elementType - The type of the input value.
  24143. * @returns {Function} - The generated function
  24144. */
  24145. _createLeadingZerosBaseLayout( method, elementType ) {
  24146. const outputConvertNode = this._returnDataNode( elementType );
  24147. const fnDef = Fn( ( [ value ] ) => {
  24148. If( value.equal( uint( 0 ) ), () => {
  24149. return uint( 32 );
  24150. } );
  24151. const v = uint( 0 );
  24152. const n = uint( 0 );
  24153. this._resolveElementType( value, v, elementType );
  24154. If( v.shiftRight( 16 ).equal( 0 ), () => {
  24155. n.addAssign( 16 );
  24156. v.shiftLeftAssign( 16 );
  24157. } );
  24158. If( v.shiftRight( 24 ).equal( 0 ), () => {
  24159. n.addAssign( 8 );
  24160. v.shiftLeftAssign( 8 );
  24161. } );
  24162. If( v.shiftRight( 28 ).equal( 0 ), () => {
  24163. n.addAssign( 4 );
  24164. v.shiftLeftAssign( 4 );
  24165. } );
  24166. If( v.shiftRight( 30 ).equal( 0 ), () => {
  24167. n.addAssign( 2 );
  24168. v.shiftLeftAssign( 2 );
  24169. } );
  24170. If( v.shiftRight( 31 ).equal( 0 ), () => {
  24171. n.addAssign( 1 );
  24172. } );
  24173. return outputConvertNode( n );
  24174. } ).setLayout( {
  24175. name: method,
  24176. type: elementType,
  24177. inputs: [
  24178. { name: 'value', type: elementType }
  24179. ]
  24180. } );
  24181. return fnDef;
  24182. }
  24183. /**
  24184. * Creates and registers a reusable GLSL function that emulates the behavior of countOneBits.
  24185. *
  24186. * @private
  24187. * @param {string} method - The name of the function to create.
  24188. * @param {string} elementType - The type of the input value.
  24189. * @returns {Function} - The generated function
  24190. */
  24191. _createOneBitsBaseLayout( method, elementType ) {
  24192. const outputConvertNode = this._returnDataNode( elementType );
  24193. const fnDef = Fn( ( [ value ] ) => {
  24194. const v = uint( 0.0 );
  24195. this._resolveElementType( value, v, elementType );
  24196. v.assign( v.sub( v.shiftRight( uint( 1 ) ).bitAnd( uint( 0x55555555 ) ) ) );
  24197. v.assign( v.bitAnd( uint( 0x33333333 ) ).add( v.shiftRight( uint( 2 ) ).bitAnd( uint( 0x33333333 ) ) ) );
  24198. const numBits = v.add( v.shiftRight( uint( 4 ) ) ).bitAnd( uint( 0xF0F0F0F ) ).mul( uint( 0x1010101 ) ).shiftRight( uint( 24 ) );
  24199. return outputConvertNode( numBits );
  24200. } ).setLayout( {
  24201. name: method,
  24202. type: elementType,
  24203. inputs: [
  24204. { name: 'value', type: elementType }
  24205. ]
  24206. } );
  24207. return fnDef;
  24208. }
  24209. /**
  24210. * Creates and registers a reusable GLSL function that emulates the behavior of the specified bitcount function.
  24211. * including considerations for component-wise bitcounts on vector type inputs.
  24212. *
  24213. * @private
  24214. * @param {string} method - The name of the function to create.
  24215. * @param {string} inputType - The type of the input value.
  24216. * @param {number} typeLength - The vec length of the input value.
  24217. * @param {Function} baseFn - The base function that operates on an individual component of the vector.
  24218. * @returns {Function} - The alias function for the specified bitcount method.
  24219. */
  24220. _createMainLayout( method, inputType, typeLength, baseFn ) {
  24221. const outputConvertNode = this._returnDataNode( inputType );
  24222. const fnDef = Fn( ( [ value ] ) => {
  24223. if ( typeLength === 1 ) {
  24224. return outputConvertNode( baseFn( value ) );
  24225. } else {
  24226. const vec = outputConvertNode( 0 );
  24227. const components = [ 'x', 'y', 'z', 'w' ];
  24228. for ( let i = 0; i < typeLength; i ++ ) {
  24229. const component = components[ i ];
  24230. vec[ component ].assign( baseFn( value[ component ] ) );
  24231. }
  24232. return vec;
  24233. }
  24234. } ).setLayout( {
  24235. name: method,
  24236. type: inputType,
  24237. inputs: [
  24238. { name: 'value', type: inputType }
  24239. ]
  24240. } );
  24241. return fnDef;
  24242. }
  24243. setup( builder ) {
  24244. const { method, aNode } = this;
  24245. const { renderer } = builder;
  24246. if ( renderer.backend.isWebGPUBackend ) {
  24247. // use built-in WGSL functions for WebGPU
  24248. return super.setup( builder );
  24249. }
  24250. const inputType = this.getInputType( builder );
  24251. const elementType = builder.getElementType( inputType );
  24252. const typeLength = builder.getTypeLength( inputType );
  24253. const baseMethod = `${method}_base_${elementType}`;
  24254. const newMethod = `${method}_${inputType}`;
  24255. let baseFn = registeredBitcountFunctions[ baseMethod ];
  24256. if ( baseFn === undefined ) {
  24257. switch ( method ) {
  24258. case BitcountNode.COUNT_LEADING_ZEROS: {
  24259. baseFn = this._createLeadingZerosBaseLayout( baseMethod, elementType );
  24260. break;
  24261. }
  24262. case BitcountNode.COUNT_TRAILING_ZEROS: {
  24263. baseFn = this._createTrailingZerosBaseLayout( baseMethod, elementType );
  24264. break;
  24265. }
  24266. case BitcountNode.COUNT_ONE_BITS: {
  24267. baseFn = this._createOneBitsBaseLayout( baseMethod, elementType );
  24268. break;
  24269. }
  24270. }
  24271. registeredBitcountFunctions[ baseMethod ] = baseFn;
  24272. }
  24273. let fn = registeredBitcountFunctions[ newMethod ];
  24274. if ( fn === undefined ) {
  24275. fn = this._createMainLayout( newMethod, inputType, typeLength, baseFn );
  24276. registeredBitcountFunctions[ newMethod ] = fn;
  24277. }
  24278. const output = Fn( () => {
  24279. return fn(
  24280. aNode,
  24281. );
  24282. } );
  24283. return output();
  24284. }
  24285. }
  24286. BitcountNode.COUNT_TRAILING_ZEROS = 'countTrailingZeros';
  24287. BitcountNode.COUNT_LEADING_ZEROS = 'countLeadingZeros';
  24288. BitcountNode.COUNT_ONE_BITS = 'countOneBits';
  24289. /**
  24290. * Finds the number of consecutive 0 bits from the least significant bit of the input value,
  24291. * which is also the index of the least significant bit of the input value.
  24292. *
  24293. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  24294. *
  24295. * @tsl
  24296. * @function
  24297. * @param {Node | number} x - The input value.
  24298. * @returns {Node}
  24299. */
  24300. const countTrailingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_TRAILING_ZEROS ).setParameterLength( 1 );
  24301. /**
  24302. * Finds the number of consecutive 0 bits starting from the most significant bit of the input value.
  24303. *
  24304. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  24305. *
  24306. * @tsl
  24307. * @function
  24308. * @param {Node | number} x - The input value.
  24309. * @returns {Node}
  24310. */
  24311. const countLeadingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_LEADING_ZEROS ).setParameterLength( 1 );
  24312. /**
  24313. * Finds the number of '1' bits set in the input value
  24314. *
  24315. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  24316. *
  24317. * @tsl
  24318. * @function
  24319. * @returns {Node}
  24320. */
  24321. const countOneBits = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_ONE_BITS ).setParameterLength( 1 );
  24322. /**
  24323. * Generates a hash value in the range `[0, 1]` from the given seed.
  24324. *
  24325. * @tsl
  24326. * @function
  24327. * @param {Node<float>} seed - The seed.
  24328. * @return {Node<float>} The hash value.
  24329. */
  24330. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  24331. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  24332. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  24333. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  24334. const result = word.shiftRight( 22 ).bitXor( word );
  24335. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  24336. } );
  24337. /**
  24338. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  24339. * The corners are mapped to `0` and the center to `1`.
  24340. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24341. *
  24342. * @tsl
  24343. * @function
  24344. * @param {Node<float>} x - The value to remap.
  24345. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  24346. * @return {Node<float>} The remapped value.
  24347. */
  24348. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  24349. /**
  24350. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  24351. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  24352. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24353. *
  24354. * @tsl
  24355. * @function
  24356. * @param {Node<float>} x - The value to remap.
  24357. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  24358. * @return {Node<float>} The remapped value.
  24359. */
  24360. 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 ) );
  24361. /**
  24362. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  24363. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  24364. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24365. *
  24366. * @tsl
  24367. * @function
  24368. * @param {Node<float>} x - The value to remap.
  24369. * @param {Node<float>} a - First control parameter.
  24370. * @param {Node<float>} b - Second control parameter.
  24371. * @return {Node<float>} The remapped value.
  24372. */
  24373. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  24374. /**
  24375. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  24376. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24377. *
  24378. * @tsl
  24379. * @function
  24380. * @param {Node<float>} x - The value to compute the sin for.
  24381. * @param {Node<float>} k - Controls the amount of bounces.
  24382. * @return {Node<float>} The result value.
  24383. */
  24384. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  24385. // https://github.com/cabbibo/glsl-tri-noise-3d
  24386. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  24387. return x.fract().sub( .5 ).abs();
  24388. } ).setLayout( {
  24389. name: 'tri',
  24390. type: 'float',
  24391. inputs: [
  24392. { name: 'x', type: 'float' }
  24393. ]
  24394. } );
  24395. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  24396. 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. ) ) ) ) );
  24397. } ).setLayout( {
  24398. name: 'tri3',
  24399. type: 'vec3',
  24400. inputs: [
  24401. { name: 'p', type: 'vec3' }
  24402. ]
  24403. } );
  24404. /**
  24405. * Generates a noise value from the given position, speed and time parameters.
  24406. *
  24407. * @tsl
  24408. * @function
  24409. * @param {Node<vec3>} position - The position.
  24410. * @param {Node<float>} speed - The speed.
  24411. * @param {Node<float>} time - The time.
  24412. * @return {Node<float>} The generated noise.
  24413. */
  24414. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  24415. const p = vec3( position ).toVar();
  24416. const z = float( 1.4 ).toVar();
  24417. const rz = float( 0.0 ).toVar();
  24418. const bp = vec3( p ).toVar();
  24419. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  24420. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  24421. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  24422. bp.mulAssign( 1.8 );
  24423. z.mulAssign( 1.5 );
  24424. p.mulAssign( 1.2 );
  24425. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  24426. rz.addAssign( t.div( z ) );
  24427. bp.addAssign( 0.14 );
  24428. } );
  24429. return rz;
  24430. } ).setLayout( {
  24431. name: 'triNoise3D',
  24432. type: 'float',
  24433. inputs: [
  24434. { name: 'position', type: 'vec3' },
  24435. { name: 'speed', type: 'float' },
  24436. { name: 'time', type: 'float' }
  24437. ]
  24438. } );
  24439. /**
  24440. * This class allows to define multiple overloaded versions
  24441. * of the same function. Depending on the parameters of the function
  24442. * call, the node picks the best-fit overloaded version.
  24443. *
  24444. * @augments Node
  24445. */
  24446. class FunctionOverloadingNode extends Node {
  24447. static get type() {
  24448. return 'FunctionOverloadingNode';
  24449. }
  24450. /**
  24451. * Constructs a new function overloading node.
  24452. *
  24453. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  24454. * @param {...Node} parametersNodes - A list of parameter nodes.
  24455. */
  24456. constructor( functionNodes = [], ...parametersNodes ) {
  24457. super();
  24458. /**
  24459. * Array of `Fn` function definitions.
  24460. *
  24461. * @type {Array<Function>}
  24462. */
  24463. this.functionNodes = functionNodes;
  24464. /**
  24465. * A list of parameter nodes.
  24466. *
  24467. * @type {Array<Node>}
  24468. */
  24469. this.parametersNodes = parametersNodes;
  24470. /**
  24471. * The selected overloaded function call.
  24472. *
  24473. * @private
  24474. * @type {ShaderCallNodeInternal}
  24475. */
  24476. this._candidateFn = null;
  24477. /**
  24478. * This node is marked as global.
  24479. *
  24480. * @type {boolean}
  24481. * @default true
  24482. */
  24483. this.global = true;
  24484. }
  24485. /**
  24486. * This method is overwritten since the node type is inferred from
  24487. * the function's return type.
  24488. *
  24489. * @param {NodeBuilder} builder - The current node builder.
  24490. * @return {string} The node type.
  24491. */
  24492. getNodeType( builder ) {
  24493. const candidateFn = this.getCandidateFn( builder );
  24494. return candidateFn.shaderNode.layout.type;
  24495. }
  24496. /**
  24497. * Returns the candidate function for the current parameters.
  24498. *
  24499. * @param {NodeBuilder} builder - The current node builder.
  24500. * @return {FunctionNode} The candidate function.
  24501. */
  24502. getCandidateFn( builder ) {
  24503. const params = this.parametersNodes;
  24504. let candidateFn = this._candidateFn;
  24505. if ( candidateFn === null ) {
  24506. let bestCandidateFn = null;
  24507. let bestScore = -1;
  24508. for ( const functionNode of this.functionNodes ) {
  24509. const shaderNode = functionNode.shaderNode;
  24510. const layout = shaderNode.layout;
  24511. if ( layout === null ) {
  24512. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  24513. }
  24514. const inputs = layout.inputs;
  24515. if ( params.length === inputs.length ) {
  24516. let currentScore = 0;
  24517. for ( let i = 0; i < params.length; i ++ ) {
  24518. const param = params[ i ];
  24519. const input = inputs[ i ];
  24520. if ( param.getNodeType( builder ) === input.type ) {
  24521. currentScore ++;
  24522. }
  24523. }
  24524. if ( currentScore > bestScore ) {
  24525. bestCandidateFn = functionNode;
  24526. bestScore = currentScore;
  24527. }
  24528. }
  24529. }
  24530. this._candidateFn = candidateFn = bestCandidateFn;
  24531. }
  24532. return candidateFn;
  24533. }
  24534. /**
  24535. * Sets up the node for the current parameters.
  24536. *
  24537. * @param {NodeBuilder} builder - The current node builder.
  24538. * @return {Node} The setup node.
  24539. */
  24540. setup( builder ) {
  24541. const candidateFn = this.getCandidateFn( builder );
  24542. return candidateFn( ...this.parametersNodes );
  24543. }
  24544. }
  24545. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  24546. /**
  24547. * TSL function for creating a function overloading node.
  24548. *
  24549. * @tsl
  24550. * @function
  24551. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  24552. * @returns {FunctionOverloadingNode}
  24553. */
  24554. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  24555. /**
  24556. * Represents the elapsed time in seconds.
  24557. *
  24558. * @tsl
  24559. * @type {UniformNode<float>}
  24560. */
  24561. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  24562. /**
  24563. * Represents the delta time in seconds.
  24564. *
  24565. * @tsl
  24566. * @type {UniformNode<float>}
  24567. */
  24568. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  24569. /**
  24570. * Represents the current frame ID.
  24571. *
  24572. * @tsl
  24573. * @type {UniformNode<uint>}
  24574. */
  24575. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  24576. /**
  24577. * Generates a sine wave oscillation based on a timer.
  24578. *
  24579. * @tsl
  24580. * @function
  24581. * @param {Node<float>} t - The timer to generate the oscillation with.
  24582. * @return {Node<float>} The oscillation node.
  24583. */
  24584. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  24585. /**
  24586. * Generates a square wave oscillation based on a timer.
  24587. *
  24588. * @tsl
  24589. * @function
  24590. * @param {Node<float>} t - The timer to generate the oscillation with.
  24591. * @return {Node<float>} The oscillation node.
  24592. */
  24593. const oscSquare = ( t = time ) => t.fract().round();
  24594. /**
  24595. * Generates a triangle wave oscillation based on a timer.
  24596. *
  24597. * @tsl
  24598. * @function
  24599. * @param {Node<float>} t - The timer to generate the oscillation with.
  24600. * @return {Node<float>} The oscillation node.
  24601. */
  24602. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  24603. /**
  24604. * Generates a sawtooth wave oscillation based on a timer.
  24605. *
  24606. * @tsl
  24607. * @function
  24608. * @param {Node<float>} t - The timer to generate the oscillation with.
  24609. * @return {Node<float>} The oscillation node.
  24610. */
  24611. const oscSawtooth = ( t = time ) => t.fract();
  24612. /**
  24613. * Replaces the default UV coordinates used in texture lookups.
  24614. *
  24615. * ```js
  24616. *material.contextNode = replaceDefaultUV( ( textureNode ) => {
  24617. *
  24618. * // ...
  24619. * return customUVCoordinates;
  24620. *
  24621. *} );
  24622. *```
  24623. *
  24624. * @tsl
  24625. * @function
  24626. * @param {function(Node):Node<vec2>} callback - A callback that receives the texture node
  24627. * and must return the new uv coordinates.
  24628. * @param {Node} [node=null] - An optional node to which the context will be applied.
  24629. * @return {ContextNode} A context node that replaces the default UV coordinates.
  24630. */
  24631. function replaceDefaultUV( callback, node = null ) {
  24632. return context( node, { getUV: callback } );
  24633. }
  24634. /**
  24635. * Rotates the given uv coordinates around a center point
  24636. *
  24637. * @tsl
  24638. * @function
  24639. * @param {Node<vec2>} uv - The uv coordinates.
  24640. * @param {Node<float>} rotation - The rotation defined in radians.
  24641. * @param {Node<vec2>} center - The center of rotation
  24642. * @return {Node<vec2>} The rotated uv coordinates.
  24643. */
  24644. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  24645. return rotate( uv.sub( center ), rotation ).add( center );
  24646. } );
  24647. /**
  24648. * Applies a spherical warping effect to the given uv coordinates.
  24649. *
  24650. * @tsl
  24651. * @function
  24652. * @param {Node<vec2>} uv - The uv coordinates.
  24653. * @param {Node<float>} strength - The strength of the effect.
  24654. * @param {Node<vec2>} center - The center point
  24655. * @return {Node<vec2>} The updated uv coordinates.
  24656. */
  24657. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  24658. const delta = uv.sub( center );
  24659. const delta2 = delta.dot( delta );
  24660. const delta4 = delta2.mul( delta2 );
  24661. const deltaOffset = delta4.mul( strength );
  24662. return uv.add( delta.mul( deltaOffset ) );
  24663. } );
  24664. /**
  24665. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  24666. * oriented always towards the camera.
  24667. *
  24668. * ```js
  24669. * material.vertexNode = billboarding();
  24670. * ```
  24671. *
  24672. * @tsl
  24673. * @function
  24674. * @param {Object} config - The configuration object.
  24675. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  24676. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  24677. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  24678. * @return {Node<vec3>} The updated vertex position in clip space.
  24679. */
  24680. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  24681. let worldMatrix;
  24682. if ( position !== null ) {
  24683. worldMatrix = modelWorldMatrix.toVar();
  24684. worldMatrix[ 3 ][ 0 ] = position.x;
  24685. worldMatrix[ 3 ][ 1 ] = position.y;
  24686. worldMatrix[ 3 ][ 2 ] = position.z;
  24687. } else {
  24688. worldMatrix = modelWorldMatrix;
  24689. }
  24690. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  24691. if ( defined( horizontal ) ) {
  24692. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  24693. modelViewMatrix[ 0 ][ 1 ] = 0;
  24694. modelViewMatrix[ 0 ][ 2 ] = 0;
  24695. }
  24696. if ( defined( vertical ) ) {
  24697. modelViewMatrix[ 1 ][ 0 ] = 0;
  24698. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  24699. modelViewMatrix[ 1 ][ 2 ] = 0;
  24700. }
  24701. modelViewMatrix[ 2 ][ 0 ] = 0;
  24702. modelViewMatrix[ 2 ][ 1 ] = 0;
  24703. modelViewMatrix[ 2 ][ 2 ] = 1;
  24704. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  24705. } );
  24706. /**
  24707. * A special version of a screen uv function that involves a depth comparison
  24708. * when computing the final uvs. The function mitigates visual errors when
  24709. * using viewport texture nodes for refraction purposes. Without this function
  24710. * objects in front of a refractive surface might appear on the refractive surface
  24711. * which is incorrect.
  24712. *
  24713. * @tsl
  24714. * @function
  24715. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  24716. * @return {Node<vec2>} The update uv coordinates.
  24717. */
  24718. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  24719. const depth = linearDepth();
  24720. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  24721. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  24722. return finalUV;
  24723. } );
  24724. /**
  24725. * Can be used to compute texture coordinates for animated sprite sheets.
  24726. *
  24727. * ```js
  24728. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  24729. *
  24730. * material.colorNode = texture( spriteSheet, uvNode );
  24731. * ```
  24732. *
  24733. * @augments Node
  24734. */
  24735. class SpriteSheetUVNode extends Node {
  24736. static get type() {
  24737. return 'SpriteSheetUVNode';
  24738. }
  24739. /**
  24740. * Constructs a new sprite sheet uv node.
  24741. *
  24742. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  24743. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  24744. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  24745. */
  24746. constructor( countNode, uvNode = uv$1(), frameNode = float( 0 ) ) {
  24747. super( 'vec2' );
  24748. /**
  24749. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  24750. *
  24751. * @type {Node<vec2>}
  24752. */
  24753. this.countNode = countNode;
  24754. /**
  24755. * The uv node.
  24756. *
  24757. * @type {Node<vec2>}
  24758. */
  24759. this.uvNode = uvNode;
  24760. /**
  24761. * The node that defines the current frame/sprite.
  24762. *
  24763. * @type {Node<float>}
  24764. */
  24765. this.frameNode = frameNode;
  24766. }
  24767. setup() {
  24768. const { frameNode, uvNode, countNode } = this;
  24769. const { width, height } = countNode;
  24770. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  24771. const column = frameNum.mod( width );
  24772. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  24773. const scale = countNode.reciprocal();
  24774. const uvFrameOffset = vec2( column, row );
  24775. return uvNode.add( uvFrameOffset ).mul( scale );
  24776. }
  24777. }
  24778. /**
  24779. * TSL function for creating a sprite sheet uv node.
  24780. *
  24781. * @tsl
  24782. * @function
  24783. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  24784. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  24785. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  24786. * @returns {SpriteSheetUVNode}
  24787. */
  24788. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  24789. /**
  24790. * TSL function for creating a triplanar textures node.
  24791. *
  24792. * Can be used for triplanar texture mapping.
  24793. *
  24794. * ```js
  24795. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  24796. * ```
  24797. *
  24798. * @tsl
  24799. * @function
  24800. * @param {Node} textureXNode - First texture node.
  24801. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  24802. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  24803. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  24804. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  24805. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  24806. * @returns {Node<vec4>}
  24807. */
  24808. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  24809. // Reference: https://github.com/keijiro/StandardTriplanar
  24810. // Blending factor of triplanar mapping
  24811. let bf = normalNode.abs().normalize();
  24812. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  24813. // Triplanar mapping
  24814. const tx = positionNode.yz.mul( scaleNode );
  24815. const ty = positionNode.zx.mul( scaleNode );
  24816. const tz = positionNode.xy.mul( scaleNode );
  24817. // Base color
  24818. const textureX = textureXNode.value;
  24819. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  24820. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  24821. const cx = texture( textureX, tx ).mul( bf.x );
  24822. const cy = texture( textureY, ty ).mul( bf.y );
  24823. const cz = texture( textureZ, tz ).mul( bf.z );
  24824. return add( cx, cy, cz );
  24825. } );
  24826. /**
  24827. * TSL function for creating a triplanar textures node.
  24828. *
  24829. * @tsl
  24830. * @function
  24831. * @param {Node} textureXNode - First texture node.
  24832. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  24833. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  24834. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  24835. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  24836. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  24837. * @returns {Node<vec4>}
  24838. */
  24839. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  24840. const _reflectorPlane = new Plane();
  24841. const _normal = new Vector3();
  24842. const _reflectorWorldPosition = new Vector3();
  24843. const _cameraWorldPosition = new Vector3();
  24844. const _rotationMatrix = new Matrix4();
  24845. const _lookAtPosition = new Vector3( 0, 0, -1 );
  24846. const clipPlane = new Vector4();
  24847. const _view = new Vector3();
  24848. const _target = new Vector3();
  24849. const _q = new Vector4();
  24850. const _size$2 = new Vector2();
  24851. const _defaultRT = new RenderTarget();
  24852. const _defaultUV = screenUV.flipX();
  24853. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  24854. let _inReflector = false;
  24855. /**
  24856. * This node can be used to implement mirror-like flat reflective surfaces.
  24857. *
  24858. * ```js
  24859. * const groundReflector = reflector();
  24860. * material.colorNode = groundReflector;
  24861. *
  24862. * const plane = new Mesh( geometry, material );
  24863. * plane.add( groundReflector.target );
  24864. * ```
  24865. *
  24866. * @augments TextureNode
  24867. */
  24868. class ReflectorNode extends TextureNode {
  24869. static get type() {
  24870. return 'ReflectorNode';
  24871. }
  24872. /**
  24873. * Constructs a new reflector node.
  24874. *
  24875. * @param {Object} [parameters={}] - An object holding configuration parameters.
  24876. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  24877. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  24878. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  24879. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  24880. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  24881. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  24882. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  24883. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  24884. */
  24885. constructor( parameters = {} ) {
  24886. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  24887. /**
  24888. * A reference to the internal reflector base node which holds the actual implementation.
  24889. *
  24890. * @private
  24891. * @type {ReflectorBaseNode}
  24892. * @default ReflectorBaseNode
  24893. */
  24894. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  24895. /**
  24896. * A reference to the internal depth node.
  24897. *
  24898. * @private
  24899. * @type {?Node}
  24900. * @default null
  24901. */
  24902. this._depthNode = null;
  24903. this.setUpdateMatrix( false );
  24904. }
  24905. /**
  24906. * A reference to the internal reflector node.
  24907. *
  24908. * @type {ReflectorBaseNode}
  24909. */
  24910. get reflector() {
  24911. return this._reflectorBaseNode;
  24912. }
  24913. /**
  24914. * A reference to 3D object the reflector is linked to.
  24915. *
  24916. * @type {Object3D}
  24917. */
  24918. get target() {
  24919. return this._reflectorBaseNode.target;
  24920. }
  24921. /**
  24922. * Returns a node representing the mirror's depth. That can be used
  24923. * to implement more advanced reflection effects like distance attenuation.
  24924. *
  24925. * @return {Node} The depth node.
  24926. */
  24927. getDepthNode() {
  24928. if ( this._depthNode === null ) {
  24929. if ( this._reflectorBaseNode.depth !== true ) {
  24930. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  24931. }
  24932. this._depthNode = nodeObject( new ReflectorNode( {
  24933. defaultTexture: _defaultRT.depthTexture,
  24934. reflector: this._reflectorBaseNode
  24935. } ) );
  24936. }
  24937. return this._depthNode;
  24938. }
  24939. setup( builder ) {
  24940. // ignore if used in post-processing
  24941. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  24942. return super.setup( builder );
  24943. }
  24944. clone() {
  24945. const newNode = new this.constructor( this.reflectorNode );
  24946. newNode.uvNode = this.uvNode;
  24947. newNode.levelNode = this.levelNode;
  24948. newNode.biasNode = this.biasNode;
  24949. newNode.sampler = this.sampler;
  24950. newNode.depthNode = this.depthNode;
  24951. newNode.compareNode = this.compareNode;
  24952. newNode.gradNode = this.gradNode;
  24953. newNode.offsetNode = this.offsetNode;
  24954. newNode._reflectorBaseNode = this._reflectorBaseNode;
  24955. return newNode;
  24956. }
  24957. /**
  24958. * Frees internal resources. Should be called when the node is no longer in use.
  24959. */
  24960. dispose() {
  24961. super.dispose();
  24962. this._reflectorBaseNode.dispose();
  24963. }
  24964. }
  24965. /**
  24966. * Holds the actual implementation of the reflector.
  24967. *
  24968. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  24969. * in `ReflectorNode`, see #29619.
  24970. *
  24971. * @private
  24972. * @augments Node
  24973. */
  24974. class ReflectorBaseNode extends Node {
  24975. static get type() {
  24976. return 'ReflectorBaseNode';
  24977. }
  24978. /**
  24979. * Constructs a new reflector base node.
  24980. *
  24981. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  24982. * @param {Object} [parameters={}] - An object holding configuration parameters.
  24983. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  24984. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  24985. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  24986. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  24987. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  24988. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  24989. */
  24990. constructor( textureNode, parameters = {} ) {
  24991. super();
  24992. const {
  24993. target = new Object3D(),
  24994. resolutionScale = 1,
  24995. generateMipmaps = false,
  24996. bounces = true,
  24997. depth = false,
  24998. samples = 0
  24999. } = parameters;
  25000. /**
  25001. * Represents the rendered reflections as a texture node.
  25002. *
  25003. * @type {TextureNode}
  25004. */
  25005. this.textureNode = textureNode;
  25006. /**
  25007. * The 3D object the reflector is linked to.
  25008. *
  25009. * @type {Object3D}
  25010. * @default {new Object3D()}
  25011. */
  25012. this.target = target;
  25013. /**
  25014. * The resolution scale.
  25015. *
  25016. * @type {number}
  25017. * @default {1}
  25018. */
  25019. this.resolutionScale = resolutionScale;
  25020. if ( parameters.resolution !== undefined ) {
  25021. warnOnce( 'ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".' ); // @deprecated r180
  25022. this.resolutionScale = parameters.resolution;
  25023. }
  25024. /**
  25025. * Whether mipmaps should be generated or not.
  25026. *
  25027. * @type {boolean}
  25028. * @default {false}
  25029. */
  25030. this.generateMipmaps = generateMipmaps;
  25031. /**
  25032. * Whether reflectors can render other reflector nodes or not.
  25033. *
  25034. * @type {boolean}
  25035. * @default {true}
  25036. */
  25037. this.bounces = bounces;
  25038. /**
  25039. * Whether depth data should be generated or not.
  25040. *
  25041. * @type {boolean}
  25042. * @default {false}
  25043. */
  25044. this.depth = depth;
  25045. /**
  25046. * The number of anti-aliasing samples for the render-target
  25047. *
  25048. * @type {number}
  25049. * @default {0}
  25050. */
  25051. this.samples = samples;
  25052. /**
  25053. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  25054. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  25055. *
  25056. * @type {string}
  25057. * @default 'render'
  25058. */
  25059. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  25060. /**
  25061. * Weak map for managing virtual cameras.
  25062. *
  25063. * @type {WeakMap<Camera, Camera>}
  25064. */
  25065. this.virtualCameras = new WeakMap();
  25066. /**
  25067. * Weak map for managing render targets.
  25068. *
  25069. * @type {Map<Camera, RenderTarget>}
  25070. */
  25071. this.renderTargets = new Map();
  25072. /**
  25073. * Force render even if reflector is facing away from camera.
  25074. *
  25075. * @type {boolean}
  25076. * @default {false}
  25077. */
  25078. this.forceUpdate = false;
  25079. /**
  25080. * Whether the reflector has been rendered or not.
  25081. *
  25082. * When the reflector is facing away from the camera,
  25083. * this flag is set to `false` and the texture will be empty(black).
  25084. *
  25085. * @type {boolean}
  25086. * @default {false}
  25087. */
  25088. this.hasOutput = false;
  25089. }
  25090. /**
  25091. * Updates the resolution of the internal render target.
  25092. *
  25093. * @private
  25094. * @param {RenderTarget} renderTarget - The render target to resize.
  25095. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  25096. */
  25097. _updateResolution( renderTarget, renderer ) {
  25098. const resolution = this.resolutionScale;
  25099. renderer.getDrawingBufferSize( _size$2 );
  25100. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  25101. }
  25102. setup( builder ) {
  25103. this._updateResolution( _defaultRT, builder.renderer );
  25104. return super.setup( builder );
  25105. }
  25106. /**
  25107. * Frees internal resources. Should be called when the node is no longer in use.
  25108. */
  25109. dispose() {
  25110. super.dispose();
  25111. for ( const renderTarget of this.renderTargets.values() ) {
  25112. renderTarget.dispose();
  25113. }
  25114. }
  25115. /**
  25116. * Returns a virtual camera for the given camera. The virtual camera is used to
  25117. * render the scene from the reflector's view so correct reflections can be produced.
  25118. *
  25119. * @param {Camera} camera - The scene's camera.
  25120. * @return {Camera} The corresponding virtual camera.
  25121. */
  25122. getVirtualCamera( camera ) {
  25123. let virtualCamera = this.virtualCameras.get( camera );
  25124. if ( virtualCamera === undefined ) {
  25125. virtualCamera = camera.clone();
  25126. this.virtualCameras.set( camera, virtualCamera );
  25127. }
  25128. return virtualCamera;
  25129. }
  25130. /**
  25131. * Returns a render target for the given camera. The reflections are rendered
  25132. * into this render target.
  25133. *
  25134. * @param {Camera} camera - The scene's camera.
  25135. * @return {RenderTarget} The render target.
  25136. */
  25137. getRenderTarget( camera ) {
  25138. let renderTarget = this.renderTargets.get( camera );
  25139. if ( renderTarget === undefined ) {
  25140. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  25141. if ( this.generateMipmaps === true ) {
  25142. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  25143. renderTarget.texture.generateMipmaps = true;
  25144. }
  25145. if ( this.depth === true ) {
  25146. renderTarget.depthTexture = new DepthTexture();
  25147. }
  25148. this.renderTargets.set( camera, renderTarget );
  25149. }
  25150. return renderTarget;
  25151. }
  25152. updateBefore( frame ) {
  25153. if ( this.bounces === false && _inReflector ) return false;
  25154. _inReflector = true;
  25155. const { scene, camera, renderer, material } = frame;
  25156. const { target } = this;
  25157. const virtualCamera = this.getVirtualCamera( camera );
  25158. const renderTarget = this.getRenderTarget( virtualCamera );
  25159. renderer.getDrawingBufferSize( _size$2 );
  25160. this._updateResolution( renderTarget, renderer );
  25161. //
  25162. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  25163. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  25164. _rotationMatrix.extractRotation( target.matrixWorld );
  25165. _normal.set( 0, 0, 1 );
  25166. _normal.applyMatrix4( _rotationMatrix );
  25167. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  25168. // Avoid rendering when reflector is facing away unless forcing an update
  25169. const isFacingAway = _view.dot( _normal ) > 0;
  25170. let needsClear = false;
  25171. if ( isFacingAway === true && this.forceUpdate === false ) {
  25172. if ( this.hasOutput === false ) {
  25173. _inReflector = false;
  25174. return;
  25175. }
  25176. needsClear = true;
  25177. }
  25178. _view.reflect( _normal ).negate();
  25179. _view.add( _reflectorWorldPosition );
  25180. _rotationMatrix.extractRotation( camera.matrixWorld );
  25181. _lookAtPosition.set( 0, 0, -1 );
  25182. _lookAtPosition.applyMatrix4( _rotationMatrix );
  25183. _lookAtPosition.add( _cameraWorldPosition );
  25184. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  25185. _target.reflect( _normal ).negate();
  25186. _target.add( _reflectorWorldPosition );
  25187. //
  25188. virtualCamera.coordinateSystem = camera.coordinateSystem;
  25189. virtualCamera.position.copy( _view );
  25190. virtualCamera.up.set( 0, 1, 0 );
  25191. virtualCamera.up.applyMatrix4( _rotationMatrix );
  25192. virtualCamera.up.reflect( _normal );
  25193. virtualCamera.lookAt( _target );
  25194. virtualCamera.near = camera.near;
  25195. virtualCamera.far = camera.far;
  25196. virtualCamera.updateMatrixWorld();
  25197. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  25198. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  25199. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  25200. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  25201. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  25202. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  25203. const projectionMatrix = virtualCamera.projectionMatrix;
  25204. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  25205. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  25206. _q.z = -1;
  25207. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  25208. // Calculate the scaled plane vector
  25209. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  25210. const clipBias = 0;
  25211. // Replacing the third row of the projection matrix
  25212. projectionMatrix.elements[ 2 ] = clipPlane.x;
  25213. projectionMatrix.elements[ 6 ] = clipPlane.y;
  25214. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  25215. projectionMatrix.elements[ 14 ] = clipPlane.w;
  25216. //
  25217. this.textureNode.value = renderTarget.texture;
  25218. if ( this.depth === true ) {
  25219. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  25220. }
  25221. material.visible = false;
  25222. const currentRenderTarget = renderer.getRenderTarget();
  25223. const currentMRT = renderer.getMRT();
  25224. const currentAutoClear = renderer.autoClear;
  25225. renderer.setMRT( null );
  25226. renderer.setRenderTarget( renderTarget );
  25227. renderer.autoClear = true;
  25228. const previousName = scene.name;
  25229. scene.name = ( scene.name || 'Scene' ) + ' [ Reflector ]'; // TODO: Add bounce index
  25230. if ( needsClear ) {
  25231. renderer.clear();
  25232. this.hasOutput = false;
  25233. } else {
  25234. renderer.render( scene, virtualCamera );
  25235. this.hasOutput = true;
  25236. }
  25237. scene.name = previousName;
  25238. renderer.setMRT( currentMRT );
  25239. renderer.setRenderTarget( currentRenderTarget );
  25240. renderer.autoClear = currentAutoClear;
  25241. material.visible = true;
  25242. _inReflector = false;
  25243. this.forceUpdate = false;
  25244. }
  25245. /**
  25246. * The resolution scale.
  25247. *
  25248. * @deprecated
  25249. * @type {number}
  25250. * @default {1}
  25251. */
  25252. get resolution() {
  25253. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  25254. return this.resolutionScale;
  25255. }
  25256. set resolution( value ) {
  25257. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  25258. this.resolutionScale = value;
  25259. }
  25260. }
  25261. /**
  25262. * TSL function for creating a reflector node.
  25263. *
  25264. * @tsl
  25265. * @function
  25266. * @param {Object} [parameters={}] - An object holding configuration parameters.
  25267. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  25268. * @param {number} [parameters.resolution=1] - The resolution scale.
  25269. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  25270. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  25271. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  25272. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  25273. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  25274. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  25275. * @returns {ReflectorNode}
  25276. */
  25277. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  25278. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  25279. /**
  25280. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  25281. *
  25282. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  25283. *
  25284. * @private
  25285. * @augments BufferGeometry
  25286. */
  25287. class QuadGeometry extends BufferGeometry {
  25288. /**
  25289. * Constructs a new quad geometry.
  25290. *
  25291. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  25292. */
  25293. constructor( flipY = false ) {
  25294. super();
  25295. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  25296. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  25297. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  25298. }
  25299. }
  25300. const _geometry = /*@__PURE__*/ new QuadGeometry();
  25301. /**
  25302. * This module is a helper for passes which need to render a full
  25303. * screen effect which is quite common in context of post processing.
  25304. *
  25305. * The intended usage is to reuse a single quad mesh for rendering
  25306. * subsequent passes by just reassigning the `material` reference.
  25307. *
  25308. * Note: This module can only be used with `WebGPURenderer`.
  25309. *
  25310. * @augments Mesh
  25311. */
  25312. class QuadMesh extends Mesh {
  25313. /**
  25314. * Constructs a new quad mesh.
  25315. *
  25316. * @param {?Material} [material=null] - The material to render the quad mesh with.
  25317. */
  25318. constructor( material = null ) {
  25319. super( _geometry, material );
  25320. /**
  25321. * The camera to render the quad mesh with.
  25322. *
  25323. * @type {OrthographicCamera}
  25324. * @readonly
  25325. */
  25326. this.camera = _camera;
  25327. /**
  25328. * This flag can be used for type testing.
  25329. *
  25330. * @type {boolean}
  25331. * @readonly
  25332. * @default true
  25333. */
  25334. this.isQuadMesh = true;
  25335. }
  25336. /**
  25337. * Async version of `render()`.
  25338. *
  25339. * @async
  25340. * @deprecated
  25341. * @param {Renderer} renderer - The renderer.
  25342. * @return {Promise} A Promise that resolves when the render has been finished.
  25343. */
  25344. async renderAsync( renderer ) {
  25345. warnOnce( 'QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  25346. await renderer.init();
  25347. renderer.render( this, _camera );
  25348. }
  25349. /**
  25350. * Renders the quad mesh
  25351. *
  25352. * @param {Renderer} renderer - The renderer.
  25353. */
  25354. render( renderer ) {
  25355. renderer.render( this, _camera );
  25356. }
  25357. }
  25358. const _size$1 = /*@__PURE__*/ new Vector2();
  25359. /**
  25360. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  25361. * This module is especially relevant in context of post processing where certain nodes require
  25362. * texture input for their effects. With the helper function `convertToTexture()` which is based
  25363. * on this module, the node system can automatically ensure texture input if required.
  25364. *
  25365. * @augments TextureNode
  25366. */
  25367. class RTTNode extends TextureNode {
  25368. static get type() {
  25369. return 'RTTNode';
  25370. }
  25371. /**
  25372. * Constructs a new RTT node.
  25373. *
  25374. * @param {Node} node - The node to render a texture with.
  25375. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  25376. * @param {?number} [height=null] - The height of the internal render target.
  25377. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  25378. */
  25379. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  25380. const renderTarget = new RenderTarget( width, height, options );
  25381. super( renderTarget.texture, uv$1() );
  25382. /**
  25383. * This flag can be used for type testing.
  25384. *
  25385. * @type {boolean}
  25386. * @readonly
  25387. * @default true
  25388. */
  25389. this.isRTTNode = true;
  25390. /**
  25391. * The node to render a texture with.
  25392. *
  25393. * @type {Node}
  25394. */
  25395. this.node = node;
  25396. /**
  25397. * The width of the internal render target.
  25398. * If not width is applied, the render target is automatically resized.
  25399. *
  25400. * @type {?number}
  25401. * @default null
  25402. */
  25403. this.width = width;
  25404. /**
  25405. * The height of the internal render target.
  25406. *
  25407. * @type {?number}
  25408. * @default null
  25409. */
  25410. this.height = height;
  25411. /**
  25412. * The pixel ratio
  25413. *
  25414. * @type {number}
  25415. * @default 1
  25416. */
  25417. this.pixelRatio = 1;
  25418. /**
  25419. * The render target
  25420. *
  25421. * @type {RenderTarget}
  25422. */
  25423. this.renderTarget = renderTarget;
  25424. /**
  25425. * Whether the texture requires an update or not.
  25426. *
  25427. * @type {boolean}
  25428. * @default true
  25429. */
  25430. this.textureNeedsUpdate = true;
  25431. /**
  25432. * Whether the texture should automatically be updated or not.
  25433. *
  25434. * @type {boolean}
  25435. * @default true
  25436. */
  25437. this.autoUpdate = true;
  25438. /**
  25439. * The node which is used with the quad mesh for RTT.
  25440. *
  25441. * @private
  25442. * @type {Node}
  25443. * @default null
  25444. */
  25445. this._rttNode = null;
  25446. /**
  25447. * The internal quad mesh for RTT.
  25448. *
  25449. * @private
  25450. * @type {QuadMesh}
  25451. */
  25452. this._quadMesh = new QuadMesh( new NodeMaterial() );
  25453. /**
  25454. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  25455. * the texture once per render in its {@link RTTNode#updateBefore} method.
  25456. *
  25457. * @type {string}
  25458. * @default 'render'
  25459. */
  25460. this.updateBeforeType = NodeUpdateType.RENDER;
  25461. }
  25462. /**
  25463. * Whether the internal render target should automatically be resized or not.
  25464. *
  25465. * @type {boolean}
  25466. * @readonly
  25467. * @default true
  25468. */
  25469. get autoResize() {
  25470. return this.width === null;
  25471. }
  25472. setup( builder ) {
  25473. this._rttNode = this.node.context( builder.getSharedContext() );
  25474. this._quadMesh.material.name = 'RTT';
  25475. this._quadMesh.material.needsUpdate = true;
  25476. return super.setup( builder );
  25477. }
  25478. /**
  25479. * Sets the size of the internal render target
  25480. *
  25481. * @param {number} width - The width to set.
  25482. * @param {number} height - The width to set.
  25483. */
  25484. setSize( width, height ) {
  25485. this.width = width;
  25486. this.height = height;
  25487. const effectiveWidth = width * this.pixelRatio;
  25488. const effectiveHeight = height * this.pixelRatio;
  25489. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  25490. this.textureNeedsUpdate = true;
  25491. }
  25492. /**
  25493. * Sets the pixel ratio. This will also resize the render target.
  25494. *
  25495. * @param {number} pixelRatio - The pixel ratio to set.
  25496. */
  25497. setPixelRatio( pixelRatio ) {
  25498. this.pixelRatio = pixelRatio;
  25499. this.setSize( this.width, this.height );
  25500. }
  25501. updateBefore( { renderer } ) {
  25502. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  25503. this.textureNeedsUpdate = false;
  25504. //
  25505. if ( this.autoResize === true ) {
  25506. const pixelRatio = renderer.getPixelRatio();
  25507. const size = renderer.getSize( _size$1 );
  25508. const effectiveWidth = Math.floor( size.width * pixelRatio );
  25509. const effectiveHeight = Math.floor( size.height * pixelRatio );
  25510. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  25511. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  25512. this.textureNeedsUpdate = true;
  25513. }
  25514. }
  25515. //
  25516. let name = 'RTT';
  25517. if ( this.node.name ) {
  25518. name = this.node.name + ' [ ' + name + ' ]';
  25519. }
  25520. this._quadMesh.material.fragmentNode = this._rttNode;
  25521. this._quadMesh.name = name;
  25522. //
  25523. const currentRenderTarget = renderer.getRenderTarget();
  25524. renderer.setRenderTarget( this.renderTarget );
  25525. this._quadMesh.render( renderer );
  25526. renderer.setRenderTarget( currentRenderTarget );
  25527. }
  25528. clone() {
  25529. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  25530. newNode.sampler = this.sampler;
  25531. newNode.referenceNode = this;
  25532. return newNode;
  25533. }
  25534. }
  25535. /**
  25536. * TSL function for creating a RTT node.
  25537. *
  25538. * @tsl
  25539. * @function
  25540. * @param {Node} node - The node to render a texture with.
  25541. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  25542. * @param {?number} [height=null] - The height of the internal render target.
  25543. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  25544. * @returns {RTTNode}
  25545. */
  25546. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  25547. /**
  25548. * TSL function for converting nodes to textures nodes.
  25549. *
  25550. * @tsl
  25551. * @function
  25552. * @param {Node} node - The node to render a texture with.
  25553. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  25554. * @param {?number} [height=null] - The height of the internal render target.
  25555. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  25556. * @returns {RTTNode}
  25557. */
  25558. const convertToTexture = ( node, ...params ) => {
  25559. if ( node.isSampleNode || node.isTextureNode ) return node;
  25560. if ( node.isPassNode ) return node.getTextureNode();
  25561. return rtt( node, ...params );
  25562. };
  25563. /**
  25564. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  25565. * depth value and the camera's inverse projection matrix.
  25566. *
  25567. * @tsl
  25568. * @function
  25569. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  25570. * @param {Node<float>} depth - The fragment's depth value.
  25571. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  25572. * @return {Node<vec3>} The fragments position in view space.
  25573. */
  25574. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  25575. let clipSpacePosition;
  25576. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25577. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  25578. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  25579. } else {
  25580. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  25581. }
  25582. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  25583. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  25584. } );
  25585. /**
  25586. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  25587. * and the camera's projection matrix
  25588. *
  25589. * @tsl
  25590. * @function
  25591. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  25592. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  25593. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  25594. */
  25595. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  25596. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  25597. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  25598. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  25599. } );
  25600. /**
  25601. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  25602. * target is available or if flat surface normals are required.
  25603. *
  25604. * @tsl
  25605. * @function
  25606. * @param {Node<vec2>} uv - The texture coordinate.
  25607. * @param {DepthTexture} depthTexture - The depth texture.
  25608. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  25609. * @return {Node<vec3>} The computed normal vector.
  25610. */
  25611. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  25612. const size = textureSize( textureLoad( depthTexture ) );
  25613. const p = ivec2( uv.mul( size ) ).toVar();
  25614. const c0 = textureLoad( depthTexture, p ).toVar();
  25615. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  25616. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  25617. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  25618. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  25619. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  25620. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  25621. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  25622. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  25623. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  25624. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  25625. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  25626. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  25627. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  25628. 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 ) ) );
  25629. 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 ) ) );
  25630. return normalize( cross( dpdx, dpdy ) );
  25631. } );
  25632. /**
  25633. * Interleaved Gradient Noise (IGN) from Jimenez 2014.
  25634. *
  25635. * IGN has "low discrepancy" resulting in evenly distributed samples. It's superior compared to
  25636. * default white noise, blue noise or Bayer.
  25637. *
  25638. * References:
  25639. * - {@link https://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare/}
  25640. * - {@link https://blog.demofox.org/2022/01/01/interleaved-gradient-noise-a-different-kind-of-low-discrepancy-sequence/}
  25641. *
  25642. * @tsl
  25643. * @function
  25644. * @param {Node<vec2>} position - The input position, usually screen coordinates.
  25645. * @return {Node<float>} The noise value.
  25646. */
  25647. const interleavedGradientNoise = Fn( ( [ position ] ) => {
  25648. return fract( float( 52.9829189 ).mul( fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ) );
  25649. } ).setLayout( {
  25650. name: 'interleavedGradientNoise',
  25651. type: 'float',
  25652. inputs: [
  25653. { name: 'position', type: 'vec2' }
  25654. ]
  25655. } );
  25656. /**
  25657. * Class representing a node that samples a value using a provided callback function.
  25658. *
  25659. * @extends Node
  25660. */
  25661. class SampleNode extends Node {
  25662. /**
  25663. * Returns the type of the node.
  25664. *
  25665. * @type {string}
  25666. * @readonly
  25667. * @static
  25668. */
  25669. static get type() {
  25670. return 'SampleNode';
  25671. }
  25672. /**
  25673. * Creates an instance of SampleNode.
  25674. *
  25675. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  25676. * @param {?Node<vec2>} [uvNode=null] - The UV node to be used in the texture sampling.
  25677. */
  25678. constructor( callback, uvNode = null ) {
  25679. super();
  25680. this.callback = callback;
  25681. /**
  25682. * Represents the texture coordinates.
  25683. *
  25684. * @type {?Node<vec2|vec3>}
  25685. * @default null
  25686. */
  25687. this.uvNode = uvNode;
  25688. /**
  25689. * This flag can be used for type testing.
  25690. *
  25691. * @type {boolean}
  25692. * @readonly
  25693. * @default true
  25694. */
  25695. this.isSampleNode = true;
  25696. }
  25697. /**
  25698. * Sets up the node by sampling with the default UV accessor.
  25699. *
  25700. * @returns {Node} The result of the callback function when called with the UV node.
  25701. */
  25702. setup() {
  25703. return this.sample( uv$1() );
  25704. }
  25705. /**
  25706. * Calls the callback function with the provided UV node.
  25707. *
  25708. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  25709. * @returns {Node} The result of the callback function.
  25710. */
  25711. sample( uv ) {
  25712. return this.callback( uv );
  25713. }
  25714. }
  25715. /**
  25716. * Helper function to create a SampleNode wrapped as a node object.
  25717. *
  25718. * @function
  25719. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  25720. * @param {?Node<vec2>} [uv=null] - The UV node to be used in the texture sampling.
  25721. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  25722. */
  25723. const sample = ( callback, uv = null ) => nodeObject( new SampleNode( callback, nodeObject( uv ) ) );
  25724. /**
  25725. * EventNode is a node that executes a callback during specific update phases.
  25726. *
  25727. * @augments Node
  25728. */
  25729. class EventNode extends Node {
  25730. static get type() {
  25731. return 'EventNode';
  25732. }
  25733. /**
  25734. * Creates an EventNode.
  25735. *
  25736. * @param {string} eventType - The type of event
  25737. * @param {Function} callback - The callback to execute on update.
  25738. */
  25739. constructor( eventType, callback ) {
  25740. super( 'void' );
  25741. this.eventType = eventType;
  25742. this.callback = callback;
  25743. if ( eventType === EventNode.OBJECT ) {
  25744. this.updateType = NodeUpdateType.OBJECT;
  25745. } else if ( eventType === EventNode.MATERIAL ) {
  25746. this.updateType = NodeUpdateType.RENDER;
  25747. } else if ( eventType === EventNode.BEFORE_OBJECT ) {
  25748. this.updateBeforeType = NodeUpdateType.OBJECT;
  25749. } else if ( eventType === EventNode.BEFORE_MATERIAL ) {
  25750. this.updateBeforeType = NodeUpdateType.RENDER;
  25751. }
  25752. }
  25753. update( frame ) {
  25754. this.callback( frame );
  25755. }
  25756. updateBefore( frame ) {
  25757. this.callback( frame );
  25758. }
  25759. }
  25760. EventNode.OBJECT = 'object';
  25761. EventNode.MATERIAL = 'material';
  25762. EventNode.BEFORE_OBJECT = 'beforeObject';
  25763. EventNode.BEFORE_MATERIAL = 'beforeMaterial';
  25764. /**
  25765. * Helper to create an EventNode and add it to the stack.
  25766. *
  25767. * @param {string} type - The event type.
  25768. * @param {Function} callback - The callback function.
  25769. * @returns {EventNode}
  25770. */
  25771. const createEvent = ( type, callback ) => nodeObject( new EventNode( type, callback ) ).toStack();
  25772. /**
  25773. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  25774. *
  25775. * 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.
  25776. *
  25777. * @param {Function} callback - The callback function.
  25778. * @returns {EventNode}
  25779. */
  25780. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  25781. /**
  25782. * Creates an event that triggers a function when the first object that uses the material is rendered.
  25783. *
  25784. * 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.
  25785. *
  25786. * @param {Function} callback - The callback function.
  25787. * @returns {EventNode}
  25788. */
  25789. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  25790. /**
  25791. * Creates an event that triggers a function before an object (Mesh|Sprite) is updated.
  25792. *
  25793. * 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.
  25794. *
  25795. * @param {Function} callback - The callback function.
  25796. * @returns {EventNode}
  25797. */
  25798. const OnBeforeObjectUpdate = ( callback ) => createEvent( EventNode.BEFORE_OBJECT, callback );
  25799. /**
  25800. * Creates an event that triggers a function before the material is updated.
  25801. *
  25802. * 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.
  25803. *
  25804. * @param {Function} callback - The callback function.
  25805. * @returns {EventNode}
  25806. */
  25807. const OnBeforeMaterialUpdate = ( callback ) => createEvent( EventNode.BEFORE_MATERIAL, callback );
  25808. /**
  25809. * This special type of instanced buffer attribute is intended for compute shaders.
  25810. * In earlier three.js versions it was only possible to update attribute data
  25811. * on the CPU via JavaScript and then upload the data to the GPU. With the
  25812. * new material system and renderer it is now possible to use compute shaders
  25813. * to compute the data for an attribute more efficiently on the GPU.
  25814. *
  25815. * The idea is to create an instance of this class and provide it as an input
  25816. * to {@link StorageBufferNode}.
  25817. *
  25818. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  25819. *
  25820. * @augments InstancedBufferAttribute
  25821. */
  25822. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  25823. /**
  25824. * Constructs a new storage instanced buffer attribute.
  25825. *
  25826. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  25827. * The subsequent parameters are then obsolete.
  25828. * @param {number} itemSize - The item size.
  25829. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  25830. */
  25831. constructor( count, itemSize, typeClass = Float32Array ) {
  25832. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  25833. super( array, itemSize );
  25834. /**
  25835. * This flag can be used for type testing.
  25836. *
  25837. * @type {boolean}
  25838. * @readonly
  25839. * @default true
  25840. */
  25841. this.isStorageInstancedBufferAttribute = true;
  25842. }
  25843. }
  25844. /**
  25845. * This special type of buffer attribute is intended for compute shaders.
  25846. * In earlier three.js versions it was only possible to update attribute data
  25847. * on the CPU via JavaScript and then upload the data to the GPU. With the
  25848. * new material system and renderer it is now possible to use compute shaders
  25849. * to compute the data for an attribute more efficiently on the GPU.
  25850. *
  25851. * The idea is to create an instance of this class and provide it as an input
  25852. * to {@link StorageBufferNode}.
  25853. *
  25854. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  25855. *
  25856. * @augments BufferAttribute
  25857. */
  25858. class StorageBufferAttribute extends BufferAttribute {
  25859. /**
  25860. * Constructs a new storage buffer attribute.
  25861. *
  25862. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  25863. * The subsequent parameters are then obsolete.
  25864. * @param {number} itemSize - The item size.
  25865. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  25866. */
  25867. constructor( count, itemSize, typeClass = Float32Array ) {
  25868. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  25869. super( array, itemSize );
  25870. /**
  25871. * This flag can be used for type testing.
  25872. *
  25873. * @type {boolean}
  25874. * @readonly
  25875. * @default true
  25876. */
  25877. this.isStorageBufferAttribute = true;
  25878. }
  25879. }
  25880. /**
  25881. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  25882. *
  25883. * @tsl
  25884. * @function
  25885. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  25886. * @param {string|Struct} [type='float'] - The data type.
  25887. * @returns {StorageBufferNode}
  25888. */
  25889. const attributeArray = ( count, type = 'float' ) => {
  25890. let itemSize, typedArray;
  25891. if ( type.isStruct === true ) {
  25892. itemSize = type.layout.getLength();
  25893. typedArray = getTypedArrayFromType( 'float' );
  25894. } else {
  25895. itemSize = getLengthFromType( type );
  25896. typedArray = getTypedArrayFromType( type );
  25897. }
  25898. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  25899. const node = storage( buffer, type, count );
  25900. return node;
  25901. };
  25902. /**
  25903. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  25904. *
  25905. * @tsl
  25906. * @function
  25907. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  25908. * @param {string|Struct} [type='float'] - The data type.
  25909. * @returns {StorageBufferNode}
  25910. */
  25911. const instancedArray = ( count, type = 'float' ) => {
  25912. let itemSize, typedArray;
  25913. if ( type.isStruct === true ) {
  25914. itemSize = type.layout.getLength();
  25915. typedArray = getTypedArrayFromType( 'float' );
  25916. } else {
  25917. itemSize = getLengthFromType( type );
  25918. typedArray = getTypedArrayFromType( type );
  25919. }
  25920. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  25921. const node = storage( buffer, type, count );
  25922. return node;
  25923. };
  25924. /**
  25925. * A node for representing the uv coordinates of points.
  25926. *
  25927. * Can only be used with a WebGL backend. In WebGPU, point
  25928. * primitives always have the size of one pixel and can thus
  25929. * can't be used as sprite-like objects that display textures.
  25930. *
  25931. * @augments Node
  25932. */
  25933. class PointUVNode extends Node {
  25934. static get type() {
  25935. return 'PointUVNode';
  25936. }
  25937. /**
  25938. * Constructs a new point uv node.
  25939. */
  25940. constructor() {
  25941. super( 'vec2' );
  25942. /**
  25943. * This flag can be used for type testing.
  25944. *
  25945. * @type {boolean}
  25946. * @readonly
  25947. * @default true
  25948. */
  25949. this.isPointUVNode = true;
  25950. }
  25951. generate( /*builder*/ ) {
  25952. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  25953. }
  25954. }
  25955. /**
  25956. * TSL object that represents the uv coordinates of points.
  25957. *
  25958. * @tsl
  25959. * @type {PointUVNode}
  25960. */
  25961. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  25962. const _e1 = /*@__PURE__*/ new Euler();
  25963. const _m1 = /*@__PURE__*/ new Matrix4();
  25964. /**
  25965. * This module allows access to a collection of scene properties. The following predefined TSL objects
  25966. * are available for easier use:
  25967. *
  25968. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  25969. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  25970. * - `backgroundRotation`: A node that represents the scene's background rotation.
  25971. *
  25972. * @augments Node
  25973. */
  25974. class SceneNode extends Node {
  25975. static get type() {
  25976. return 'SceneNode';
  25977. }
  25978. /**
  25979. * Constructs a new scene node.
  25980. *
  25981. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  25982. * @param {?Scene} [scene=null] - A reference to the scene.
  25983. */
  25984. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  25985. super();
  25986. /**
  25987. * The scope defines the type of scene property that is accessed.
  25988. *
  25989. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  25990. */
  25991. this.scope = scope;
  25992. /**
  25993. * A reference to the scene that is going to be accessed.
  25994. *
  25995. * @type {?Scene}
  25996. * @default null
  25997. */
  25998. this.scene = scene;
  25999. }
  26000. /**
  26001. * Depending on the scope, the method returns a different type of node that represents
  26002. * the respective scene property.
  26003. *
  26004. * @param {NodeBuilder} builder - The current node builder.
  26005. * @return {Node} The output node.
  26006. */
  26007. setup( builder ) {
  26008. const scope = this.scope;
  26009. const scene = this.scene !== null ? this.scene : builder.scene;
  26010. let output;
  26011. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  26012. output = reference( 'backgroundBlurriness', 'float', scene );
  26013. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  26014. output = reference( 'backgroundIntensity', 'float', scene );
  26015. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  26016. output = uniform( 'mat4' ).setName( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  26017. const background = scene.background;
  26018. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  26019. _e1.copy( scene.backgroundRotation );
  26020. // accommodate left-handed frame
  26021. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  26022. _m1.makeRotationFromEuler( _e1 );
  26023. } else {
  26024. _m1.identity();
  26025. }
  26026. return _m1;
  26027. } );
  26028. } else {
  26029. error( 'SceneNode: Unknown scope:', scope );
  26030. }
  26031. return output;
  26032. }
  26033. }
  26034. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  26035. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  26036. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  26037. /**
  26038. * TSL object that represents the scene's background blurriness.
  26039. *
  26040. * @tsl
  26041. * @type {SceneNode}
  26042. */
  26043. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  26044. /**
  26045. * TSL object that represents the scene's background intensity.
  26046. *
  26047. * @tsl
  26048. * @type {SceneNode}
  26049. */
  26050. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  26051. /**
  26052. * TSL object that represents the scene's background rotation.
  26053. *
  26054. * @tsl
  26055. * @type {SceneNode}
  26056. */
  26057. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  26058. /**
  26059. * This special version of a texture node can be used to
  26060. * write data into a storage texture with a compute shader.
  26061. *
  26062. * ```js
  26063. * const storageTexture = new THREE.StorageTexture( width, height );
  26064. *
  26065. * const computeTexture = Fn( ( { storageTexture } ) => {
  26066. *
  26067. * const posX = instanceIndex.mod( width );
  26068. * const posY = instanceIndex.div( width );
  26069. * const indexUV = uvec2( posX, posY );
  26070. *
  26071. * // generate RGB values
  26072. *
  26073. * const r = 1;
  26074. * const g = 1;
  26075. * const b = 1;
  26076. *
  26077. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  26078. *
  26079. * } );
  26080. *
  26081. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  26082. * renderer.computeAsync( computeNode );
  26083. * ```
  26084. *
  26085. * This node can only be used with a WebGPU backend.
  26086. *
  26087. * @augments TextureNode
  26088. */
  26089. class StorageTextureNode extends TextureNode {
  26090. static get type() {
  26091. return 'StorageTextureNode';
  26092. }
  26093. /**
  26094. * Constructs a new storage texture node.
  26095. *
  26096. * @param {StorageTexture} value - The storage texture.
  26097. * @param {Node<vec2|vec3>} uvNode - The uv node.
  26098. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  26099. */
  26100. constructor( value, uvNode, storeNode = null ) {
  26101. super( value, uvNode );
  26102. /**
  26103. * The value node that should be stored in the texture.
  26104. *
  26105. * @type {?Node}
  26106. * @default null
  26107. */
  26108. this.storeNode = storeNode;
  26109. /**
  26110. * The mip level to write to for storage textures.
  26111. *
  26112. * @type {number}
  26113. * @default 0
  26114. */
  26115. this.mipLevel = 0;
  26116. /**
  26117. * This flag can be used for type testing.
  26118. *
  26119. * @type {boolean}
  26120. * @readonly
  26121. * @default true
  26122. */
  26123. this.isStorageTextureNode = true;
  26124. /**
  26125. * The access type of the texture node.
  26126. *
  26127. * @type {string}
  26128. * @default 'writeOnly'
  26129. */
  26130. this.access = NodeAccess.WRITE_ONLY;
  26131. }
  26132. /**
  26133. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  26134. *
  26135. * @param {NodeBuilder} builder - The current node builder.
  26136. * @return {string} The input type.
  26137. */
  26138. getInputType( /*builder*/ ) {
  26139. return 'storageTexture';
  26140. }
  26141. setup( builder ) {
  26142. super.setup( builder );
  26143. const properties = builder.getNodeProperties( this );
  26144. properties.storeNode = this.storeNode;
  26145. return properties;
  26146. }
  26147. /**
  26148. * Defines the node access.
  26149. *
  26150. * @param {string} value - The node access.
  26151. * @return {StorageTextureNode} A reference to this node.
  26152. */
  26153. setAccess( value ) {
  26154. this.access = value;
  26155. return this;
  26156. }
  26157. /**
  26158. * Sets the mip level to write to.
  26159. *
  26160. * @param {number} level - The mip level.
  26161. * @return {StorageTextureNode} A reference to this node.
  26162. */
  26163. setMipLevel( level ) {
  26164. this.mipLevel = level;
  26165. return this;
  26166. }
  26167. /**
  26168. * Generates the code snippet of the storage node. If no `storeNode`
  26169. * is defined, the texture node is generated as normal texture.
  26170. *
  26171. * @param {NodeBuilder} builder - The current node builder.
  26172. * @param {string} output - The current output.
  26173. * @return {string} The generated code snippet.
  26174. */
  26175. generate( builder, output ) {
  26176. let snippet;
  26177. if ( this.storeNode !== null ) {
  26178. snippet = this.generateStore( builder );
  26179. } else {
  26180. snippet = super.generate( builder, output );
  26181. }
  26182. return snippet;
  26183. }
  26184. /**
  26185. * Convenience method for configuring a read/write node access.
  26186. *
  26187. * @return {StorageTextureNode} A reference to this node.
  26188. */
  26189. toReadWrite() {
  26190. return this.setAccess( NodeAccess.READ_WRITE );
  26191. }
  26192. /**
  26193. * Convenience method for configuring a read-only node access.
  26194. *
  26195. * @return {StorageTextureNode} A reference to this node.
  26196. */
  26197. toReadOnly() {
  26198. return this.setAccess( NodeAccess.READ_ONLY );
  26199. }
  26200. /**
  26201. * Convenience method for configuring a write-only node access.
  26202. *
  26203. * @return {StorageTextureNode} A reference to this node.
  26204. */
  26205. toWriteOnly() {
  26206. return this.setAccess( NodeAccess.WRITE_ONLY );
  26207. }
  26208. /**
  26209. * Generates the code snippet of the storage texture node.
  26210. *
  26211. * @param {NodeBuilder} builder - The current node builder.
  26212. */
  26213. generateStore( builder ) {
  26214. const properties = builder.getNodeProperties( this );
  26215. const { uvNode, storeNode, depthNode } = properties;
  26216. const textureProperty = super.generate( builder, 'property' );
  26217. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  26218. const storeSnippet = storeNode.build( builder, 'vec4' );
  26219. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  26220. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  26221. builder.addLineFlowCode( snippet, this );
  26222. }
  26223. clone() {
  26224. const newNode = super.clone();
  26225. newNode.storeNode = this.storeNode;
  26226. newNode.mipLevel = this.mipLevel;
  26227. return newNode;
  26228. }
  26229. }
  26230. /**
  26231. * TSL function for creating a storage texture node.
  26232. *
  26233. * @tsl
  26234. * @function
  26235. * @param {StorageTexture} value - The storage texture.
  26236. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  26237. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  26238. * @returns {StorageTextureNode}
  26239. */
  26240. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  26241. /**
  26242. * TODO: Explain difference to `storageTexture()`.
  26243. *
  26244. * @tsl
  26245. * @function
  26246. * @param {StorageTexture} value - The storage texture.
  26247. * @param {Node<vec2|vec3>} uvNode - The uv node.
  26248. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  26249. * @returns {StorageTextureNode}
  26250. */
  26251. const textureStore = ( value, uvNode, storeNode ) => {
  26252. const node = storageTexture( value, uvNode, storeNode );
  26253. if ( storeNode !== null ) node.toStack();
  26254. return node;
  26255. };
  26256. const normal = Fn( ( { texture, uv } ) => {
  26257. const epsilon = 0.0001;
  26258. const ret = vec3().toVar();
  26259. If( uv.x.lessThan( epsilon ), () => {
  26260. ret.assign( vec3( 1, 0, 0 ) );
  26261. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  26262. ret.assign( vec3( 0, 1, 0 ) );
  26263. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  26264. ret.assign( vec3( 0, 0, 1 ) );
  26265. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  26266. ret.assign( vec3( -1, 0, 0 ) );
  26267. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  26268. ret.assign( vec3( 0, -1, 0 ) );
  26269. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  26270. ret.assign( vec3( 0, 0, -1 ) );
  26271. } ).Else( () => {
  26272. const step = 0.01;
  26273. 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 );
  26274. 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 );
  26275. 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 );
  26276. ret.assign( vec3( x, y, z ) );
  26277. } );
  26278. return ret.normalize();
  26279. } );
  26280. /**
  26281. * This type of uniform node represents a 3D texture.
  26282. *
  26283. * @augments TextureNode
  26284. */
  26285. class Texture3DNode extends TextureNode {
  26286. static get type() {
  26287. return 'Texture3DNode';
  26288. }
  26289. /**
  26290. * Constructs a new 3D texture node.
  26291. *
  26292. * @param {Data3DTexture} value - The 3D texture.
  26293. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  26294. * @param {?Node<int>} [levelNode=null] - The level node.
  26295. */
  26296. constructor( value, uvNode = null, levelNode = null ) {
  26297. super( value, uvNode, levelNode );
  26298. /**
  26299. * This flag can be used for type testing.
  26300. *
  26301. * @type {boolean}
  26302. * @readonly
  26303. * @default true
  26304. */
  26305. this.isTexture3DNode = true;
  26306. }
  26307. /**
  26308. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  26309. *
  26310. * @param {NodeBuilder} builder - The current node builder.
  26311. * @return {string} The input type.
  26312. */
  26313. getInputType( /*builder*/ ) {
  26314. return 'texture3D';
  26315. }
  26316. /**
  26317. * Returns a default uv node which is in context of 3D textures a three-dimensional
  26318. * uv node.
  26319. *
  26320. * @return {Node<vec3>} The default uv node.
  26321. */
  26322. getDefaultUV() {
  26323. return vec3( 0.5, 0.5, 0.5 );
  26324. }
  26325. /**
  26326. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  26327. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  26328. *
  26329. * @param {boolean} value - The update toggle.
  26330. */
  26331. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  26332. /**
  26333. * Overwrites the default implementation to return the unmodified uv node.
  26334. *
  26335. * @param {NodeBuilder} builder - The current node builder.
  26336. * @param {Node} uvNode - The uv node to setup.
  26337. * @return {Node} The unmodified uv node.
  26338. */
  26339. setupUV( builder, uvNode ) {
  26340. const texture = this.value;
  26341. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  26342. if ( this.sampler ) {
  26343. uvNode = uvNode.flipY();
  26344. } else {
  26345. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  26346. }
  26347. }
  26348. return uvNode;
  26349. }
  26350. /**
  26351. * Generates the uv code snippet.
  26352. *
  26353. * @param {NodeBuilder} builder - The current node builder.
  26354. * @param {Node} uvNode - The uv node to generate code for.
  26355. * @return {string} The generated code snippet.
  26356. */
  26357. generateUV( builder, uvNode ) {
  26358. return uvNode.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  26359. }
  26360. /**
  26361. * Generates the offset code snippet.
  26362. *
  26363. * @param {NodeBuilder} builder - The current node builder.
  26364. * @param {Node} offsetNode - The offset node to generate code for.
  26365. * @return {string} The generated code snippet.
  26366. */
  26367. generateOffset( builder, offsetNode ) {
  26368. return offsetNode.build( builder, 'ivec3' );
  26369. }
  26370. /**
  26371. * TODO.
  26372. *
  26373. * @param {Node<vec3>} uvNode - The uv node .
  26374. * @return {Node<vec3>} TODO.
  26375. */
  26376. normal( uvNode ) {
  26377. return normal( { texture: this, uv: uvNode } );
  26378. }
  26379. }
  26380. /**
  26381. * TSL function for creating a 3D texture node.
  26382. *
  26383. * @tsl
  26384. * @function
  26385. * @param {Data3DTexture} value - The 3D texture.
  26386. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  26387. * @param {?Node<int>} [levelNode=null] - The level node.
  26388. * @returns {Texture3DNode}
  26389. */
  26390. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  26391. /**
  26392. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  26393. *
  26394. * @tsl
  26395. * @function
  26396. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  26397. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  26398. * @param {?Node<int>} [levelNode=null] - The level node.
  26399. * @param {?Node<float>} [biasNode=null] - The bias node.
  26400. * @returns {TextureNode}
  26401. */
  26402. const texture3DLoad = ( ...params ) => texture3D( ...params ).setSampler( false );
  26403. /**
  26404. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  26405. *
  26406. * @tsl
  26407. * @function
  26408. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  26409. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  26410. * @param {?Node<int>} [levelNode=null] - The level node.
  26411. * @returns {TextureNode}
  26412. */
  26413. const texture3DLevel = ( value, uvNode, levelNode ) => texture3D( value, uvNode ).level( levelNode );
  26414. /**
  26415. * A special type of reference node that allows to link values in
  26416. * `userData` fields to node objects.
  26417. * ```js
  26418. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  26419. *
  26420. * const material = new THREE.SpriteNodeMaterial();
  26421. * material.rotationNode = userData( 'rotation', 'float' );
  26422. * ```
  26423. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  26424. * will automatically be updated when the `rotation` user data field changes.
  26425. *
  26426. * @augments ReferenceNode
  26427. */
  26428. class UserDataNode extends ReferenceNode {
  26429. static get type() {
  26430. return 'UserDataNode';
  26431. }
  26432. /**
  26433. * Constructs a new user data node.
  26434. *
  26435. * @param {string} property - The property name that should be referenced by the node.
  26436. * @param {string} inputType - The node data type of the reference.
  26437. * @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.
  26438. */
  26439. constructor( property, inputType, userData = null ) {
  26440. super( property, inputType, userData );
  26441. /**
  26442. * A reference to the `userData` object. If not provided, the `userData`
  26443. * property of the 3D object that uses the node material is evaluated.
  26444. *
  26445. * @type {?Object}
  26446. * @default null
  26447. */
  26448. this.userData = userData;
  26449. }
  26450. /**
  26451. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  26452. * `userData` field.
  26453. *
  26454. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  26455. * @return {Object} A reference to the `userData` field.
  26456. */
  26457. updateReference( state ) {
  26458. this.reference = this.userData !== null ? this.userData : state.object.userData;
  26459. return this.reference;
  26460. }
  26461. }
  26462. /**
  26463. * TSL function for creating a user data node.
  26464. *
  26465. * @tsl
  26466. * @function
  26467. * @param {string} name - The property name that should be referenced by the node.
  26468. * @param {string} inputType - The node data type of the reference.
  26469. * @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.
  26470. * @returns {UserDataNode}
  26471. */
  26472. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  26473. const _objectData = new WeakMap();
  26474. /**
  26475. * A node for representing motion or velocity vectors. Foundation
  26476. * for advanced post processing effects like motion blur or TRAA.
  26477. *
  26478. * The node keeps track of the model, view and projection matrices
  26479. * of the previous frame and uses them to compute offsets in NDC space.
  26480. * These offsets represent the final velocity.
  26481. *
  26482. * @augments TempNode
  26483. */
  26484. class VelocityNode extends TempNode {
  26485. static get type() {
  26486. return 'VelocityNode';
  26487. }
  26488. /**
  26489. * Constructs a new vertex color node.
  26490. */
  26491. constructor() {
  26492. super( 'vec2' );
  26493. /**
  26494. * The current projection matrix.
  26495. *
  26496. * @type {?Matrix4}
  26497. * @default null
  26498. */
  26499. this.projectionMatrix = null;
  26500. /**
  26501. * Overwritten since velocity nodes are updated per object.
  26502. *
  26503. * @type {string}
  26504. * @default 'object'
  26505. */
  26506. this.updateType = NodeUpdateType.OBJECT;
  26507. /**
  26508. * Overwritten since velocity nodes save data after the update.
  26509. *
  26510. * @type {string}
  26511. * @default 'object'
  26512. */
  26513. this.updateAfterType = NodeUpdateType.OBJECT;
  26514. /**
  26515. * Uniform node representing the previous model matrix in world space.
  26516. *
  26517. * @type {UniformNode<mat4>}
  26518. * @default null
  26519. */
  26520. this.previousModelWorldMatrix = uniform( new Matrix4() );
  26521. /**
  26522. * Uniform node representing the previous projection matrix.
  26523. *
  26524. * @type {UniformNode<mat4>}
  26525. * @default null
  26526. */
  26527. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  26528. /**
  26529. * Uniform node representing the previous view matrix.
  26530. *
  26531. * @type {UniformNode<mat4>}
  26532. * @default null
  26533. */
  26534. this.previousCameraViewMatrix = uniform( new Matrix4() );
  26535. }
  26536. /**
  26537. * Sets the given projection matrix.
  26538. *
  26539. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  26540. */
  26541. setProjectionMatrix( projectionMatrix ) {
  26542. this.projectionMatrix = projectionMatrix;
  26543. }
  26544. /**
  26545. * Updates velocity specific uniforms.
  26546. *
  26547. * @param {NodeFrame} frame - A reference to the current node frame.
  26548. */
  26549. update( { frameId, camera, object } ) {
  26550. const previousModelMatrix = getPreviousMatrix( object );
  26551. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  26552. //
  26553. const cameraData = getData( camera );
  26554. if ( cameraData.frameId !== frameId ) {
  26555. cameraData.frameId = frameId;
  26556. if ( cameraData.previousProjectionMatrix === undefined ) {
  26557. cameraData.previousProjectionMatrix = new Matrix4();
  26558. cameraData.previousCameraViewMatrix = new Matrix4();
  26559. cameraData.currentProjectionMatrix = new Matrix4();
  26560. cameraData.currentCameraViewMatrix = new Matrix4();
  26561. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  26562. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  26563. } else {
  26564. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  26565. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  26566. }
  26567. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  26568. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  26569. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  26570. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  26571. }
  26572. }
  26573. /**
  26574. * Overwritten to updated velocity specific uniforms.
  26575. *
  26576. * @param {NodeFrame} frame - A reference to the current node frame.
  26577. */
  26578. updateAfter( { object } ) {
  26579. getPreviousMatrix( object ).copy( object.matrixWorld );
  26580. }
  26581. /**
  26582. * Implements the velocity computation based on the previous and current vertex data.
  26583. *
  26584. * @param {NodeBuilder} builder - A reference to the current node builder.
  26585. * @return {Node<vec2>} The motion vector.
  26586. */
  26587. setup( /*builder*/ ) {
  26588. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  26589. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  26590. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  26591. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  26592. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  26593. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  26594. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  26595. return velocity;
  26596. }
  26597. }
  26598. function getData( object ) {
  26599. let objectData = _objectData.get( object );
  26600. if ( objectData === undefined ) {
  26601. objectData = {};
  26602. _objectData.set( object, objectData );
  26603. }
  26604. return objectData;
  26605. }
  26606. function getPreviousMatrix( object, index = 0 ) {
  26607. const objectData = getData( object );
  26608. let matrix = objectData[ index ];
  26609. if ( matrix === undefined ) {
  26610. objectData[ index ] = matrix = new Matrix4();
  26611. objectData[ index ].copy( object.matrixWorld );
  26612. }
  26613. return matrix;
  26614. }
  26615. /**
  26616. * TSL object that represents the velocity of a render pass.
  26617. *
  26618. * @tsl
  26619. * @type {VelocityNode}
  26620. */
  26621. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  26622. /**
  26623. * Computes a grayscale value for the given RGB color value.
  26624. *
  26625. * @tsl
  26626. * @function
  26627. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  26628. * @return {Node<vec3>} The grayscale color.
  26629. */
  26630. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  26631. return luminance( color.rgb );
  26632. } );
  26633. /**
  26634. * Super-saturates or desaturates the given RGB color.
  26635. *
  26636. * @tsl
  26637. * @function
  26638. * @param {Node<vec3>} color - The input color.
  26639. * @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.
  26640. * @return {Node<vec3>} The saturated color.
  26641. */
  26642. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  26643. return adjustment.mix( luminance( color.rgb ), color.rgb );
  26644. } );
  26645. /**
  26646. * Selectively enhance the intensity of less saturated RGB colors. Can result
  26647. * in a more natural and visually appealing image with enhanced color depth
  26648. * compared to {@link ColorAdjustment#saturation}.
  26649. *
  26650. * @tsl
  26651. * @function
  26652. * @param {Node<vec3>} color - The input color.
  26653. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  26654. * @return {Node<vec3>} The updated color.
  26655. */
  26656. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  26657. const average = add( color.r, color.g, color.b ).div( 3.0 );
  26658. const mx = color.r.max( color.g.max( color.b ) );
  26659. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  26660. return mix( color.rgb, mx, amt );
  26661. } );
  26662. /**
  26663. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  26664. *
  26665. * @tsl
  26666. * @function
  26667. * @param {Node<vec3>} color - The input color.
  26668. * @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.
  26669. * @return {Node<vec3>} The updated color.
  26670. */
  26671. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  26672. const k = vec3( 0.57735, 0.57735, 0.57735 );
  26673. const cosAngle = adjustment.cos();
  26674. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  26675. } );
  26676. /**
  26677. * Computes the luminance for the given RGB color value.
  26678. *
  26679. * @tsl
  26680. * @function
  26681. * @param {Node<vec3>} color - The color value to compute the luminance for.
  26682. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  26683. * @return {Node<float>} The luminance.
  26684. */
  26685. const luminance = (
  26686. color,
  26687. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  26688. ) => dot( color, luminanceCoefficients );
  26689. /**
  26690. * Color Decision List (CDL) v1.2
  26691. *
  26692. * Compact representation of color grading information, defined by slope, offset, power, and
  26693. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  26694. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  26695. *
  26696. * @tsl
  26697. * @function
  26698. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  26699. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  26700. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  26701. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  26702. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  26703. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  26704. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  26705. *
  26706. * References:
  26707. * - ASC CDL v1.2
  26708. * - {@link https://blender.stackexchange.com/a/55239/43930}
  26709. * - {@link https://docs.acescentral.com/specifications/acescc/}
  26710. */
  26711. const cdl = /*@__PURE__*/ Fn( ( [
  26712. color,
  26713. slope = vec3( 1 ),
  26714. offset = vec3( 0 ),
  26715. power = vec3( 1 ),
  26716. saturation = float( 1 ),
  26717. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  26718. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  26719. ] ) => {
  26720. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  26721. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  26722. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  26723. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  26724. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  26725. const pv = v.pow( power ).toVar();
  26726. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  26727. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  26728. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  26729. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  26730. return vec4( v.rgb, color.a );
  26731. } );
  26732. /**
  26733. * Represents a posterize effect which reduces the number of colors
  26734. * in an image, resulting in a more blocky and stylized appearance.
  26735. *
  26736. * @augments TempNode
  26737. */
  26738. class PosterizeNode extends TempNode {
  26739. static get type() {
  26740. return 'PosterizeNode';
  26741. }
  26742. /**
  26743. * Constructs a new posterize node.
  26744. *
  26745. * @param {Node} sourceNode - The input color.
  26746. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  26747. */
  26748. constructor( sourceNode, stepsNode ) {
  26749. super();
  26750. /**
  26751. * The input color.
  26752. *
  26753. * @type {Node}
  26754. */
  26755. this.sourceNode = sourceNode;
  26756. /**
  26757. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  26758. *
  26759. * @type {Node}
  26760. */
  26761. this.stepsNode = stepsNode;
  26762. }
  26763. setup() {
  26764. const { sourceNode, stepsNode } = this;
  26765. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  26766. }
  26767. }
  26768. /**
  26769. * TSL function for creating a posterize node.
  26770. *
  26771. * @tsl
  26772. * @function
  26773. * @param {Node} sourceNode - The input color.
  26774. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  26775. * @returns {PosterizeNode}
  26776. */
  26777. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  26778. const _size = /*@__PURE__*/ new Vector2();
  26779. /**
  26780. * Represents the texture of a pass node.
  26781. *
  26782. * @augments TextureNode
  26783. */
  26784. class PassTextureNode extends TextureNode {
  26785. static get type() {
  26786. return 'PassTextureNode';
  26787. }
  26788. /**
  26789. * Constructs a new pass texture node.
  26790. *
  26791. * @param {PassNode} passNode - The pass node.
  26792. * @param {Texture} texture - The output texture.
  26793. */
  26794. constructor( passNode, texture ) {
  26795. super( texture );
  26796. /**
  26797. * A reference to the pass node.
  26798. *
  26799. * @type {PassNode}
  26800. */
  26801. this.passNode = passNode;
  26802. this.setUpdateMatrix( false );
  26803. }
  26804. setup( builder ) {
  26805. this.passNode.build( builder );
  26806. return super.setup( builder );
  26807. }
  26808. clone() {
  26809. return new this.constructor( this.passNode, this.value );
  26810. }
  26811. }
  26812. /**
  26813. * An extension of `PassTextureNode` which allows to manage more than one
  26814. * internal texture. Relevant for the `getPreviousTexture()` related API.
  26815. *
  26816. * @augments PassTextureNode
  26817. */
  26818. class PassMultipleTextureNode extends PassTextureNode {
  26819. static get type() {
  26820. return 'PassMultipleTextureNode';
  26821. }
  26822. /**
  26823. * Constructs a new pass texture node.
  26824. *
  26825. * @param {PassNode} passNode - The pass node.
  26826. * @param {string} textureName - The output texture name.
  26827. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  26828. */
  26829. constructor( passNode, textureName, previousTexture = false ) {
  26830. // null is passed to the super call since this class does not
  26831. // use an external texture for rendering pass data into. Instead
  26832. // the texture is managed by the pass node itself
  26833. super( passNode, null );
  26834. /**
  26835. * The output texture name.
  26836. *
  26837. * @type {string}
  26838. */
  26839. this.textureName = textureName;
  26840. /**
  26841. * Whether previous frame data should be used or not.
  26842. *
  26843. * @type {boolean}
  26844. */
  26845. this.previousTexture = previousTexture;
  26846. }
  26847. /**
  26848. * Updates the texture reference of this node.
  26849. */
  26850. updateTexture() {
  26851. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  26852. }
  26853. setup( builder ) {
  26854. this.updateTexture();
  26855. return super.setup( builder );
  26856. }
  26857. clone() {
  26858. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  26859. newNode.uvNode = this.uvNode;
  26860. newNode.levelNode = this.levelNode;
  26861. newNode.biasNode = this.biasNode;
  26862. newNode.sampler = this.sampler;
  26863. newNode.depthNode = this.depthNode;
  26864. newNode.compareNode = this.compareNode;
  26865. newNode.gradNode = this.gradNode;
  26866. newNode.offsetNode = this.offsetNode;
  26867. return newNode;
  26868. }
  26869. }
  26870. /**
  26871. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  26872. * This pass produces a render for the given scene and camera and can provide multiple outputs
  26873. * via MRT for further processing.
  26874. *
  26875. * ```js
  26876. * const postProcessing = new PostProcessing( renderer );
  26877. *
  26878. * const scenePass = pass( scene, camera );
  26879. *
  26880. * postProcessing.outputNode = scenePass;
  26881. * ```
  26882. *
  26883. * @augments TempNode
  26884. */
  26885. class PassNode extends TempNode {
  26886. static get type() {
  26887. return 'PassNode';
  26888. }
  26889. /**
  26890. * Constructs a new pass node.
  26891. *
  26892. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  26893. * @param {Scene} scene - A reference to the scene.
  26894. * @param {Camera} camera - A reference to the camera.
  26895. * @param {Object} options - Options for the internal render target.
  26896. */
  26897. constructor( scope, scene, camera, options = {} ) {
  26898. super( 'vec4' );
  26899. /**
  26900. * The scope of the pass. The scope determines whether the node outputs color or depth.
  26901. *
  26902. * @type {('color'|'depth')}
  26903. */
  26904. this.scope = scope;
  26905. /**
  26906. * A reference to the scene.
  26907. *
  26908. * @type {Scene}
  26909. */
  26910. this.scene = scene;
  26911. /**
  26912. * A reference to the camera.
  26913. *
  26914. * @type {Camera}
  26915. */
  26916. this.camera = camera;
  26917. /**
  26918. * Options for the internal render target.
  26919. *
  26920. * @type {Object}
  26921. */
  26922. this.options = options;
  26923. /**
  26924. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  26925. *
  26926. * @private
  26927. * @type {number}
  26928. * @default 1
  26929. */
  26930. this._pixelRatio = 1;
  26931. /**
  26932. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  26933. * @private
  26934. * @type {number}
  26935. * @default 1
  26936. */
  26937. this._width = 1;
  26938. /**
  26939. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  26940. * @private
  26941. * @type {number}
  26942. * @default 1
  26943. */
  26944. this._height = 1;
  26945. const depthTexture = new DepthTexture();
  26946. depthTexture.isRenderTargetTexture = true;
  26947. //depthTexture.type = FloatType;
  26948. depthTexture.name = 'depth';
  26949. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  26950. renderTarget.texture.name = 'output';
  26951. renderTarget.depthTexture = depthTexture;
  26952. /**
  26953. * The pass's render target.
  26954. *
  26955. * @type {RenderTarget}
  26956. */
  26957. this.renderTarget = renderTarget;
  26958. /**
  26959. * An optional override material for the pass.
  26960. *
  26961. * @type {Material|null}
  26962. */
  26963. this.overrideMaterial = null;
  26964. /**
  26965. * Whether the pass is transparent.
  26966. *
  26967. * @type {boolean}
  26968. * @default false
  26969. */
  26970. this.transparent = true;
  26971. /**
  26972. * Whether the pass is opaque.
  26973. *
  26974. * @type {boolean}
  26975. * @default true
  26976. */
  26977. this.opaque = true;
  26978. /**
  26979. * An optional global context for the pass.
  26980. *
  26981. * @type {ContextNode|null}
  26982. */
  26983. this.contextNode = null;
  26984. /**
  26985. * A cache for the context node.
  26986. *
  26987. * @private
  26988. * @type {?Object}
  26989. * @default null
  26990. */
  26991. this._contextNodeCache = null;
  26992. /**
  26993. * A dictionary holding the internal result textures.
  26994. *
  26995. * @private
  26996. * @type {Object<string, Texture>}
  26997. */
  26998. this._textures = {
  26999. output: renderTarget.texture,
  27000. depth: depthTexture
  27001. };
  27002. /**
  27003. * A dictionary holding the internal texture nodes.
  27004. *
  27005. * @private
  27006. * @type {Object<string, TextureNode>}
  27007. */
  27008. this._textureNodes = {};
  27009. /**
  27010. * A dictionary holding the internal depth nodes.
  27011. *
  27012. * @private
  27013. * @type {Object}
  27014. */
  27015. this._linearDepthNodes = {};
  27016. /**
  27017. * A dictionary holding the internal viewZ nodes.
  27018. *
  27019. * @private
  27020. * @type {Object}
  27021. */
  27022. this._viewZNodes = {};
  27023. /**
  27024. * A dictionary holding the texture data of the previous frame.
  27025. * Used for computing velocity/motion vectors.
  27026. *
  27027. * @private
  27028. * @type {Object<string, Texture>}
  27029. */
  27030. this._previousTextures = {};
  27031. /**
  27032. * A dictionary holding the texture nodes of the previous frame.
  27033. * Used for computing velocity/motion vectors.
  27034. *
  27035. * @private
  27036. * @type {Object<string, TextureNode>}
  27037. */
  27038. this._previousTextureNodes = {};
  27039. /**
  27040. * The `near` property of the camera as a uniform.
  27041. *
  27042. * @private
  27043. * @type {UniformNode}
  27044. */
  27045. this._cameraNear = uniform( 0 );
  27046. /**
  27047. * The `far` property of the camera as a uniform.
  27048. *
  27049. * @private
  27050. * @type {UniformNode}
  27051. */
  27052. this._cameraFar = uniform( 0 );
  27053. /**
  27054. * A MRT node configuring the MRT settings.
  27055. *
  27056. * @private
  27057. * @type {?MRTNode}
  27058. * @default null
  27059. */
  27060. this._mrt = null;
  27061. /**
  27062. * Layer object for configuring the camera that is used
  27063. * to produce the pass.
  27064. *
  27065. * @private
  27066. * @type {?Layers}
  27067. * @default null
  27068. */
  27069. this._layers = null;
  27070. /**
  27071. * Scales the resolution of the internal render target.
  27072. *
  27073. * @private
  27074. * @type {number}
  27075. * @default 1
  27076. */
  27077. this._resolutionScale = 1;
  27078. /**
  27079. * Custom viewport definition.
  27080. *
  27081. * @private
  27082. * @type {?Vector4}
  27083. * @default null
  27084. */
  27085. this._viewport = null;
  27086. /**
  27087. * Custom scissor definition.
  27088. *
  27089. * @private
  27090. * @type {?Vector4}
  27091. * @default null
  27092. */
  27093. this._scissor = null;
  27094. /**
  27095. * This flag can be used for type testing.
  27096. *
  27097. * @type {boolean}
  27098. * @readonly
  27099. * @default true
  27100. */
  27101. this.isPassNode = true;
  27102. /**
  27103. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  27104. * scene once per frame in its {@link PassNode#updateBefore} method.
  27105. *
  27106. * @type {string}
  27107. * @default 'frame'
  27108. */
  27109. this.updateBeforeType = NodeUpdateType.FRAME;
  27110. /**
  27111. * This flag is used for global cache.
  27112. *
  27113. * @type {boolean}
  27114. * @default true
  27115. */
  27116. this.global = true;
  27117. }
  27118. /**
  27119. * Sets the resolution scale for the pass.
  27120. * The resolution scale is a factor that is multiplied with the renderer's width and height.
  27121. *
  27122. * @param {number} resolutionScale - The resolution scale to set. A value of `1` means full resolution.
  27123. * @return {PassNode} A reference to this pass.
  27124. */
  27125. setResolutionScale( resolutionScale ) {
  27126. this._resolutionScale = resolutionScale;
  27127. return this;
  27128. }
  27129. /**
  27130. * Gets the current resolution scale of the pass.
  27131. *
  27132. * @return {number} The current resolution scale. A value of `1` means full resolution.
  27133. */
  27134. getResolutionScale() {
  27135. return this._resolutionScale;
  27136. }
  27137. /**
  27138. * Sets the resolution for the pass.
  27139. * The resolution is a factor that is multiplied with the renderer's width and height.
  27140. *
  27141. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  27142. * @return {PassNode} A reference to this pass.
  27143. * @deprecated since r181. Use {@link PassNode#setResolutionScale `setResolutionScale()`} instead.
  27144. */
  27145. setResolution( resolution ) { // @deprecated, r181
  27146. warn( 'PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead.' );
  27147. return this.setResolutionScale( resolution );
  27148. }
  27149. /**
  27150. * Gets the current resolution of the pass.
  27151. *
  27152. * @return {number} The current resolution. A value of `1` means full resolution.
  27153. * @deprecated since r181. Use {@link PassNode#getResolutionScale `getResolutionScale()`} instead.
  27154. */
  27155. getResolution() { // @deprecated, r181
  27156. warn( 'PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead.' );
  27157. return this.getResolutionScale();
  27158. }
  27159. /**
  27160. * Sets the layer configuration that should be used when rendering the pass.
  27161. *
  27162. * @param {Layers} layers - The layers object to set.
  27163. * @return {PassNode} A reference to this pass.
  27164. */
  27165. setLayers( layers ) {
  27166. this._layers = layers;
  27167. return this;
  27168. }
  27169. /**
  27170. * Gets the current layer configuration of the pass.
  27171. *
  27172. * @return {?Layers} .
  27173. */
  27174. getLayers() {
  27175. return this._layers;
  27176. }
  27177. /**
  27178. * Sets the given MRT node to setup MRT for this pass.
  27179. *
  27180. * @param {MRTNode} mrt - The MRT object.
  27181. * @return {PassNode} A reference to this pass.
  27182. */
  27183. setMRT( mrt ) {
  27184. this._mrt = mrt;
  27185. return this;
  27186. }
  27187. /**
  27188. * Returns the current MRT node.
  27189. *
  27190. * @return {MRTNode} The current MRT node.
  27191. */
  27192. getMRT() {
  27193. return this._mrt;
  27194. }
  27195. /**
  27196. * Returns the texture for the given output name.
  27197. *
  27198. * @param {string} name - The output name to get the texture for.
  27199. * @return {Texture} The texture.
  27200. */
  27201. getTexture( name ) {
  27202. let texture = this._textures[ name ];
  27203. if ( texture === undefined ) {
  27204. const refTexture = this.renderTarget.texture;
  27205. texture = refTexture.clone();
  27206. texture.name = name;
  27207. this._textures[ name ] = texture;
  27208. this.renderTarget.textures.push( texture );
  27209. }
  27210. return texture;
  27211. }
  27212. /**
  27213. * Returns the texture holding the data of the previous frame for the given output name.
  27214. *
  27215. * @param {string} name - The output name to get the texture for.
  27216. * @return {Texture} The texture holding the data of the previous frame.
  27217. */
  27218. getPreviousTexture( name ) {
  27219. let texture = this._previousTextures[ name ];
  27220. if ( texture === undefined ) {
  27221. texture = this.getTexture( name ).clone();
  27222. this._previousTextures[ name ] = texture;
  27223. }
  27224. return texture;
  27225. }
  27226. /**
  27227. * Switches current and previous textures for the given output name.
  27228. *
  27229. * @param {string} name - The output name.
  27230. */
  27231. toggleTexture( name ) {
  27232. const prevTexture = this._previousTextures[ name ];
  27233. if ( prevTexture !== undefined ) {
  27234. const texture = this._textures[ name ];
  27235. const index = this.renderTarget.textures.indexOf( texture );
  27236. this.renderTarget.textures[ index ] = prevTexture;
  27237. this._textures[ name ] = prevTexture;
  27238. this._previousTextures[ name ] = texture;
  27239. this._textureNodes[ name ].updateTexture();
  27240. this._previousTextureNodes[ name ].updateTexture();
  27241. }
  27242. }
  27243. /**
  27244. * Returns the texture node for the given output name.
  27245. *
  27246. * @param {string} [name='output'] - The output name to get the texture node for.
  27247. * @return {TextureNode} The texture node.
  27248. */
  27249. getTextureNode( name = 'output' ) {
  27250. let textureNode = this._textureNodes[ name ];
  27251. if ( textureNode === undefined ) {
  27252. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  27253. textureNode.updateTexture();
  27254. this._textureNodes[ name ] = textureNode;
  27255. }
  27256. return textureNode;
  27257. }
  27258. /**
  27259. * Returns the previous texture node for the given output name.
  27260. *
  27261. * @param {string} [name='output'] - The output name to get the previous texture node for.
  27262. * @return {TextureNode} The previous texture node.
  27263. */
  27264. getPreviousTextureNode( name = 'output' ) {
  27265. let textureNode = this._previousTextureNodes[ name ];
  27266. if ( textureNode === undefined ) {
  27267. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  27268. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  27269. textureNode.updateTexture();
  27270. this._previousTextureNodes[ name ] = textureNode;
  27271. }
  27272. return textureNode;
  27273. }
  27274. /**
  27275. * Returns a viewZ node of this pass.
  27276. *
  27277. * @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.
  27278. * @return {Node} The viewZ node.
  27279. */
  27280. getViewZNode( name = 'depth' ) {
  27281. let viewZNode = this._viewZNodes[ name ];
  27282. if ( viewZNode === undefined ) {
  27283. const cameraNear = this._cameraNear;
  27284. const cameraFar = this._cameraFar;
  27285. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  27286. }
  27287. return viewZNode;
  27288. }
  27289. /**
  27290. * Returns a linear depth node of this pass.
  27291. *
  27292. * @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.
  27293. * @return {Node} The linear depth node.
  27294. */
  27295. getLinearDepthNode( name = 'depth' ) {
  27296. let linearDepthNode = this._linearDepthNodes[ name ];
  27297. if ( linearDepthNode === undefined ) {
  27298. const cameraNear = this._cameraNear;
  27299. const cameraFar = this._cameraFar;
  27300. const viewZNode = this.getViewZNode( name );
  27301. // TODO: just if ( builder.camera.isPerspectiveCamera )
  27302. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  27303. }
  27304. return linearDepthNode;
  27305. }
  27306. /**
  27307. * Precompiles the pass.
  27308. *
  27309. * Note that this method must be called after the pass configuration is complete.
  27310. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  27311. *
  27312. * @async
  27313. * @param {Renderer} renderer - The renderer.
  27314. * @return {Promise} A Promise that resolves when the compile has been finished.
  27315. * @see {@link Renderer#compileAsync}
  27316. */
  27317. async compileAsync( renderer ) {
  27318. const currentRenderTarget = renderer.getRenderTarget();
  27319. const currentMRT = renderer.getMRT();
  27320. renderer.setRenderTarget( this.renderTarget );
  27321. renderer.setMRT( this._mrt );
  27322. await renderer.compileAsync( this.scene, this.camera );
  27323. renderer.setRenderTarget( currentRenderTarget );
  27324. renderer.setMRT( currentMRT );
  27325. }
  27326. setup( { renderer } ) {
  27327. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  27328. this.renderTarget.texture.type = renderer.getColorBufferType();
  27329. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  27330. }
  27331. updateBefore( frame ) {
  27332. const { renderer } = frame;
  27333. const { scene } = this;
  27334. let camera;
  27335. let pixelRatio;
  27336. const outputRenderTarget = renderer.getOutputRenderTarget();
  27337. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  27338. pixelRatio = 1;
  27339. camera = renderer.xr.getCamera();
  27340. renderer.xr.updateCamera( camera );
  27341. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  27342. } else {
  27343. camera = this.camera;
  27344. pixelRatio = renderer.getPixelRatio();
  27345. renderer.getSize( _size );
  27346. }
  27347. this._pixelRatio = pixelRatio;
  27348. this.setSize( _size.width, _size.height );
  27349. const currentRenderTarget = renderer.getRenderTarget();
  27350. const currentMRT = renderer.getMRT();
  27351. const currentAutoClear = renderer.autoClear;
  27352. const currentTransparent = renderer.transparent;
  27353. const currentOpaque = renderer.opaque;
  27354. const currentMask = camera.layers.mask;
  27355. const currentContextNode = renderer.contextNode;
  27356. const currentOverrideMaterial = scene.overrideMaterial;
  27357. this._cameraNear.value = camera.near;
  27358. this._cameraFar.value = camera.far;
  27359. if ( this._layers !== null ) {
  27360. camera.layers.mask = this._layers.mask;
  27361. }
  27362. for ( const name in this._previousTextures ) {
  27363. this.toggleTexture( name );
  27364. }
  27365. if ( this.overrideMaterial !== null ) {
  27366. scene.overrideMaterial = this.overrideMaterial;
  27367. }
  27368. renderer.setRenderTarget( this.renderTarget );
  27369. renderer.setMRT( this._mrt );
  27370. renderer.autoClear = true;
  27371. renderer.transparent = this.transparent;
  27372. renderer.opaque = this.opaque;
  27373. if ( this.contextNode !== null ) {
  27374. if ( this._contextNodeCache === null || this._contextNodeCache.version !== this.version ) {
  27375. this._contextNodeCache = {
  27376. version: this.version,
  27377. context: context( { ...renderer.contextNode.getFlowContextData(), ...this.contextNode.getFlowContextData() } )
  27378. };
  27379. }
  27380. renderer.contextNode = this._contextNodeCache.context;
  27381. }
  27382. const currentSceneName = scene.name;
  27383. scene.name = this.name ? this.name : scene.name;
  27384. renderer.render( scene, camera );
  27385. scene.name = currentSceneName;
  27386. scene.overrideMaterial = currentOverrideMaterial;
  27387. renderer.setRenderTarget( currentRenderTarget );
  27388. renderer.setMRT( currentMRT );
  27389. renderer.autoClear = currentAutoClear;
  27390. renderer.transparent = currentTransparent;
  27391. renderer.opaque = currentOpaque;
  27392. renderer.contextNode = currentContextNode;
  27393. camera.layers.mask = currentMask;
  27394. }
  27395. /**
  27396. * Sets the size of the pass's render target. Honors the pixel ratio.
  27397. *
  27398. * @param {number} width - The width to set.
  27399. * @param {number} height - The height to set.
  27400. */
  27401. setSize( width, height ) {
  27402. this._width = width;
  27403. this._height = height;
  27404. const effectiveWidth = Math.floor( this._width * this._pixelRatio * this._resolutionScale );
  27405. const effectiveHeight = Math.floor( this._height * this._pixelRatio * this._resolutionScale );
  27406. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  27407. if ( this._scissor !== null ) this.renderTarget.scissor.copy( this._scissor );
  27408. if ( this._viewport !== null ) this.renderTarget.viewport.copy( this._viewport );
  27409. }
  27410. /**
  27411. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  27412. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  27413. * with `null` as the single argument.
  27414. *
  27415. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  27416. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  27417. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  27418. * @param {number} width - The width of the scissor box in logical pixel unit.
  27419. * @param {number} height - The height of the scissor box in logical pixel unit.
  27420. */
  27421. setScissor( x, y, width, height ) {
  27422. if ( x === null ) {
  27423. this._scissor = null;
  27424. } else {
  27425. if ( this._scissor === null ) this._scissor = new Vector4();
  27426. if ( x.isVector4 ) {
  27427. this._scissor.copy( x );
  27428. } else {
  27429. this._scissor.set( x, y, width, height );
  27430. }
  27431. this._scissor.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  27432. }
  27433. }
  27434. /**
  27435. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  27436. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  27437. * with `null` as the single argument.
  27438. *
  27439. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  27440. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  27441. * @param {number} width - The width of the viewport in logical pixel unit.
  27442. * @param {number} height - The height of the viewport in logical pixel unit.
  27443. */
  27444. setViewport( x, y, width, height ) {
  27445. if ( x === null ) {
  27446. this._viewport = null;
  27447. } else {
  27448. if ( this._viewport === null ) this._viewport = new Vector4();
  27449. if ( x.isVector4 ) {
  27450. this._viewport.copy( x );
  27451. } else {
  27452. this._viewport.set( x, y, width, height );
  27453. }
  27454. this._viewport.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  27455. }
  27456. }
  27457. /**
  27458. * Sets the pixel ratio the pass's render target and updates the size.
  27459. *
  27460. * @param {number} pixelRatio - The pixel ratio to set.
  27461. */
  27462. setPixelRatio( pixelRatio ) {
  27463. this._pixelRatio = pixelRatio;
  27464. this.setSize( this._width, this._height );
  27465. }
  27466. /**
  27467. * Frees internal resources. Should be called when the node is no longer in use.
  27468. */
  27469. dispose() {
  27470. this.renderTarget.dispose();
  27471. }
  27472. }
  27473. /**
  27474. * @static
  27475. * @type {'color'}
  27476. * @default 'color'
  27477. */
  27478. PassNode.COLOR = 'color';
  27479. /**
  27480. * @static
  27481. * @type {'depth'}
  27482. * @default 'depth'
  27483. */
  27484. PassNode.DEPTH = 'depth';
  27485. /**
  27486. * TSL function for creating a pass node.
  27487. *
  27488. * @tsl
  27489. * @function
  27490. * @param {Scene} scene - A reference to the scene.
  27491. * @param {Camera} camera - A reference to the camera.
  27492. * @param {Object} options - Options for the internal render target.
  27493. * @returns {PassNode}
  27494. */
  27495. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  27496. /**
  27497. * TSL function for creating a pass texture node.
  27498. *
  27499. * @tsl
  27500. * @function
  27501. * @param {PassNode} pass - The pass node.
  27502. * @param {Texture} texture - The output texture.
  27503. * @returns {PassTextureNode}
  27504. */
  27505. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  27506. /**
  27507. * TSL function for creating a depth pass node.
  27508. *
  27509. * @tsl
  27510. * @function
  27511. * @param {Scene} scene - A reference to the scene.
  27512. * @param {Camera} camera - A reference to the camera.
  27513. * @param {Object} options - Options for the internal render target.
  27514. * @returns {PassNode}
  27515. */
  27516. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  27517. /**
  27518. * Represents a render pass for producing a toon outline effect on compatible objects.
  27519. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  27520. * will receive the outline.
  27521. *
  27522. * ```js
  27523. * const postProcessing = new PostProcessing( renderer );
  27524. *
  27525. * const scenePass = toonOutlinePass( scene, camera );
  27526. *
  27527. * postProcessing.outputNode = scenePass;
  27528. * ```
  27529. * @augments PassNode
  27530. */
  27531. class ToonOutlinePassNode extends PassNode {
  27532. static get type() {
  27533. return 'ToonOutlinePassNode';
  27534. }
  27535. /**
  27536. * Constructs a new outline pass node.
  27537. *
  27538. * @param {Scene} scene - A reference to the scene.
  27539. * @param {Camera} camera - A reference to the camera.
  27540. * @param {Node} colorNode - Defines the outline's color.
  27541. * @param {Node} thicknessNode - Defines the outline's thickness.
  27542. * @param {Node} alphaNode - Defines the outline's alpha.
  27543. */
  27544. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  27545. super( PassNode.COLOR, scene, camera );
  27546. /**
  27547. * Defines the outline's color.
  27548. *
  27549. * @type {Node}
  27550. */
  27551. this.colorNode = colorNode;
  27552. /**
  27553. * Defines the outline's thickness.
  27554. *
  27555. * @type {Node}
  27556. */
  27557. this.thicknessNode = thicknessNode;
  27558. /**
  27559. * Defines the outline's alpha.
  27560. *
  27561. * @type {Node}
  27562. */
  27563. this.alphaNode = alphaNode;
  27564. /**
  27565. * An internal material cache.
  27566. *
  27567. * @private
  27568. * @type {WeakMap<Material, NodeMaterial>}
  27569. */
  27570. this._materialCache = new WeakMap();
  27571. /**
  27572. * The name of this pass.
  27573. *
  27574. * @type {string}
  27575. * @default 'Outline Pass'
  27576. */
  27577. this.name = 'Outline Pass';
  27578. }
  27579. updateBefore( frame ) {
  27580. const { renderer } = frame;
  27581. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  27582. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  27583. // only render outline for supported materials
  27584. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  27585. if ( material.wireframe === false ) {
  27586. const outlineMaterial = this._getOutlineMaterial( material );
  27587. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  27588. }
  27589. }
  27590. // default
  27591. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  27592. } );
  27593. super.updateBefore( frame );
  27594. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  27595. }
  27596. /**
  27597. * Creates the material used for outline rendering.
  27598. *
  27599. * @private
  27600. * @return {NodeMaterial} The outline material.
  27601. */
  27602. _createMaterial() {
  27603. const material = new NodeMaterial();
  27604. material.isMeshToonOutlineMaterial = true;
  27605. material.name = 'Toon_Outline';
  27606. material.side = BackSide;
  27607. // vertex node
  27608. const outlineNormal = normalLocal.negate();
  27609. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  27610. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  27611. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  27612. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  27613. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  27614. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  27615. // color node
  27616. material.colorNode = vec4( this.colorNode, this.alphaNode );
  27617. return material;
  27618. }
  27619. /**
  27620. * For the given toon material, this method returns a corresponding
  27621. * outline material.
  27622. *
  27623. * @private
  27624. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  27625. * @return {NodeMaterial} The outline material.
  27626. */
  27627. _getOutlineMaterial( originalMaterial ) {
  27628. let outlineMaterial = this._materialCache.get( originalMaterial );
  27629. if ( outlineMaterial === undefined ) {
  27630. outlineMaterial = this._createMaterial();
  27631. this._materialCache.set( originalMaterial, outlineMaterial );
  27632. }
  27633. return outlineMaterial;
  27634. }
  27635. }
  27636. /**
  27637. * TSL function for creating a toon outline pass node.
  27638. *
  27639. * @tsl
  27640. * @function
  27641. * @param {Scene} scene - A reference to the scene.
  27642. * @param {Camera} camera - A reference to the camera.
  27643. * @param {Color} color - Defines the outline's color.
  27644. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  27645. * @param {number} [alpha=1] - Defines the outline's alpha.
  27646. * @returns {ToonOutlinePassNode}
  27647. */
  27648. 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 ) ) );
  27649. /**
  27650. * Linear tone mapping, exposure only.
  27651. *
  27652. * @tsl
  27653. * @function
  27654. * @param {Node<vec3>} color - The color that should be tone mapped.
  27655. * @param {Node<float>} exposure - The exposure.
  27656. * @return {Node<vec3>} The tone mapped color.
  27657. */
  27658. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27659. return color.mul( exposure ).clamp();
  27660. } ).setLayout( {
  27661. name: 'linearToneMapping',
  27662. type: 'vec3',
  27663. inputs: [
  27664. { name: 'color', type: 'vec3' },
  27665. { name: 'exposure', type: 'float' }
  27666. ]
  27667. } );
  27668. /**
  27669. * Reinhard tone mapping.
  27670. *
  27671. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  27672. *
  27673. * @tsl
  27674. * @function
  27675. * @param {Node<vec3>} color - The color that should be tone mapped.
  27676. * @param {Node<float>} exposure - The exposure.
  27677. * @return {Node<vec3>} The tone mapped color.
  27678. */
  27679. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27680. color = color.mul( exposure );
  27681. return color.div( color.add( 1.0 ) ).clamp();
  27682. } ).setLayout( {
  27683. name: 'reinhardToneMapping',
  27684. type: 'vec3',
  27685. inputs: [
  27686. { name: 'color', type: 'vec3' },
  27687. { name: 'exposure', type: 'float' }
  27688. ]
  27689. } );
  27690. /**
  27691. * Cineon tone mapping.
  27692. *
  27693. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  27694. *
  27695. * @tsl
  27696. * @function
  27697. * @param {Node<vec3>} color - The color that should be tone mapped.
  27698. * @param {Node<float>} exposure - The exposure.
  27699. * @return {Node<vec3>} The tone mapped color.
  27700. */
  27701. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27702. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  27703. color = color.mul( exposure );
  27704. color = color.sub( 0.004 ).max( 0.0 );
  27705. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  27706. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  27707. return a.div( b ).pow( 2.2 );
  27708. } ).setLayout( {
  27709. name: 'cineonToneMapping',
  27710. type: 'vec3',
  27711. inputs: [
  27712. { name: 'color', type: 'vec3' },
  27713. { name: 'exposure', type: 'float' }
  27714. ]
  27715. } );
  27716. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  27717. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  27718. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  27719. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  27720. return a.div( b );
  27721. } );
  27722. /**
  27723. * ACESFilmic tone mapping.
  27724. *
  27725. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  27726. *
  27727. * @tsl
  27728. * @function
  27729. * @param {Node<vec3>} color - The color that should be tone mapped.
  27730. * @param {Node<float>} exposure - The exposure.
  27731. * @return {Node<vec3>} The tone mapped color.
  27732. */
  27733. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27734. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  27735. const ACESInputMat = mat3(
  27736. 0.59719, 0.35458, 0.04823,
  27737. 0.07600, 0.90834, 0.01566,
  27738. 0.02840, 0.13383, 0.83777
  27739. );
  27740. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  27741. const ACESOutputMat = mat3(
  27742. 1.60475, -0.53108, -0.07367,
  27743. -0.10208, 1.10813, -605e-5,
  27744. -327e-5, -0.07276, 1.07602
  27745. );
  27746. color = color.mul( exposure ).div( 0.6 );
  27747. color = ACESInputMat.mul( color );
  27748. // Apply RRT and ODT
  27749. color = RRTAndODTFit( color );
  27750. color = ACESOutputMat.mul( color );
  27751. // Clamp to [0, 1]
  27752. return color.clamp();
  27753. } ).setLayout( {
  27754. name: 'acesFilmicToneMapping',
  27755. type: 'vec3',
  27756. inputs: [
  27757. { name: 'color', type: 'vec3' },
  27758. { name: 'exposure', type: 'float' }
  27759. ]
  27760. } );
  27761. 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 ) );
  27762. 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 ) );
  27763. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  27764. const x = vec3( x_immutable ).toVar();
  27765. const x2 = vec3( x.mul( x ) ).toVar();
  27766. const x4 = vec3( x2.mul( x2 ) ).toVar();
  27767. 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 ) ) ) );
  27768. } );
  27769. /**
  27770. * AgX tone mapping.
  27771. *
  27772. * @tsl
  27773. * @function
  27774. * @param {Node<vec3>} color - The color that should be tone mapped.
  27775. * @param {Node<float>} exposure - The exposure.
  27776. * @return {Node<vec3>} The tone mapped color.
  27777. */
  27778. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27779. const colortone = vec3( color ).toVar();
  27780. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  27781. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  27782. const AgxMinEv = float( -12.47393 );
  27783. const AgxMaxEv = float( 4.026069 );
  27784. colortone.mulAssign( exposure );
  27785. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  27786. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  27787. colortone.assign( max$1( colortone, 1e-10 ) );
  27788. colortone.assign( log2( colortone ) );
  27789. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  27790. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  27791. colortone.assign( agxDefaultContrastApprox( colortone ) );
  27792. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  27793. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  27794. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  27795. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  27796. return colortone;
  27797. } ).setLayout( {
  27798. name: 'agxToneMapping',
  27799. type: 'vec3',
  27800. inputs: [
  27801. { name: 'color', type: 'vec3' },
  27802. { name: 'exposure', type: 'float' }
  27803. ]
  27804. } );
  27805. /**
  27806. * Neutral tone mapping.
  27807. *
  27808. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  27809. *
  27810. * @tsl
  27811. * @function
  27812. * @param {Node<vec3>} color - The color that should be tone mapped.
  27813. * @param {Node<float>} exposure - The exposure.
  27814. * @return {Node<vec3>} The tone mapped color.
  27815. */
  27816. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27817. const StartCompression = float( 0.8 - 0.04 );
  27818. const Desaturation = float( 0.15 );
  27819. color = color.mul( exposure );
  27820. const x = min$1( color.r, min$1( color.g, color.b ) );
  27821. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  27822. color.subAssign( offset );
  27823. const peak = max$1( color.r, max$1( color.g, color.b ) );
  27824. If( peak.lessThan( StartCompression ), () => {
  27825. return color;
  27826. } );
  27827. const d = sub( 1, StartCompression );
  27828. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  27829. color.mulAssign( newPeak.div( peak ) );
  27830. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  27831. return mix( color, vec3( newPeak ), g );
  27832. } ).setLayout( {
  27833. name: 'neutralToneMapping',
  27834. type: 'vec3',
  27835. inputs: [
  27836. { name: 'color', type: 'vec3' },
  27837. { name: 'exposure', type: 'float' }
  27838. ]
  27839. } );
  27840. /**
  27841. * This class represents native code sections. It is the base
  27842. * class for modules like {@link FunctionNode} which allows to implement
  27843. * functions with native shader languages.
  27844. *
  27845. * @augments Node
  27846. */
  27847. class CodeNode extends Node {
  27848. static get type() {
  27849. return 'CodeNode';
  27850. }
  27851. /**
  27852. * Constructs a new code node.
  27853. *
  27854. * @param {string} [code=''] - The native code.
  27855. * @param {Array<Node>} [includes=[]] - An array of includes.
  27856. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  27857. */
  27858. constructor( code = '', includes = [], language = '' ) {
  27859. super( 'code' );
  27860. /**
  27861. * This flag can be used for type testing.
  27862. *
  27863. * @type {boolean}
  27864. * @readonly
  27865. * @default true
  27866. */
  27867. this.isCodeNode = true;
  27868. /**
  27869. * This flag is used for global cache.
  27870. *
  27871. * @type {boolean}
  27872. * @default true
  27873. */
  27874. this.global = true;
  27875. /**
  27876. * The native code.
  27877. *
  27878. * @type {string}
  27879. * @default ''
  27880. */
  27881. this.code = code;
  27882. /**
  27883. * An array of includes
  27884. *
  27885. * @type {Array<Node>}
  27886. * @default []
  27887. */
  27888. this.includes = includes;
  27889. /**
  27890. * The used language.
  27891. *
  27892. * @type {('js'|'wgsl'|'glsl')}
  27893. * @default ''
  27894. */
  27895. this.language = language;
  27896. }
  27897. /**
  27898. * Sets the includes of this code node.
  27899. *
  27900. * @param {Array<Node>} includes - The includes to set.
  27901. * @return {CodeNode} A reference to this node.
  27902. */
  27903. setIncludes( includes ) {
  27904. this.includes = includes;
  27905. return this;
  27906. }
  27907. /**
  27908. * Returns the includes of this code node.
  27909. *
  27910. * @param {NodeBuilder} builder - The current node builder.
  27911. * @return {Array<Node>} The includes.
  27912. */
  27913. getIncludes( /*builder*/ ) {
  27914. return this.includes;
  27915. }
  27916. generate( builder ) {
  27917. const includes = this.getIncludes( builder );
  27918. for ( const include of includes ) {
  27919. include.build( builder );
  27920. }
  27921. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  27922. nodeCode.code = this.code;
  27923. return nodeCode.code;
  27924. }
  27925. serialize( data ) {
  27926. super.serialize( data );
  27927. data.code = this.code;
  27928. data.language = this.language;
  27929. }
  27930. deserialize( data ) {
  27931. super.deserialize( data );
  27932. this.code = data.code;
  27933. this.language = data.language;
  27934. }
  27935. }
  27936. /**
  27937. * TSL function for creating a code node.
  27938. *
  27939. * @tsl
  27940. * @function
  27941. * @param {string} [code] - The native code.
  27942. * @param {?Array<Node>} [includes=[]] - An array of includes.
  27943. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  27944. * @returns {CodeNode}
  27945. */
  27946. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  27947. /**
  27948. * TSL function for creating a JS code node.
  27949. *
  27950. * @tsl
  27951. * @function
  27952. * @param {string} src - The native code.
  27953. * @param {Array<Node>} includes - An array of includes.
  27954. * @returns {CodeNode}
  27955. */
  27956. const js = ( src, includes ) => code( src, includes, 'js' );
  27957. /**
  27958. * TSL function for creating a WGSL code node.
  27959. *
  27960. * @tsl
  27961. * @function
  27962. * @param {string} src - The native code.
  27963. * @param {Array<Node>} includes - An array of includes.
  27964. * @returns {CodeNode}
  27965. */
  27966. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  27967. /**
  27968. * TSL function for creating a GLSL code node.
  27969. *
  27970. * @tsl
  27971. * @function
  27972. * @param {string} src - The native code.
  27973. * @param {Array<Node>} includes - An array of includes.
  27974. * @returns {CodeNode}
  27975. */
  27976. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  27977. /**
  27978. * This class represents a native shader function. It can be used to implement
  27979. * certain aspects of a node material with native shader code. There are two predefined
  27980. * TSL functions for easier usage.
  27981. *
  27982. * - `wgslFn`: Creates a WGSL function node.
  27983. * - `glslFn`: Creates a GLSL function node.
  27984. *
  27985. * A basic example with one include looks like so:
  27986. *
  27987. * ```js
  27988. * const desaturateWGSLFn = wgslFn( `
  27989. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  27990. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  27991. * return vec3<f32>( dot( lum, color ) );
  27992. * }`
  27993. *);
  27994. * const someWGSLFn = wgslFn( `
  27995. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  27996. * return desaturate( color );
  27997. * }
  27998. * `, [ desaturateWGSLFn ] );
  27999. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  28000. *```
  28001. * @augments CodeNode
  28002. */
  28003. class FunctionNode extends CodeNode {
  28004. static get type() {
  28005. return 'FunctionNode';
  28006. }
  28007. /**
  28008. * Constructs a new function node.
  28009. *
  28010. * @param {string} [code=''] - The native code.
  28011. * @param {Array<Node>} [includes=[]] - An array of includes.
  28012. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  28013. */
  28014. constructor( code = '', includes = [], language = '' ) {
  28015. super( code, includes, language );
  28016. }
  28017. /**
  28018. * Returns the type of this function node.
  28019. *
  28020. * @param {NodeBuilder} builder - The current node builder.
  28021. * @return {string} The type.
  28022. */
  28023. getNodeType( builder ) {
  28024. return this.getNodeFunction( builder ).type;
  28025. }
  28026. /**
  28027. * Returns the type of a member of this function node.
  28028. *
  28029. * @param {NodeBuilder} builder - The current node builder.
  28030. * @param {string} name - The name of the member.
  28031. * @return {string} The type of the member.
  28032. */
  28033. getMemberType( builder, name ) {
  28034. const type = this.getNodeType( builder );
  28035. const structType = builder.getStructTypeNode( type );
  28036. return structType.getMemberType( builder, name );
  28037. }
  28038. /**
  28039. * Returns the inputs of this function node.
  28040. *
  28041. * @param {NodeBuilder} builder - The current node builder.
  28042. * @return {Array<NodeFunctionInput>} The inputs.
  28043. */
  28044. getInputs( builder ) {
  28045. return this.getNodeFunction( builder ).inputs;
  28046. }
  28047. /**
  28048. * Returns the node function for this function node.
  28049. *
  28050. * @param {NodeBuilder} builder - The current node builder.
  28051. * @return {NodeFunction} The node function.
  28052. */
  28053. getNodeFunction( builder ) {
  28054. const nodeData = builder.getDataFromNode( this );
  28055. let nodeFunction = nodeData.nodeFunction;
  28056. if ( nodeFunction === undefined ) {
  28057. nodeFunction = builder.parser.parseFunction( this.code );
  28058. nodeData.nodeFunction = nodeFunction;
  28059. }
  28060. return nodeFunction;
  28061. }
  28062. generate( builder, output ) {
  28063. super.generate( builder );
  28064. const nodeFunction = this.getNodeFunction( builder );
  28065. const name = nodeFunction.name;
  28066. const type = nodeFunction.type;
  28067. const nodeCode = builder.getCodeFromNode( this, type );
  28068. if ( name !== '' ) {
  28069. // use a custom property name
  28070. nodeCode.name = name;
  28071. }
  28072. const propertyName = builder.getPropertyName( nodeCode );
  28073. const code = this.getNodeFunction( builder ).getCode( propertyName );
  28074. nodeCode.code = code + '\n';
  28075. if ( output === 'property' ) {
  28076. return propertyName;
  28077. } else {
  28078. return builder.format( `${ propertyName }()`, type, output );
  28079. }
  28080. }
  28081. }
  28082. const nativeFn = ( code, includes = [], language = '' ) => {
  28083. for ( let i = 0; i < includes.length; i ++ ) {
  28084. const include = includes[ i ];
  28085. // TSL Function: glslFn, wgslFn
  28086. if ( typeof include === 'function' ) {
  28087. includes[ i ] = include.functionNode;
  28088. }
  28089. }
  28090. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  28091. const fn = ( ...params ) => functionNode.call( ...params );
  28092. fn.functionNode = functionNode;
  28093. return fn;
  28094. };
  28095. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  28096. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  28097. /**
  28098. * `ScriptableNode` uses this class to manage script inputs and outputs.
  28099. *
  28100. * @augments Node
  28101. */
  28102. class ScriptableValueNode extends Node {
  28103. static get type() {
  28104. return 'ScriptableValueNode';
  28105. }
  28106. /**
  28107. * Constructs a new scriptable node.
  28108. *
  28109. * @param {any} [value=null] - The value.
  28110. */
  28111. constructor( value = null ) {
  28112. super();
  28113. /**
  28114. * A reference to the value.
  28115. *
  28116. * @private
  28117. * @default null
  28118. */
  28119. this._value = value;
  28120. /**
  28121. * Depending on the type of `_value`, this property might cache parsed data.
  28122. *
  28123. * @private
  28124. * @default null
  28125. */
  28126. this._cache = null;
  28127. /**
  28128. * If this node represents an input, this property represents the input type.
  28129. *
  28130. * @type {?string}
  28131. * @default null
  28132. */
  28133. this.inputType = null;
  28134. /**
  28135. * If this node represents an output, this property represents the output type.
  28136. *
  28137. * @type {?string}
  28138. * @default null
  28139. */
  28140. this.outputType = null;
  28141. /**
  28142. * An event dispatcher for managing events.
  28143. *
  28144. * @type {EventDispatcher}
  28145. */
  28146. this.events = new EventDispatcher();
  28147. /**
  28148. * This flag can be used for type testing.
  28149. *
  28150. * @type {boolean}
  28151. * @readonly
  28152. * @default true
  28153. */
  28154. this.isScriptableValueNode = true;
  28155. }
  28156. /**
  28157. * Whether this node represents an output or not.
  28158. *
  28159. * @type {boolean}
  28160. * @readonly
  28161. * @default true
  28162. */
  28163. get isScriptableOutputNode() {
  28164. return this.outputType !== null;
  28165. }
  28166. set value( val ) {
  28167. if ( this._value === val ) return;
  28168. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  28169. URL.revokeObjectURL( this._cache );
  28170. this._cache = null;
  28171. }
  28172. this._value = val;
  28173. this.events.dispatchEvent( { type: 'change' } );
  28174. this.refresh();
  28175. }
  28176. /**
  28177. * The node's value.
  28178. *
  28179. * @type {any}
  28180. */
  28181. get value() {
  28182. return this._value;
  28183. }
  28184. /**
  28185. * Dispatches the `refresh` event.
  28186. */
  28187. refresh() {
  28188. this.events.dispatchEvent( { type: 'refresh' } );
  28189. }
  28190. /**
  28191. * The `value` property usually represents a node or even binary data in form of array buffers.
  28192. * In this case, this method tries to return the actual value behind the complex type.
  28193. *
  28194. * @return {any} The value.
  28195. */
  28196. getValue() {
  28197. const value = this.value;
  28198. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  28199. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  28200. } else if ( value && value.value !== null && value.value !== undefined && (
  28201. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  28202. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  28203. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  28204. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  28205. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  28206. ( this.inputType === 'Color' && value.value.isColor ) ||
  28207. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  28208. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  28209. ) ) {
  28210. return value.value;
  28211. }
  28212. return this._cache || value;
  28213. }
  28214. /**
  28215. * Overwritten since the node type is inferred from the value.
  28216. *
  28217. * @param {NodeBuilder} builder - The current node builder.
  28218. * @return {string} The node type.
  28219. */
  28220. getNodeType( builder ) {
  28221. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  28222. }
  28223. setup() {
  28224. return this.value && this.value.isNode ? this.value : float();
  28225. }
  28226. serialize( data ) {
  28227. super.serialize( data );
  28228. if ( this.value !== null ) {
  28229. if ( this.inputType === 'ArrayBuffer' ) {
  28230. data.value = arrayBufferToBase64( this.value );
  28231. } else {
  28232. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  28233. }
  28234. } else {
  28235. data.value = null;
  28236. }
  28237. data.inputType = this.inputType;
  28238. data.outputType = this.outputType;
  28239. }
  28240. deserialize( data ) {
  28241. super.deserialize( data );
  28242. let value = null;
  28243. if ( data.value !== null ) {
  28244. if ( data.inputType === 'ArrayBuffer' ) {
  28245. value = base64ToArrayBuffer( data.value );
  28246. } else if ( data.inputType === 'Texture' ) {
  28247. value = data.meta.textures[ data.value ];
  28248. } else {
  28249. value = data.meta.nodes[ data.value ] || null;
  28250. }
  28251. }
  28252. this.value = value;
  28253. this.inputType = data.inputType;
  28254. this.outputType = data.outputType;
  28255. }
  28256. }
  28257. /**
  28258. * TSL function for creating a scriptable value node.
  28259. *
  28260. * @tsl
  28261. * @function
  28262. * @param {any} [value] - The value.
  28263. * @returns {ScriptableValueNode}
  28264. */
  28265. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  28266. /**
  28267. * A Map-like data structure for managing resources of scriptable nodes.
  28268. *
  28269. * @augments Map
  28270. */
  28271. class Resources extends Map {
  28272. get( key, callback = null, ...params ) {
  28273. if ( this.has( key ) ) return super.get( key );
  28274. if ( callback !== null ) {
  28275. const value = callback( ...params );
  28276. this.set( key, value );
  28277. return value;
  28278. }
  28279. }
  28280. }
  28281. class Parameters {
  28282. constructor( scriptableNode ) {
  28283. this.scriptableNode = scriptableNode;
  28284. }
  28285. get parameters() {
  28286. return this.scriptableNode.parameters;
  28287. }
  28288. get layout() {
  28289. return this.scriptableNode.getLayout();
  28290. }
  28291. getInputLayout( id ) {
  28292. return this.scriptableNode.getInputLayout( id );
  28293. }
  28294. get( name ) {
  28295. const param = this.parameters[ name ];
  28296. const value = param ? param.getValue() : null;
  28297. return value;
  28298. }
  28299. }
  28300. /**
  28301. * Defines the resources (e.g. namespaces) of scriptable nodes.
  28302. *
  28303. * @type {Resources}
  28304. */
  28305. const ScriptableNodeResources = new Resources();
  28306. /**
  28307. * This type of node allows to implement nodes with custom scripts. The script
  28308. * section is represented as an instance of `CodeNode` written with JavaScript.
  28309. * The script itself must adhere to a specific structure.
  28310. *
  28311. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  28312. * - layout: The layout object defines the script's interface (inputs and outputs).
  28313. *
  28314. * ```js
  28315. * ScriptableNodeResources.set( 'TSL', TSL );
  28316. *
  28317. * const scriptableNode = scriptable( js( `
  28318. * layout = {
  28319. * outputType: 'node',
  28320. * elements: [
  28321. * { name: 'source', inputType: 'node' },
  28322. * ]
  28323. * };
  28324. *
  28325. * const { mul, oscSine } = TSL;
  28326. *
  28327. * function main() {
  28328. * const source = parameters.get( 'source' ) || float();
  28329. * return mul( source, oscSine() ) );
  28330. * }
  28331. *
  28332. * ` ) );
  28333. *
  28334. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  28335. *
  28336. * const material = new THREE.MeshBasicNodeMaterial();
  28337. * material.colorNode = scriptableNode;
  28338. * ```
  28339. *
  28340. * @augments Node
  28341. */
  28342. class ScriptableNode extends Node {
  28343. static get type() {
  28344. return 'ScriptableNode';
  28345. }
  28346. /**
  28347. * Constructs a new scriptable node.
  28348. *
  28349. * @param {?CodeNode} [codeNode=null] - The code node.
  28350. * @param {Object} [parameters={}] - The parameters definition.
  28351. */
  28352. constructor( codeNode = null, parameters = {} ) {
  28353. super();
  28354. /**
  28355. * The code node.
  28356. *
  28357. * @type {?CodeNode}
  28358. * @default null
  28359. */
  28360. this.codeNode = codeNode;
  28361. /**
  28362. * The parameters definition.
  28363. *
  28364. * @type {Object}
  28365. * @default {}
  28366. */
  28367. this.parameters = parameters;
  28368. this._local = new Resources();
  28369. this._output = scriptableValue( null );
  28370. this._outputs = {};
  28371. this._source = this.source;
  28372. this._method = null;
  28373. this._object = null;
  28374. this._value = null;
  28375. this._needsOutputUpdate = true;
  28376. this.onRefresh = this.onRefresh.bind( this );
  28377. /**
  28378. * This flag can be used for type testing.
  28379. *
  28380. * @type {boolean}
  28381. * @readonly
  28382. * @default true
  28383. */
  28384. this.isScriptableNode = true;
  28385. }
  28386. /**
  28387. * The source code of the scriptable node.
  28388. *
  28389. * @type {string}
  28390. */
  28391. get source() {
  28392. return this.codeNode ? this.codeNode.code : '';
  28393. }
  28394. /**
  28395. * Sets the reference of a local script variable.
  28396. *
  28397. * @param {string} name - The variable name.
  28398. * @param {Object} value - The reference to set.
  28399. * @return {Resources} The resource map
  28400. */
  28401. setLocal( name, value ) {
  28402. return this._local.set( name, value );
  28403. }
  28404. /**
  28405. * Gets the value of a local script variable.
  28406. *
  28407. * @param {string} name - The variable name.
  28408. * @return {Object} The value.
  28409. */
  28410. getLocal( name ) {
  28411. return this._local.get( name );
  28412. }
  28413. /**
  28414. * Event listener for the `refresh` event.
  28415. */
  28416. onRefresh() {
  28417. this._refresh();
  28418. }
  28419. /**
  28420. * Returns an input from the layout with the given id/name.
  28421. *
  28422. * @param {string} id - The id/name of the input.
  28423. * @return {Object} The element entry.
  28424. */
  28425. getInputLayout( id ) {
  28426. for ( const element of this.getLayout() ) {
  28427. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  28428. return element;
  28429. }
  28430. }
  28431. }
  28432. /**
  28433. * Returns an output from the layout with the given id/name.
  28434. *
  28435. * @param {string} id - The id/name of the output.
  28436. * @return {Object} The element entry.
  28437. */
  28438. getOutputLayout( id ) {
  28439. for ( const element of this.getLayout() ) {
  28440. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  28441. return element;
  28442. }
  28443. }
  28444. }
  28445. /**
  28446. * Defines a script output for the given name and value.
  28447. *
  28448. * @param {string} name - The name of the output.
  28449. * @param {Node} value - The node value.
  28450. * @return {ScriptableNode} A reference to this node.
  28451. */
  28452. setOutput( name, value ) {
  28453. const outputs = this._outputs;
  28454. if ( outputs[ name ] === undefined ) {
  28455. outputs[ name ] = scriptableValue( value );
  28456. } else {
  28457. outputs[ name ].value = value;
  28458. }
  28459. return this;
  28460. }
  28461. /**
  28462. * Returns a script output for the given name.
  28463. *
  28464. * @param {string} name - The name of the output.
  28465. * @return {ScriptableValueNode} The node value.
  28466. */
  28467. getOutput( name ) {
  28468. return this._outputs[ name ];
  28469. }
  28470. /**
  28471. * Returns a parameter for the given name
  28472. *
  28473. * @param {string} name - The name of the parameter.
  28474. * @return {ScriptableValueNode} The node value.
  28475. */
  28476. getParameter( name ) {
  28477. return this.parameters[ name ];
  28478. }
  28479. /**
  28480. * Sets a value for the given parameter name.
  28481. *
  28482. * @param {string} name - The parameter name.
  28483. * @param {any} value - The parameter value.
  28484. * @return {ScriptableNode} A reference to this node.
  28485. */
  28486. setParameter( name, value ) {
  28487. const parameters = this.parameters;
  28488. if ( value && value.isScriptableNode ) {
  28489. this.deleteParameter( name );
  28490. parameters[ name ] = value;
  28491. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  28492. } else if ( value && value.isScriptableValueNode ) {
  28493. this.deleteParameter( name );
  28494. parameters[ name ] = value;
  28495. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  28496. } else if ( parameters[ name ] === undefined ) {
  28497. parameters[ name ] = scriptableValue( value );
  28498. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  28499. } else {
  28500. parameters[ name ].value = value;
  28501. }
  28502. return this;
  28503. }
  28504. /**
  28505. * Returns the value of this node which is the value of
  28506. * the default output.
  28507. *
  28508. * @return {Node} The value.
  28509. */
  28510. getValue() {
  28511. return this.getDefaultOutput().getValue();
  28512. }
  28513. /**
  28514. * Deletes a parameter from the script.
  28515. *
  28516. * @param {string} name - The parameter to remove.
  28517. * @return {ScriptableNode} A reference to this node.
  28518. */
  28519. deleteParameter( name ) {
  28520. let valueNode = this.parameters[ name ];
  28521. if ( valueNode ) {
  28522. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  28523. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  28524. }
  28525. return this;
  28526. }
  28527. /**
  28528. * Deletes all parameters from the script.
  28529. *
  28530. * @return {ScriptableNode} A reference to this node.
  28531. */
  28532. clearParameters() {
  28533. for ( const name of Object.keys( this.parameters ) ) {
  28534. this.deleteParameter( name );
  28535. }
  28536. this.needsUpdate = true;
  28537. return this;
  28538. }
  28539. /**
  28540. * Calls a function from the script.
  28541. *
  28542. * @param {string} name - The function name.
  28543. * @param {...any} params - A list of parameters.
  28544. * @return {any} The result of the function call.
  28545. */
  28546. call( name, ...params ) {
  28547. const object = this.getObject();
  28548. const method = object[ name ];
  28549. if ( typeof method === 'function' ) {
  28550. return method( ...params );
  28551. }
  28552. }
  28553. /**
  28554. * Asynchronously calls a function from the script.
  28555. *
  28556. * @param {string} name - The function name.
  28557. * @param {...any} params - A list of parameters.
  28558. * @return {Promise<any>} The result of the function call.
  28559. */
  28560. async callAsync( name, ...params ) {
  28561. const object = this.getObject();
  28562. const method = object[ name ];
  28563. if ( typeof method === 'function' ) {
  28564. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  28565. }
  28566. }
  28567. /**
  28568. * Overwritten since the node types is inferred from the script's output.
  28569. *
  28570. * @param {NodeBuilder} builder - The current node builder
  28571. * @return {string} The node type.
  28572. */
  28573. getNodeType( builder ) {
  28574. return this.getDefaultOutputNode().getNodeType( builder );
  28575. }
  28576. /**
  28577. * Refreshes the script node.
  28578. *
  28579. * @param {?string} [output=null] - An optional output.
  28580. */
  28581. refresh( output = null ) {
  28582. if ( output !== null ) {
  28583. this.getOutput( output ).refresh();
  28584. } else {
  28585. this._refresh();
  28586. }
  28587. }
  28588. /**
  28589. * Returns an object representation of the script.
  28590. *
  28591. * @return {Object} The result object.
  28592. */
  28593. getObject() {
  28594. if ( this.needsUpdate ) this.dispose();
  28595. if ( this._object !== null ) return this._object;
  28596. //
  28597. const refresh = () => this.refresh();
  28598. const setOutput = ( id, value ) => this.setOutput( id, value );
  28599. const parameters = new Parameters( this );
  28600. const THREE = ScriptableNodeResources.get( 'THREE' );
  28601. const TSL = ScriptableNodeResources.get( 'TSL' );
  28602. const method = this.getMethod();
  28603. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  28604. this._object = method( ...params );
  28605. const layout = this._object.layout;
  28606. if ( layout ) {
  28607. if ( layout.cache === false ) {
  28608. this._local.clear();
  28609. }
  28610. // default output
  28611. this._output.outputType = layout.outputType || null;
  28612. if ( Array.isArray( layout.elements ) ) {
  28613. for ( const element of layout.elements ) {
  28614. const id = element.id || element.name;
  28615. if ( element.inputType ) {
  28616. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  28617. this.getParameter( id ).inputType = element.inputType;
  28618. }
  28619. if ( element.outputType ) {
  28620. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  28621. this.getOutput( id ).outputType = element.outputType;
  28622. }
  28623. }
  28624. }
  28625. }
  28626. return this._object;
  28627. }
  28628. deserialize( data ) {
  28629. super.deserialize( data );
  28630. for ( const name in this.parameters ) {
  28631. let valueNode = this.parameters[ name ];
  28632. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  28633. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  28634. }
  28635. }
  28636. /**
  28637. * Returns the layout of the script.
  28638. *
  28639. * @return {Object} The script's layout.
  28640. */
  28641. getLayout() {
  28642. return this.getObject().layout;
  28643. }
  28644. /**
  28645. * Returns default node output of the script.
  28646. *
  28647. * @return {Node} The default node output.
  28648. */
  28649. getDefaultOutputNode() {
  28650. const output = this.getDefaultOutput().value;
  28651. if ( output && output.isNode ) {
  28652. return output;
  28653. }
  28654. return float();
  28655. }
  28656. /**
  28657. * Returns default output of the script.
  28658. *
  28659. * @return {ScriptableValueNode} The default output.
  28660. */
  28661. getDefaultOutput() {
  28662. return this._exec()._output;
  28663. }
  28664. /**
  28665. * Returns a function created from the node's script.
  28666. *
  28667. * @return {Function} The function representing the node's code.
  28668. */
  28669. getMethod() {
  28670. if ( this.needsUpdate ) this.dispose();
  28671. if ( this._method !== null ) return this._method;
  28672. //
  28673. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  28674. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  28675. const properties = interfaceProps.join( ', ' );
  28676. const declarations = 'var ' + properties + '; var output = {};\n';
  28677. const returns = '\nreturn { ...output, ' + properties + ' };';
  28678. const code = declarations + this.codeNode.code + returns;
  28679. //
  28680. this._method = new Function( ...parametersProps, code );
  28681. return this._method;
  28682. }
  28683. /**
  28684. * Frees all internal resources.
  28685. */
  28686. dispose() {
  28687. if ( this._method === null ) return;
  28688. if ( this._object && typeof this._object.dispose === 'function' ) {
  28689. this._object.dispose();
  28690. }
  28691. this._method = null;
  28692. this._object = null;
  28693. this._source = null;
  28694. this._value = null;
  28695. this._needsOutputUpdate = true;
  28696. this._output.value = null;
  28697. this._outputs = {};
  28698. }
  28699. setup() {
  28700. return this.getDefaultOutputNode();
  28701. }
  28702. getCacheKey( force ) {
  28703. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  28704. for ( const param in this.parameters ) {
  28705. values.push( this.parameters[ param ].getCacheKey( force ) );
  28706. }
  28707. return hashArray( values );
  28708. }
  28709. set needsUpdate( value ) {
  28710. if ( value === true ) this.dispose();
  28711. }
  28712. get needsUpdate() {
  28713. return this.source !== this._source;
  28714. }
  28715. /**
  28716. * Executes the `main` function of the script.
  28717. *
  28718. * @private
  28719. * @return {ScriptableNode} A reference to this node.
  28720. */
  28721. _exec() {
  28722. if ( this.codeNode === null ) return this;
  28723. if ( this._needsOutputUpdate === true ) {
  28724. this._value = this.call( 'main' );
  28725. this._needsOutputUpdate = false;
  28726. }
  28727. this._output.value = this._value;
  28728. return this;
  28729. }
  28730. /**
  28731. * Executes the refresh.
  28732. *
  28733. * @private
  28734. */
  28735. _refresh() {
  28736. this.needsUpdate = true;
  28737. this._exec();
  28738. this._output.refresh();
  28739. }
  28740. }
  28741. /**
  28742. * TSL function for creating a scriptable node.
  28743. *
  28744. * @tsl
  28745. * @function
  28746. * @param {CodeNode} [codeNode] - The code node.
  28747. * @param {?Object} [parameters={}] - The parameters definition.
  28748. * @returns {ScriptableNode}
  28749. */
  28750. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  28751. /**
  28752. * Returns a node that represents the `z` coordinate in view space
  28753. * for the current fragment. It's a different representation of the
  28754. * default depth value.
  28755. *
  28756. * This value can be part of a computation that defines how the fog
  28757. * density increases when moving away from the camera.
  28758. *
  28759. * @param {NodeBuilder} builder - The current node builder.
  28760. * @return {Node} The viewZ node.
  28761. */
  28762. function getViewZNode( builder ) {
  28763. let viewZ;
  28764. const getViewZ = builder.context.getViewZ;
  28765. if ( getViewZ !== undefined ) {
  28766. viewZ = getViewZ( this );
  28767. }
  28768. return ( viewZ || positionView.z ).negate();
  28769. }
  28770. /**
  28771. * Constructs a new range factor node.
  28772. *
  28773. * @tsl
  28774. * @function
  28775. * @param {Node} near - Defines the near value.
  28776. * @param {Node} far - Defines the far value.
  28777. */
  28778. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  28779. const viewZ = getViewZNode( builder );
  28780. return smoothstep( near, far, viewZ );
  28781. } );
  28782. /**
  28783. * Represents an exponential squared fog. This type of fog gives
  28784. * a clear view near the camera and a faster than exponentially
  28785. * densening fog farther from the camera.
  28786. *
  28787. * @tsl
  28788. * @function
  28789. * @param {Node} density - Defines the fog density.
  28790. */
  28791. const densityFogFactor = Fn( ( [ density ], builder ) => {
  28792. const viewZ = getViewZNode( builder );
  28793. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  28794. } );
  28795. /**
  28796. * This class can be used to configure a fog for the scene.
  28797. * Nodes of this type are assigned to `Scene.fogNode`.
  28798. *
  28799. * @tsl
  28800. * @function
  28801. * @param {Node} color - Defines the color of the fog.
  28802. * @param {Node} factor - Defines how the fog is factored in the scene.
  28803. */
  28804. const fog = Fn( ( [ color, factor ] ) => {
  28805. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  28806. } );
  28807. // Deprecated
  28808. /**
  28809. * @tsl
  28810. * @function
  28811. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  28812. *
  28813. * @param {Node} color
  28814. * @param {Node} near
  28815. * @param {Node} far
  28816. * @returns {Function}
  28817. */
  28818. function rangeFog( color, near, far ) { // @deprecated, r171
  28819. warn( 'TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  28820. return fog( color, rangeFogFactor( near, far ) );
  28821. }
  28822. /**
  28823. * @tsl
  28824. * @function
  28825. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  28826. *
  28827. * @param {Node} color
  28828. * @param {Node} density
  28829. * @returns {Function}
  28830. */
  28831. function densityFog( color, density ) { // @deprecated, r171
  28832. warn( 'TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  28833. return fog( color, densityFogFactor( density ) );
  28834. }
  28835. let min = null;
  28836. let max = null;
  28837. /**
  28838. * `RangeNode` generates random instanced attribute data in a defined range.
  28839. * An exemplary use case for this utility node is to generate random per-instance
  28840. * colors:
  28841. * ```js
  28842. * const material = new MeshBasicNodeMaterial();
  28843. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  28844. * const mesh = new InstancedMesh( geometry, material, count );
  28845. * ```
  28846. * @augments Node
  28847. */
  28848. class RangeNode extends Node {
  28849. static get type() {
  28850. return 'RangeNode';
  28851. }
  28852. /**
  28853. * Constructs a new range node.
  28854. *
  28855. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  28856. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  28857. */
  28858. constructor( minNode = float(), maxNode = float() ) {
  28859. super();
  28860. /**
  28861. * A node defining the lower bound of the range.
  28862. *
  28863. * @type {Node<any>}
  28864. * @default float()
  28865. */
  28866. this.minNode = minNode;
  28867. /**
  28868. * A node defining the upper bound of the range.
  28869. *
  28870. * @type {Node<any>}
  28871. * @default float()
  28872. */
  28873. this.maxNode = maxNode;
  28874. }
  28875. /**
  28876. * Returns the vector length which is computed based on the range definition.
  28877. *
  28878. * @param {NodeBuilder} builder - The current node builder.
  28879. * @return {number} The vector length.
  28880. */
  28881. getVectorLength( builder ) {
  28882. const minNode = this.getConstNode( this.minNode );
  28883. const maxNode = this.getConstNode( this.maxNode );
  28884. const minLength = builder.getTypeLength( getValueType( minNode.value ) );
  28885. const maxLength = builder.getTypeLength( getValueType( maxNode.value ) );
  28886. return minLength > maxLength ? minLength : maxLength;
  28887. }
  28888. /**
  28889. * This method is overwritten since the node type is inferred from range definition.
  28890. *
  28891. * @param {NodeBuilder} builder - The current node builder.
  28892. * @return {string} The node type.
  28893. */
  28894. getNodeType( builder ) {
  28895. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  28896. }
  28897. /**
  28898. * Returns a constant node from the given node by traversing it.
  28899. *
  28900. * @param {Node} node - The node to traverse.
  28901. * @returns {Node} The constant node, if found.
  28902. */
  28903. getConstNode( node ) {
  28904. let output = null;
  28905. node.traverse( n => {
  28906. if ( n.isConstNode === true ) {
  28907. output = n;
  28908. }
  28909. } );
  28910. if ( output === null ) {
  28911. throw new Error( 'THREE.TSL: No "ConstNode" found in node graph.' );
  28912. }
  28913. return output;
  28914. }
  28915. setup( builder ) {
  28916. const object = builder.object;
  28917. let output = null;
  28918. if ( object.count > 1 ) {
  28919. const minNode = this.getConstNode( this.minNode );
  28920. const maxNode = this.getConstNode( this.maxNode );
  28921. const minValue = minNode.value;
  28922. const maxValue = maxNode.value;
  28923. const minLength = builder.getTypeLength( getValueType( minValue ) );
  28924. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  28925. min = min || new Vector4();
  28926. max = max || new Vector4();
  28927. min.setScalar( 0 );
  28928. max.setScalar( 0 );
  28929. if ( minLength === 1 ) min.setScalar( minValue );
  28930. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  28931. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  28932. if ( maxLength === 1 ) max.setScalar( maxValue );
  28933. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  28934. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  28935. const stride = 4;
  28936. const length = stride * object.count;
  28937. const array = new Float32Array( length );
  28938. for ( let i = 0; i < length; i ++ ) {
  28939. const index = i % stride;
  28940. const minElementValue = min.getComponent( index );
  28941. const maxElementValue = max.getComponent( index );
  28942. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  28943. }
  28944. const nodeType = this.getNodeType( builder );
  28945. if ( object.count <= 4096 ) {
  28946. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  28947. } else {
  28948. // TODO: Improve anonymous buffer attribute creation removing this part
  28949. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  28950. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  28951. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  28952. }
  28953. } else {
  28954. output = float( 0 );
  28955. }
  28956. return output;
  28957. }
  28958. }
  28959. /**
  28960. * TSL function for creating a range node.
  28961. *
  28962. * @tsl
  28963. * @function
  28964. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  28965. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  28966. * @returns {RangeNode}
  28967. */
  28968. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  28969. /**
  28970. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  28971. * about the currently running dispatch and/or the device it is running on.
  28972. *
  28973. * This node can only be used with a WebGPU backend.
  28974. *
  28975. * @augments Node
  28976. */
  28977. class ComputeBuiltinNode extends Node {
  28978. static get type() {
  28979. return 'ComputeBuiltinNode';
  28980. }
  28981. /**
  28982. * Constructs a new compute builtin node.
  28983. *
  28984. * @param {string} builtinName - The built-in name.
  28985. * @param {string} nodeType - The node type.
  28986. */
  28987. constructor( builtinName, nodeType ) {
  28988. super( nodeType );
  28989. /**
  28990. * The built-in name.
  28991. *
  28992. * @private
  28993. * @type {string}
  28994. */
  28995. this._builtinName = builtinName;
  28996. }
  28997. /**
  28998. * This method is overwritten since hash is derived from the built-in name.
  28999. *
  29000. * @param {NodeBuilder} builder - The current node builder.
  29001. * @return {string} The hash.
  29002. */
  29003. getHash( builder ) {
  29004. return this.getBuiltinName( builder );
  29005. }
  29006. /**
  29007. * This method is overwritten since the node type is simply derived from `nodeType`..
  29008. *
  29009. * @param {NodeBuilder} builder - The current node builder.
  29010. * @return {string} The node type.
  29011. */
  29012. getNodeType( /*builder*/ ) {
  29013. return this.nodeType;
  29014. }
  29015. /**
  29016. * Sets the builtin name.
  29017. *
  29018. * @param {string} builtinName - The built-in name.
  29019. * @return {ComputeBuiltinNode} A reference to this node.
  29020. */
  29021. setBuiltinName( builtinName ) {
  29022. this._builtinName = builtinName;
  29023. return this;
  29024. }
  29025. /**
  29026. * Returns the builtin name.
  29027. *
  29028. * @param {NodeBuilder} builder - The current node builder.
  29029. * @return {string} The builtin name.
  29030. */
  29031. getBuiltinName( /*builder*/ ) {
  29032. return this._builtinName;
  29033. }
  29034. /**
  29035. * Whether the current node builder has the builtin or not.
  29036. *
  29037. * @param {NodeBuilder} builder - The current node builder.
  29038. * @return {boolean} Whether the builder has the builtin or not.
  29039. */
  29040. hasBuiltin( builder ) {
  29041. return builder.hasBuiltin( this._builtinName );
  29042. }
  29043. generate( builder, output ) {
  29044. const builtinName = this.getBuiltinName( builder );
  29045. const nodeType = this.getNodeType( builder );
  29046. if ( builder.shaderStage === 'compute' ) {
  29047. return builder.format( builtinName, nodeType, output );
  29048. } else {
  29049. warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  29050. return builder.generateConst( nodeType );
  29051. }
  29052. }
  29053. serialize( data ) {
  29054. super.serialize( data );
  29055. data.global = this.global;
  29056. data._builtinName = this._builtinName;
  29057. }
  29058. deserialize( data ) {
  29059. super.deserialize( data );
  29060. this.global = data.global;
  29061. this._builtinName = data._builtinName;
  29062. }
  29063. }
  29064. /**
  29065. * TSL function for creating a compute builtin node.
  29066. *
  29067. * @tsl
  29068. * @function
  29069. * @param {string} name - The built-in name.
  29070. * @param {string} nodeType - The node type.
  29071. * @returns {ComputeBuiltinNode}
  29072. */
  29073. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  29074. /**
  29075. * Represents the number of workgroups dispatched by the compute shader.
  29076. * ```js
  29077. * // Run 512 invocations/threads with a workgroup size of 128.
  29078. * const computeFn = Fn(() => {
  29079. *
  29080. * // numWorkgroups.x = 4
  29081. * storageBuffer.element(0).assign(numWorkgroups.x)
  29082. *
  29083. * })().compute(512, [128]);
  29084. *
  29085. * // Run 512 invocations/threads with the default workgroup size of 64.
  29086. * const computeFn = Fn(() => {
  29087. *
  29088. * // numWorkgroups.x = 8
  29089. * storageBuffer.element(0).assign(numWorkgroups.x)
  29090. *
  29091. * })().compute(512);
  29092. * ```
  29093. *
  29094. * @tsl
  29095. * @type {ComputeBuiltinNode<uvec3>}
  29096. */
  29097. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  29098. /**
  29099. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  29100. * ```js
  29101. * // Execute 12 compute threads with a workgroup size of 3.
  29102. * const computeFn = Fn( () => {
  29103. *
  29104. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  29105. *
  29106. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  29107. *
  29108. * } ).Else( () => {
  29109. *
  29110. * storageBuffer.element( instanceIndex ).assign( 0 );
  29111. *
  29112. * } );
  29113. *
  29114. * } )().compute( 12, [ 3 ] );
  29115. *
  29116. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  29117. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  29118. * ```
  29119. *
  29120. * @tsl
  29121. * @type {ComputeBuiltinNode<uvec3>}
  29122. */
  29123. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  29124. /**
  29125. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  29126. *
  29127. * @tsl
  29128. * @type {ComputeBuiltinNode<uvec3>}
  29129. */
  29130. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  29131. /**
  29132. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  29133. *
  29134. * @tsl
  29135. * @type {ComputeBuiltinNode<uvec3>}
  29136. */
  29137. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  29138. /**
  29139. * A device dependent variable that exposes the size of the current invocation's subgroup.
  29140. *
  29141. * @tsl
  29142. * @type {ComputeBuiltinNode<uint>}
  29143. */
  29144. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  29145. /**
  29146. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  29147. *
  29148. * This node can only be used with a WebGPU backend.
  29149. *
  29150. * @augments Node
  29151. */
  29152. class BarrierNode extends Node {
  29153. /**
  29154. * Constructs a new barrier node.
  29155. *
  29156. * @param {string} scope - The scope defines the behavior of the node.
  29157. */
  29158. constructor( scope ) {
  29159. super();
  29160. this.scope = scope;
  29161. }
  29162. generate( builder ) {
  29163. const { scope } = this;
  29164. const { renderer } = builder;
  29165. if ( renderer.backend.isWebGLBackend === true ) {
  29166. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  29167. } else {
  29168. builder.addLineFlowCode( `${scope}Barrier()`, this );
  29169. }
  29170. }
  29171. }
  29172. /**
  29173. * TSL function for creating a barrier node.
  29174. *
  29175. * @tsl
  29176. * @function
  29177. * @param {string} scope - The scope defines the behavior of the node..
  29178. * @returns {BarrierNode}
  29179. */
  29180. const barrier = nodeProxy( BarrierNode );
  29181. /**
  29182. * TSL function for creating a workgroup barrier. All compute shader
  29183. * invocations must wait for each invocation within a workgroup to
  29184. * complete before the barrier can be surpassed.
  29185. *
  29186. * @tsl
  29187. * @function
  29188. * @returns {BarrierNode}
  29189. */
  29190. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  29191. /**
  29192. * TSL function for creating a storage barrier. All invocations must
  29193. * wait for each access to variables within the 'storage' address space
  29194. * to complete before the barrier can be passed.
  29195. *
  29196. * @tsl
  29197. * @function
  29198. * @returns {BarrierNode}
  29199. */
  29200. const storageBarrier = () => barrier( 'storage' ).toStack();
  29201. /**
  29202. * TSL function for creating a texture barrier. All invocations must
  29203. * wait for each access to variables within the 'texture' address space
  29204. * to complete before the barrier can be passed.
  29205. *
  29206. * @tsl
  29207. * @function
  29208. * @returns {BarrierNode}
  29209. */
  29210. const textureBarrier = () => barrier( 'texture' ).toStack();
  29211. /**
  29212. * Represents an element of a 'workgroup' scoped buffer.
  29213. *
  29214. * @augments ArrayElementNode
  29215. */
  29216. class WorkgroupInfoElementNode extends ArrayElementNode {
  29217. /**
  29218. * Constructs a new workgroup info element node.
  29219. *
  29220. * @param {Node} workgroupInfoNode - The workgroup info node.
  29221. * @param {Node} indexNode - The index node that defines the element access.
  29222. */
  29223. constructor( workgroupInfoNode, indexNode ) {
  29224. super( workgroupInfoNode, indexNode );
  29225. /**
  29226. * This flag can be used for type testing.
  29227. *
  29228. * @type {boolean}
  29229. * @readonly
  29230. * @default true
  29231. */
  29232. this.isWorkgroupInfoElementNode = true;
  29233. }
  29234. generate( builder, output ) {
  29235. let snippet;
  29236. const isAssignContext = builder.context.assign;
  29237. snippet = super.generate( builder );
  29238. if ( isAssignContext !== true ) {
  29239. const type = this.getNodeType( builder );
  29240. snippet = builder.format( snippet, type, output );
  29241. }
  29242. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  29243. return snippet;
  29244. }
  29245. }
  29246. /**
  29247. * A node allowing the user to create a 'workgroup' scoped buffer within the
  29248. * context of a compute shader. Typically, workgroup scoped buffers are
  29249. * created to hold data that is transferred from a global storage scope into
  29250. * a local workgroup scope. For invocations within a workgroup, data
  29251. * access speeds on 'workgroup' scoped buffers can be significantly faster
  29252. * than similar access operations on globally accessible storage buffers.
  29253. *
  29254. * This node can only be used with a WebGPU backend.
  29255. *
  29256. * @augments Node
  29257. */
  29258. class WorkgroupInfoNode extends Node {
  29259. /**
  29260. * Constructs a new buffer scoped to type scope.
  29261. *
  29262. * @param {string} scope - TODO.
  29263. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  29264. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  29265. */
  29266. constructor( scope, bufferType, bufferCount = 0 ) {
  29267. super( bufferType );
  29268. /**
  29269. * The buffer type.
  29270. *
  29271. * @type {string}
  29272. */
  29273. this.bufferType = bufferType;
  29274. /**
  29275. * The buffer count.
  29276. *
  29277. * @type {number}
  29278. * @default 0
  29279. */
  29280. this.bufferCount = bufferCount;
  29281. /**
  29282. * This flag can be used for type testing.
  29283. *
  29284. * @type {boolean}
  29285. * @readonly
  29286. * @default true
  29287. */
  29288. this.isWorkgroupInfoNode = true;
  29289. /**
  29290. * The data type of the array buffer.
  29291. *
  29292. * @type {string}
  29293. */
  29294. this.elementType = bufferType;
  29295. /**
  29296. * TODO.
  29297. *
  29298. * @type {string}
  29299. */
  29300. this.scope = scope;
  29301. /**
  29302. * The name of the workgroup scoped buffer.
  29303. *
  29304. * @type {string}
  29305. * @default ''
  29306. */
  29307. this.name = '';
  29308. }
  29309. /**
  29310. * Sets the name of this node.
  29311. *
  29312. * @param {string} name - The name to set.
  29313. * @return {WorkgroupInfoNode} A reference to this node.
  29314. */
  29315. setName( name ) {
  29316. this.name = name;
  29317. return this;
  29318. }
  29319. /**
  29320. * Sets the name/label of this node.
  29321. *
  29322. * @deprecated
  29323. * @param {string} name - The name to set.
  29324. * @return {WorkgroupInfoNode} A reference to this node.
  29325. */
  29326. label( name ) {
  29327. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  29328. return this.setName( name );
  29329. }
  29330. /**
  29331. * Sets the scope of this node.
  29332. *
  29333. * @param {string} scope - The scope to set.
  29334. * @return {WorkgroupInfoNode} A reference to this node.
  29335. */
  29336. setScope( scope ) {
  29337. this.scope = scope;
  29338. return this;
  29339. }
  29340. /**
  29341. * The data type of the array buffer.
  29342. *
  29343. * @return {string} The element type.
  29344. */
  29345. getElementType() {
  29346. return this.elementType;
  29347. }
  29348. /**
  29349. * Overwrites the default implementation since the input type
  29350. * is inferred from the scope.
  29351. *
  29352. * @param {NodeBuilder} builder - The current node builder.
  29353. * @return {string} The input type.
  29354. */
  29355. getInputType( /*builder*/ ) {
  29356. return `${this.scope}Array`;
  29357. }
  29358. /**
  29359. * This method can be used to access elements via an index node.
  29360. *
  29361. * @param {IndexNode} indexNode - indexNode.
  29362. * @return {WorkgroupInfoElementNode} A reference to an element.
  29363. */
  29364. element( indexNode ) {
  29365. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  29366. }
  29367. generate( builder ) {
  29368. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  29369. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  29370. }
  29371. }
  29372. /**
  29373. * TSL function for creating a workgroup info node.
  29374. * Creates a new 'workgroup' scoped array buffer.
  29375. *
  29376. * @tsl
  29377. * @function
  29378. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  29379. * @param {number} [count=0] - The number of elements in the buffer.
  29380. * @returns {WorkgroupInfoNode}
  29381. */
  29382. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  29383. /**
  29384. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  29385. * within a shader. In an atomic function, any modification to an atomic variable will
  29386. * occur as an indivisible step with a defined order relative to other modifications.
  29387. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  29388. * atomic operations will not interfere with each other.
  29389. *
  29390. * This node can only be used with a WebGPU backend.
  29391. *
  29392. * @augments Node
  29393. */
  29394. class AtomicFunctionNode extends Node {
  29395. static get type() {
  29396. return 'AtomicFunctionNode';
  29397. }
  29398. /**
  29399. * Constructs a new atomic function node.
  29400. *
  29401. * @param {string} method - The signature of the atomic function to construct.
  29402. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29403. * @param {Node} valueNode - The value that mutates the atomic variable.
  29404. */
  29405. constructor( method, pointerNode, valueNode ) {
  29406. super( 'uint' );
  29407. /**
  29408. * The signature of the atomic function to construct.
  29409. *
  29410. * @type {string}
  29411. */
  29412. this.method = method;
  29413. /**
  29414. * An atomic variable or element of an atomic buffer.
  29415. *
  29416. * @type {Node}
  29417. */
  29418. this.pointerNode = pointerNode;
  29419. /**
  29420. * A value that modifies the atomic variable.
  29421. *
  29422. * @type {Node}
  29423. */
  29424. this.valueNode = valueNode;
  29425. /**
  29426. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  29427. *
  29428. * @type {boolean}
  29429. * @default true
  29430. */
  29431. this.parents = true;
  29432. }
  29433. /**
  29434. * Overwrites the default implementation to return the type of
  29435. * the pointer node.
  29436. *
  29437. * @param {NodeBuilder} builder - The current node builder.
  29438. * @return {string} The input type.
  29439. */
  29440. getInputType( builder ) {
  29441. return this.pointerNode.getNodeType( builder );
  29442. }
  29443. /**
  29444. * Overwritten since the node type is inferred from the input type.
  29445. *
  29446. * @param {NodeBuilder} builder - The current node builder.
  29447. * @return {string} The node type.
  29448. */
  29449. getNodeType( builder ) {
  29450. return this.getInputType( builder );
  29451. }
  29452. generate( builder ) {
  29453. const properties = builder.getNodeProperties( this );
  29454. const parents = properties.parents;
  29455. const method = this.method;
  29456. const type = this.getNodeType( builder );
  29457. const inputType = this.getInputType( builder );
  29458. const a = this.pointerNode;
  29459. const b = this.valueNode;
  29460. const params = [];
  29461. params.push( `&${ a.build( builder, inputType ) }` );
  29462. if ( b !== null ) {
  29463. params.push( b.build( builder, inputType ) );
  29464. }
  29465. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  29466. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  29467. if ( isVoid ) {
  29468. builder.addLineFlowCode( methodSnippet, this );
  29469. } else {
  29470. if ( properties.constNode === undefined ) {
  29471. properties.constNode = expression( methodSnippet, type ).toConst();
  29472. }
  29473. return properties.constNode.build( builder );
  29474. }
  29475. }
  29476. }
  29477. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  29478. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  29479. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  29480. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  29481. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  29482. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  29483. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  29484. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  29485. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  29486. /**
  29487. * TSL function for creating an atomic function node.
  29488. *
  29489. * @tsl
  29490. * @function
  29491. * @param {string} method - The signature of the atomic function to construct.
  29492. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29493. * @param {Node} valueNode - The value that mutates the atomic variable.
  29494. * @returns {AtomicFunctionNode}
  29495. */
  29496. const atomicNode = nodeProxy( AtomicFunctionNode );
  29497. /**
  29498. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  29499. *
  29500. * @tsl
  29501. * @function
  29502. * @param {string} method - The signature of the atomic function to construct.
  29503. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29504. * @param {Node} valueNode - The value that mutates the atomic variable.
  29505. * @returns {AtomicFunctionNode}
  29506. */
  29507. const atomicFunc = ( method, pointerNode, valueNode ) => {
  29508. return atomicNode( method, pointerNode, valueNode ).toStack();
  29509. };
  29510. /**
  29511. * Loads the value stored in the atomic variable.
  29512. *
  29513. * @tsl
  29514. * @function
  29515. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29516. * @returns {AtomicFunctionNode}
  29517. */
  29518. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  29519. /**
  29520. * Stores a value in the atomic variable.
  29521. *
  29522. * @tsl
  29523. * @function
  29524. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29525. * @param {Node} valueNode - The value that mutates the atomic variable.
  29526. * @returns {AtomicFunctionNode}
  29527. */
  29528. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  29529. /**
  29530. * Increments the value stored in the atomic variable.
  29531. *
  29532. * @tsl
  29533. * @function
  29534. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29535. * @param {Node} valueNode - The value that mutates the atomic variable.
  29536. * @returns {AtomicFunctionNode}
  29537. */
  29538. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  29539. /**
  29540. * Decrements the value stored in the atomic variable.
  29541. *
  29542. * @tsl
  29543. * @function
  29544. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29545. * @param {Node} valueNode - The value that mutates the atomic variable.
  29546. * @returns {AtomicFunctionNode}
  29547. */
  29548. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  29549. /**
  29550. * Stores in an atomic variable the maximum between its current value and a parameter.
  29551. *
  29552. * @tsl
  29553. * @function
  29554. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29555. * @param {Node} valueNode - The value that mutates the atomic variable.
  29556. * @returns {AtomicFunctionNode}
  29557. */
  29558. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  29559. /**
  29560. * Stores in an atomic variable the minimum between its current value and a parameter.
  29561. *
  29562. * @tsl
  29563. * @function
  29564. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29565. * @param {Node} valueNode - The value that mutates the atomic variable.
  29566. * @returns {AtomicFunctionNode}
  29567. */
  29568. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  29569. /**
  29570. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  29571. *
  29572. * @tsl
  29573. * @function
  29574. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29575. * @param {Node} valueNode - The value that mutates the atomic variable.
  29576. * @returns {AtomicFunctionNode}
  29577. */
  29578. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  29579. /**
  29580. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  29581. *
  29582. * @tsl
  29583. * @function
  29584. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29585. * @param {Node} valueNode - The value that mutates the atomic variable.
  29586. * @returns {AtomicFunctionNode}
  29587. */
  29588. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  29589. /**
  29590. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  29591. *
  29592. * @tsl
  29593. * @function
  29594. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29595. * @param {Node} valueNode - The value that mutates the atomic variable.
  29596. * @returns {AtomicFunctionNode}
  29597. */
  29598. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  29599. /**
  29600. * This class represents a set of built in WGSL shader functions that sync
  29601. * synchronously execute an operation across a subgroup, or 'warp', of compute
  29602. * or fragment shader invocations within a workgroup. Typically, these functions
  29603. * will synchronously execute an operation using data from all active invocations
  29604. * within the subgroup, then broadcast that result to all active invocations. In
  29605. * other graphics APIs, subgroup functions are also referred to as wave intrinsics
  29606. * (DirectX/HLSL) or warp intrinsics (CUDA).
  29607. *
  29608. * @augments TempNode
  29609. */
  29610. class SubgroupFunctionNode extends TempNode {
  29611. static get type() {
  29612. return 'SubgroupFunctionNode';
  29613. }
  29614. /**
  29615. * Constructs a new function node.
  29616. *
  29617. * @param {string} method - The subgroup/wave intrinsic method to construct.
  29618. * @param {Node} [aNode=null] - The method's first argument.
  29619. * @param {Node} [bNode=null] - The method's second argument.
  29620. */
  29621. constructor( method, aNode = null, bNode = null ) {
  29622. super();
  29623. /**
  29624. * The subgroup/wave intrinsic method to construct.
  29625. *
  29626. * @type {String}
  29627. */
  29628. this.method = method;
  29629. /**
  29630. * The method's first argument.
  29631. *
  29632. * @type {Node}
  29633. */
  29634. this.aNode = aNode;
  29635. /**
  29636. * The method's second argument.
  29637. *
  29638. * @type {Node}
  29639. */
  29640. this.bNode = bNode;
  29641. }
  29642. getInputType( builder ) {
  29643. const aType = this.aNode ? this.aNode.getNodeType( builder ) : null;
  29644. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  29645. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  29646. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  29647. if ( aLen > bLen ) {
  29648. return aType;
  29649. } else {
  29650. return bType;
  29651. }
  29652. }
  29653. getNodeType( builder ) {
  29654. const method = this.method;
  29655. if ( method === SubgroupFunctionNode.SUBGROUP_ELECT ) {
  29656. return 'bool';
  29657. } else if ( method === SubgroupFunctionNode.SUBGROUP_BALLOT ) {
  29658. return 'uvec4';
  29659. } else {
  29660. return this.getInputType( builder );
  29661. }
  29662. }
  29663. generate( builder, output ) {
  29664. const method = this.method;
  29665. const type = this.getNodeType( builder );
  29666. const inputType = this.getInputType( builder );
  29667. const a = this.aNode;
  29668. const b = this.bNode;
  29669. const params = [];
  29670. if (
  29671. method === SubgroupFunctionNode.SUBGROUP_BROADCAST ||
  29672. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE ||
  29673. method === SubgroupFunctionNode.QUAD_BROADCAST
  29674. ) {
  29675. const bType = b.getNodeType( builder );
  29676. params.push(
  29677. a.build( builder, type ),
  29678. b.build( builder, bType === 'float' ? 'int' : type )
  29679. );
  29680. } else if (
  29681. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ||
  29682. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ||
  29683. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP
  29684. ) {
  29685. params.push(
  29686. a.build( builder, type ),
  29687. b.build( builder, 'uint' )
  29688. );
  29689. } else {
  29690. if ( a !== null ) params.push( a.build( builder, inputType ) );
  29691. if ( b !== null ) params.push( b.build( builder, inputType ) );
  29692. }
  29693. const paramsString = params.length === 0 ? '()' : `( ${params.join( ', ' )} )`;
  29694. return builder.format( `${ builder.getMethod( method, type ) }${paramsString}`, type, output );
  29695. }
  29696. serialize( data ) {
  29697. super.serialize( data );
  29698. data.method = this.method;
  29699. }
  29700. deserialize( data ) {
  29701. super.deserialize( data );
  29702. this.method = data.method;
  29703. }
  29704. }
  29705. // 0 inputs
  29706. SubgroupFunctionNode.SUBGROUP_ELECT = 'subgroupElect';
  29707. // 1 input
  29708. SubgroupFunctionNode.SUBGROUP_BALLOT = 'subgroupBallot';
  29709. SubgroupFunctionNode.SUBGROUP_ADD = 'subgroupAdd';
  29710. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD = 'subgroupInclusiveAdd';
  29711. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND = 'subgroupExclusiveAdd';
  29712. SubgroupFunctionNode.SUBGROUP_MUL = 'subgroupMul';
  29713. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL = 'subgroupInclusiveMul';
  29714. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL = 'subgroupExclusiveMul';
  29715. SubgroupFunctionNode.SUBGROUP_AND = 'subgroupAnd';
  29716. SubgroupFunctionNode.SUBGROUP_OR = 'subgroupOr';
  29717. SubgroupFunctionNode.SUBGROUP_XOR = 'subgroupXor';
  29718. SubgroupFunctionNode.SUBGROUP_MIN = 'subgroupMin';
  29719. SubgroupFunctionNode.SUBGROUP_MAX = 'subgroupMax';
  29720. SubgroupFunctionNode.SUBGROUP_ALL = 'subgroupAll';
  29721. SubgroupFunctionNode.SUBGROUP_ANY = 'subgroupAny';
  29722. SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST = 'subgroupBroadcastFirst';
  29723. SubgroupFunctionNode.QUAD_SWAP_X = 'quadSwapX';
  29724. SubgroupFunctionNode.QUAD_SWAP_Y = 'quadSwapY';
  29725. SubgroupFunctionNode.QUAD_SWAP_DIAGONAL = 'quadSwapDiagonal';
  29726. // 2 inputs
  29727. SubgroupFunctionNode.SUBGROUP_BROADCAST = 'subgroupBroadcast';
  29728. SubgroupFunctionNode.SUBGROUP_SHUFFLE = 'subgroupShuffle';
  29729. SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR = 'subgroupShuffleXor';
  29730. SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP = 'subgroupShuffleUp';
  29731. SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN = 'subgroupShuffleDown';
  29732. SubgroupFunctionNode.QUAD_BROADCAST = 'quadBroadcast';
  29733. /**
  29734. * Returns true if this invocation has the lowest subgroup_invocation_id
  29735. * among active invocations in the subgroup.
  29736. *
  29737. * @tsl
  29738. * @method
  29739. * @return {bool} The result of the computation.
  29740. */
  29741. const subgroupElect = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ELECT ).setParameterLength( 0 );
  29742. /**
  29743. * Returns a set of bitfields where the bit corresponding to subgroup_invocation_id
  29744. * is 1 if pred is true for that active invocation and 0 otherwise.
  29745. *
  29746. * @tsl
  29747. * @method
  29748. * @param {bool} pred - A boolean that sets the bit corresponding to the invocations subgroup invocation id.
  29749. * @return {vec4<u32>}- A bitfield corresponding to the pred value of each subgroup invocation.
  29750. */
  29751. const subgroupBallot = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BALLOT ).setParameterLength( 1 );
  29752. /**
  29753. * A reduction that adds e among all active invocations and returns that result.
  29754. *
  29755. * @tsl
  29756. * @method
  29757. * @param {number} e - The value provided to the reduction by the current invocation.
  29758. * @return {number} The accumulated result of the reduction operation.
  29759. */
  29760. const subgroupAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ADD ).setParameterLength( 1 );
  29761. /**
  29762. * An inclusive scan returning the sum of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  29763. *
  29764. * @tsl
  29765. * @method
  29766. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  29767. * @return {number} The accumulated result of the inclusive scan operation.
  29768. */
  29769. const subgroupInclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD ).setParameterLength( 1 );
  29770. /**
  29771. * An exclusive scan that returns the sum of e for all active invocations with subgroup_invocation_id less than this invocation.
  29772. *
  29773. * @tsl
  29774. * @method
  29775. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  29776. * @return {number} The accumulated result of the exclusive scan operation.
  29777. */
  29778. const subgroupExclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND ).setParameterLength( 1 );
  29779. /**
  29780. * A reduction that multiplies e among all active invocations and returns that result.
  29781. *
  29782. * @tsl
  29783. * @method
  29784. * @param {number} e - The value provided to the reduction by the current invocation.
  29785. * @return {number} The accumulated result of the reduction operation.
  29786. */
  29787. const subgroupMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MUL ).setParameterLength( 1 );
  29788. /**
  29789. * An inclusive scan returning the product of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  29790. *
  29791. * @tsl
  29792. * @method
  29793. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  29794. * @return {number} The accumulated result of the inclusive scan operation.
  29795. */
  29796. const subgroupInclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL ).setParameterLength( 1 );
  29797. /**
  29798. * An exclusive scan that returns the product of e for all active invocations with subgroup_invocation_id less than this invocation.
  29799. *
  29800. * @tsl
  29801. * @method
  29802. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  29803. * @return {number} The accumulated result of the exclusive scan operation.
  29804. */
  29805. const subgroupExclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL ).setParameterLength( 1 );
  29806. /**
  29807. * A reduction that performs a bitwise and of e among all active invocations and returns that result.
  29808. *
  29809. * @tsl
  29810. * @method
  29811. * @param {number} e - The value provided to the reduction by the current invocation.
  29812. * @return {number} The result of the reduction operation.
  29813. */
  29814. const subgroupAnd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_AND ).setParameterLength( 1 );
  29815. /**
  29816. * A reduction that performs a bitwise or of e among all active invocations and returns that result.
  29817. *
  29818. * @tsl
  29819. * @method
  29820. * @param {number} e - The value provided to the reduction by the current invocation.
  29821. * @return {number} The result of the reduction operation.
  29822. */
  29823. const subgroupOr = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_OR ).setParameterLength( 1 );
  29824. /**
  29825. * A reduction that performs a bitwise xor of e among all active invocations and returns that result.
  29826. *
  29827. * @tsl
  29828. * @method
  29829. * @param {number} e - The value provided to the reduction by the current invocation.
  29830. * @return {number} The result of the reduction operation.
  29831. */
  29832. const subgroupXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_XOR ).setParameterLength( 1 );
  29833. /**
  29834. * A reduction that performs a min of e among all active invocations and returns that result.
  29835. *
  29836. * @tsl
  29837. * @method
  29838. * @param {number} e - The value provided to the reduction by the current invocation.
  29839. * @return {number} The result of the reduction operation.
  29840. */
  29841. const subgroupMin = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MIN ).setParameterLength( 1 );
  29842. /**
  29843. * A reduction that performs a max of e among all active invocations and returns that result.
  29844. *
  29845. * @tsl
  29846. * @method
  29847. * @param {number} e - The value provided to the reduction by the current invocation.
  29848. * @return {number} The result of the reduction operation.
  29849. */
  29850. const subgroupMax = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MAX ).setParameterLength( 1 );
  29851. /**
  29852. * Returns true if e is true for all active invocations in the subgroup.
  29853. *
  29854. * @tsl
  29855. * @method
  29856. * @return {bool} The result of the computation.
  29857. */
  29858. const subgroupAll = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ALL ).setParameterLength( 0 );
  29859. /**
  29860. * Returns true if e is true for any active invocation in the subgroup
  29861. *
  29862. * @tsl
  29863. * @method
  29864. * @return {bool} The result of the computation.
  29865. */
  29866. const subgroupAny = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ANY ).setParameterLength( 0 );
  29867. /**
  29868. * Broadcasts e from the active invocation with the lowest subgroup_invocation_id in the subgroup to all other active invocations.
  29869. *
  29870. * @tsl
  29871. * @method
  29872. * @param {number} e - The value to broadcast from the lowest subgroup invocation.
  29873. * @param {number} id - The subgroup invocation to broadcast from.
  29874. * @return {number} The broadcast value.
  29875. */
  29876. const subgroupBroadcastFirst = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST ).setParameterLength( 2 );
  29877. /**
  29878. * Swaps e between invocations in the quad in the X direction.
  29879. *
  29880. * @tsl
  29881. * @method
  29882. * @param {number} e - The value to swap from the current invocation.
  29883. * @return {number} The value received from the swap operation.
  29884. */
  29885. const quadSwapX = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_X ).setParameterLength( 1 );
  29886. /**
  29887. * Swaps e between invocations in the quad in the Y direction.
  29888. *
  29889. * @tsl
  29890. * @method
  29891. * @param {number} e - The value to swap from the current invocation.
  29892. * @return {number} The value received from the swap operation.
  29893. */
  29894. const quadSwapY = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_Y ).setParameterLength( 1 );
  29895. /**
  29896. * Swaps e between invocations in the quad diagonally.
  29897. *
  29898. * @tsl
  29899. * @method
  29900. * @param {number} e - The value to swap from the current invocation.
  29901. * @return {number} The value received from the swap operation.
  29902. */
  29903. const quadSwapDiagonal = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_DIAGONAL ).setParameterLength( 1 );
  29904. /**
  29905. * Broadcasts e from the invocation whose subgroup_invocation_id matches id, to all active invocations.
  29906. *
  29907. * @tsl
  29908. * @method
  29909. * @param {number} e - The value to broadcast from subgroup invocation 'id'.
  29910. * @param {number} id - The subgroup invocation to broadcast from.
  29911. * @return {number} The broadcast value.
  29912. */
  29913. const subgroupBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST ).setParameterLength( 2 );
  29914. /**
  29915. * Returns v from the active invocation whose subgroup_invocation_id matches id
  29916. *
  29917. * @tsl
  29918. * @method
  29919. * @param {number} v - The value to return from subgroup invocation id^mask.
  29920. * @param {number} id - The subgroup invocation which returns the value v.
  29921. * @return {number} The broadcast value.
  29922. */
  29923. const subgroupShuffle = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE ).setParameterLength( 2 );
  29924. /**
  29925. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id ^ mask.
  29926. *
  29927. * @tsl
  29928. * @method
  29929. * @param {number} v - The value to return from subgroup invocation id^mask.
  29930. * @param {number} mask - A bitmask that determines the target invocation via a XOR operation.
  29931. * @return {number} The broadcast value.
  29932. */
  29933. const subgroupShuffleXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ).setParameterLength( 2 );
  29934. /**
  29935. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id - delta
  29936. *
  29937. * @tsl
  29938. * @method
  29939. * @param {number} v - The value to return from subgroup invocation id^mask.
  29940. * @param {number} delta - A value that offsets the current in.
  29941. * @return {number} The broadcast value.
  29942. */
  29943. const subgroupShuffleUp = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP ).setParameterLength( 2 );
  29944. /**
  29945. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id + delta
  29946. *
  29947. * @tsl
  29948. * @method
  29949. * @param {number} v - The value to return from subgroup invocation id^mask.
  29950. * @param {number} delta - A value that offsets the current subgroup invocation.
  29951. * @return {number} The broadcast value.
  29952. */
  29953. const subgroupShuffleDown = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ).setParameterLength( 2 );
  29954. /**
  29955. * Broadcasts e from the quad invocation with id equal to id.
  29956. *
  29957. * @tsl
  29958. * @method
  29959. * @param {number} e - The value to broadcast.
  29960. * @return {number} The broadcast value.
  29961. */
  29962. const quadBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_BROADCAST ).setParameterLength( 1 );
  29963. let uniformsLib;
  29964. function getLightData( light ) {
  29965. uniformsLib = uniformsLib || new WeakMap();
  29966. let uniforms = uniformsLib.get( light );
  29967. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  29968. return uniforms;
  29969. }
  29970. /**
  29971. * TSL function for getting a shadow matrix uniform node for the given light.
  29972. *
  29973. * @tsl
  29974. * @function
  29975. * @param {Light} light -The light source.
  29976. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  29977. */
  29978. function lightShadowMatrix( light ) {
  29979. const data = getLightData( light );
  29980. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  29981. // normally, shadow matrices are updated in ShadowNode. However, if the shadow matrix is used outside
  29982. // of shadow rendering (like in ProjectorLightNode), the shadow matrix still requires an update
  29983. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  29984. if ( light.shadow.camera.coordinateSystem !== frame.camera.coordinateSystem ) {
  29985. light.shadow.camera.coordinateSystem = frame.camera.coordinateSystem;
  29986. light.shadow.camera.updateProjectionMatrix();
  29987. }
  29988. light.shadow.updateMatrices( light );
  29989. }
  29990. return light.shadow.matrix;
  29991. } ) );
  29992. }
  29993. /**
  29994. * TSL function for getting projected uv coordinates for the given light.
  29995. * Relevant when using maps with spot lights.
  29996. *
  29997. * @tsl
  29998. * @function
  29999. * @param {Light} light -The light source.
  30000. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  30001. * @returns {Node<vec3>} The projected uvs.
  30002. */
  30003. function lightProjectionUV( light, position = positionWorld ) {
  30004. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  30005. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  30006. return projectionUV;
  30007. }
  30008. /**
  30009. * TSL function for getting the position in world space for the given light.
  30010. *
  30011. * @tsl
  30012. * @function
  30013. * @param {Light} light -The light source.
  30014. * @returns {UniformNode<vec3>} The light's position in world space.
  30015. */
  30016. function lightPosition( light ) {
  30017. const data = getLightData( light );
  30018. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  30019. }
  30020. /**
  30021. * TSL function for getting the light target position in world space for the given light.
  30022. *
  30023. * @tsl
  30024. * @function
  30025. * @param {Light} light -The light source.
  30026. * @returns {UniformNode<vec3>} The light target position in world space.
  30027. */
  30028. function lightTargetPosition( light ) {
  30029. const data = getLightData( light );
  30030. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  30031. }
  30032. /**
  30033. * TSL function for getting the position in view space for the given light.
  30034. *
  30035. * @tsl
  30036. * @function
  30037. * @param {Light} light - The light source.
  30038. * @returns {UniformNode<vec3>} The light's position in view space.
  30039. */
  30040. function lightViewPosition( light ) {
  30041. const data = getLightData( light );
  30042. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  30043. self.value = self.value || new Vector3();
  30044. self.value.setFromMatrixPosition( light.matrixWorld );
  30045. self.value.applyMatrix4( camera.matrixWorldInverse );
  30046. } ) );
  30047. }
  30048. /**
  30049. * TSL function for getting the light target direction for the given light.
  30050. *
  30051. * @tsl
  30052. * @function
  30053. * @param {Light} light -The light source.
  30054. * @returns {Node<vec3>} The light's target direction.
  30055. */
  30056. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  30057. const sortLights = ( lights ) => {
  30058. return lights.sort( ( a, b ) => a.id - b.id );
  30059. };
  30060. const getLightNodeById = ( id, lightNodes ) => {
  30061. for ( const lightNode of lightNodes ) {
  30062. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  30063. return lightNode;
  30064. }
  30065. }
  30066. return null;
  30067. };
  30068. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  30069. const _hashData = [];
  30070. /**
  30071. * This node represents the scene's lighting and manages the lighting model's life cycle
  30072. * for the current build 3D object. It is responsible for computing the total outgoing
  30073. * light in a given lighting context.
  30074. *
  30075. * @augments Node
  30076. */
  30077. class LightsNode extends Node {
  30078. static get type() {
  30079. return 'LightsNode';
  30080. }
  30081. /**
  30082. * Constructs a new lights node.
  30083. */
  30084. constructor() {
  30085. super( 'vec3' );
  30086. /**
  30087. * A node representing the total diffuse light.
  30088. *
  30089. * @type {Node<vec3>}
  30090. */
  30091. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  30092. /**
  30093. * A node representing the total specular light.
  30094. *
  30095. * @type {Node<vec3>}
  30096. */
  30097. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  30098. /**
  30099. * A node representing the outgoing light.
  30100. *
  30101. * @type {Node<vec3>}
  30102. */
  30103. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  30104. /**
  30105. * An array representing the lights in the scene.
  30106. *
  30107. * @private
  30108. * @type {Array<Light>}
  30109. */
  30110. this._lights = [];
  30111. /**
  30112. * For each light in the scene, this node will create a
  30113. * corresponding light node.
  30114. *
  30115. * @private
  30116. * @type {?Array<LightingNode>}
  30117. * @default null
  30118. */
  30119. this._lightNodes = null;
  30120. /**
  30121. * A hash for identifying the current light nodes setup.
  30122. *
  30123. * @private
  30124. * @type {?string}
  30125. * @default null
  30126. */
  30127. this._lightNodesHash = null;
  30128. /**
  30129. * `LightsNode` sets this property to `true` by default.
  30130. *
  30131. * @type {boolean}
  30132. * @default true
  30133. */
  30134. this.global = true;
  30135. }
  30136. /**
  30137. * Overwrites the default {@link Node#customCacheKey} implementation by including
  30138. * light data into the cache key.
  30139. *
  30140. * @return {number} The custom cache key.
  30141. */
  30142. customCacheKey() {
  30143. const lights = this._lights;
  30144. for ( let i = 0; i < lights.length; i ++ ) {
  30145. const light = lights[ i ];
  30146. _hashData.push( light.id );
  30147. _hashData.push( light.castShadow ? 1 : 0 );
  30148. if ( light.isSpotLight === true ) {
  30149. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  30150. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  30151. _hashData.push( hashMap, hashColorNode );
  30152. }
  30153. }
  30154. const cacheKey = hashArray( _hashData );
  30155. _hashData.length = 0;
  30156. return cacheKey;
  30157. }
  30158. /**
  30159. * Computes a hash value for identifying the current light nodes setup.
  30160. *
  30161. * @param {NodeBuilder} builder - A reference to the current node builder.
  30162. * @return {string} The computed hash.
  30163. */
  30164. getHash( builder ) {
  30165. if ( this._lightNodesHash === null ) {
  30166. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  30167. const hash = [];
  30168. for ( const lightNode of this._lightNodes ) {
  30169. hash.push( lightNode.getHash() );
  30170. }
  30171. this._lightNodesHash = 'lights-' + hash.join( ',' );
  30172. }
  30173. return this._lightNodesHash;
  30174. }
  30175. analyze( builder ) {
  30176. const properties = builder.getNodeProperties( this );
  30177. for ( const node of properties.nodes ) {
  30178. node.build( builder );
  30179. }
  30180. properties.outputNode.build( builder );
  30181. }
  30182. /**
  30183. * Creates lighting nodes for each scene light. This makes it possible to further
  30184. * process lights in the node system.
  30185. *
  30186. * @param {NodeBuilder} builder - A reference to the current node builder.
  30187. */
  30188. setupLightsNode( builder ) {
  30189. const lightNodes = [];
  30190. const previousLightNodes = this._lightNodes;
  30191. const lights = sortLights( this._lights );
  30192. const nodeLibrary = builder.renderer.library;
  30193. for ( const light of lights ) {
  30194. if ( light.isNode ) {
  30195. lightNodes.push( nodeObject( light ) );
  30196. } else {
  30197. let lightNode = null;
  30198. if ( previousLightNodes !== null ) {
  30199. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  30200. }
  30201. if ( lightNode === null ) {
  30202. // find the corresponding node type for a given light
  30203. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  30204. if ( lightNodeClass === null ) {
  30205. warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  30206. continue;
  30207. }
  30208. let lightNode = null;
  30209. if ( ! _lightsNodeRef.has( light ) ) {
  30210. lightNode = nodeObject( new lightNodeClass( light ) );
  30211. _lightsNodeRef.set( light, lightNode );
  30212. } else {
  30213. lightNode = _lightsNodeRef.get( light );
  30214. }
  30215. lightNodes.push( lightNode );
  30216. }
  30217. }
  30218. }
  30219. this._lightNodes = lightNodes;
  30220. }
  30221. /**
  30222. * Sets up a direct light in the lighting model.
  30223. *
  30224. * @param {Object} builder - The builder object containing the context and stack.
  30225. * @param {Object} lightNode - The light node.
  30226. * @param {Object} lightData - The light object containing color and direction properties.
  30227. */
  30228. setupDirectLight( builder, lightNode, lightData ) {
  30229. const { lightingModel, reflectedLight } = builder.context;
  30230. lightingModel.direct( {
  30231. ...lightData,
  30232. lightNode,
  30233. reflectedLight
  30234. }, builder );
  30235. }
  30236. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  30237. const { lightingModel, reflectedLight } = builder.context;
  30238. lightingModel.directRectArea( {
  30239. ...lightData,
  30240. lightNode,
  30241. reflectedLight
  30242. }, builder );
  30243. }
  30244. /**
  30245. * Setups the internal lights by building all respective
  30246. * light nodes.
  30247. *
  30248. * @param {NodeBuilder} builder - A reference to the current node builder.
  30249. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  30250. */
  30251. setupLights( builder, lightNodes ) {
  30252. for ( const lightNode of lightNodes ) {
  30253. lightNode.build( builder );
  30254. }
  30255. }
  30256. getLightNodes( builder ) {
  30257. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  30258. return this._lightNodes;
  30259. }
  30260. /**
  30261. * The implementation makes sure that for each light in the scene
  30262. * there is a corresponding light node. By building the light nodes
  30263. * and evaluating the lighting model the outgoing light is computed.
  30264. *
  30265. * @param {NodeBuilder} builder - A reference to the current node builder.
  30266. * @return {Node<vec3>} A node representing the outgoing light.
  30267. */
  30268. setup( builder ) {
  30269. const currentLightsNode = builder.lightsNode;
  30270. builder.lightsNode = this;
  30271. //
  30272. let outgoingLightNode = this.outgoingLightNode;
  30273. const context = builder.context;
  30274. const lightingModel = context.lightingModel;
  30275. const properties = builder.getNodeProperties( this );
  30276. if ( lightingModel ) {
  30277. const { totalDiffuseNode, totalSpecularNode } = this;
  30278. context.outgoingLight = outgoingLightNode;
  30279. const stack = builder.addStack();
  30280. //
  30281. properties.nodes = stack.nodes;
  30282. //
  30283. lightingModel.start( builder );
  30284. //
  30285. const { backdrop, backdropAlpha } = context;
  30286. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  30287. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  30288. if ( backdrop !== null ) {
  30289. if ( backdropAlpha !== null ) {
  30290. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  30291. } else {
  30292. totalDiffuse = vec3( backdrop );
  30293. }
  30294. }
  30295. totalDiffuseNode.assign( totalDiffuse );
  30296. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  30297. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  30298. //
  30299. lightingModel.finish( builder );
  30300. //
  30301. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  30302. } else {
  30303. properties.nodes = [];
  30304. }
  30305. //
  30306. builder.lightsNode = currentLightsNode;
  30307. return outgoingLightNode;
  30308. }
  30309. /**
  30310. * Configures this node with an array of lights.
  30311. *
  30312. * @param {Array<Light>} lights - An array of lights.
  30313. * @return {LightsNode} A reference to this node.
  30314. */
  30315. setLights( lights ) {
  30316. this._lights = lights;
  30317. this._lightNodes = null;
  30318. this._lightNodesHash = null;
  30319. return this;
  30320. }
  30321. /**
  30322. * Returns an array of the scene's lights.
  30323. *
  30324. * @return {Array<Light>} The scene's lights.
  30325. */
  30326. getLights() {
  30327. return this._lights;
  30328. }
  30329. /**
  30330. * Whether the scene has lights or not.
  30331. *
  30332. * @type {boolean}
  30333. */
  30334. get hasLights() {
  30335. return this._lights.length > 0;
  30336. }
  30337. }
  30338. /**
  30339. * TSL function for creating an instance of `LightsNode` and configuring
  30340. * it with the given array of lights.
  30341. *
  30342. * @tsl
  30343. * @function
  30344. * @param {Array<Light>} lights - An array of lights.
  30345. * @return {LightsNode} The created lights node.
  30346. */
  30347. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  30348. /**
  30349. * Base class for all shadow nodes.
  30350. *
  30351. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  30352. * Lighting nodes might share the same shadow node type or use specific ones depending on
  30353. * their requirements.
  30354. *
  30355. * @augments Node
  30356. */
  30357. class ShadowBaseNode extends Node {
  30358. static get type() {
  30359. return 'ShadowBaseNode';
  30360. }
  30361. /**
  30362. * Constructs a new shadow base node.
  30363. *
  30364. * @param {Light} light - The shadow casting light.
  30365. */
  30366. constructor( light ) {
  30367. super();
  30368. /**
  30369. * The shadow casting light.
  30370. *
  30371. * @type {Light}
  30372. */
  30373. this.light = light;
  30374. /**
  30375. * Overwritten since shadows are updated by default per render.
  30376. *
  30377. * @type {string}
  30378. * @default 'render'
  30379. */
  30380. this.updateBeforeType = NodeUpdateType.RENDER;
  30381. /**
  30382. * This flag can be used for type testing.
  30383. *
  30384. * @type {boolean}
  30385. * @readonly
  30386. * @default true
  30387. */
  30388. this.isShadowBaseNode = true;
  30389. }
  30390. /**
  30391. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  30392. *
  30393. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  30394. */
  30395. setupShadowPosition( { context, material } ) {
  30396. // Use assign inside an Fn()
  30397. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  30398. }
  30399. }
  30400. /**
  30401. * TSL object that represents the vertex position in world space during the shadow pass.
  30402. *
  30403. * @tsl
  30404. * @type {Node<vec3>}
  30405. */
  30406. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  30407. /**
  30408. * Saves the state of the given renderer and stores it into the given state object.
  30409. *
  30410. * If not state object is provided, the function creates one.
  30411. *
  30412. * @private
  30413. * @function
  30414. * @param {Renderer} renderer - The renderer.
  30415. * @param {Object} [state={}] - The state.
  30416. * @return {Object} The state.
  30417. */
  30418. function saveRendererState( renderer, state = {} ) {
  30419. state.toneMapping = renderer.toneMapping;
  30420. state.toneMappingExposure = renderer.toneMappingExposure;
  30421. state.outputColorSpace = renderer.outputColorSpace;
  30422. state.renderTarget = renderer.getRenderTarget();
  30423. state.activeCubeFace = renderer.getActiveCubeFace();
  30424. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  30425. state.renderObjectFunction = renderer.getRenderObjectFunction();
  30426. state.pixelRatio = renderer.getPixelRatio();
  30427. state.mrt = renderer.getMRT();
  30428. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  30429. state.clearAlpha = renderer.getClearAlpha();
  30430. state.autoClear = renderer.autoClear;
  30431. state.scissorTest = renderer.getScissorTest();
  30432. return state;
  30433. }
  30434. /**
  30435. * Saves the state of the given renderer and stores it into the given state object.
  30436. * Besides, the function also resets the state of the renderer to its default values.
  30437. *
  30438. * If not state object is provided, the function creates one.
  30439. *
  30440. * @private
  30441. * @function
  30442. * @param {Renderer} renderer - The renderer.
  30443. * @param {Object} [state={}] - The state.
  30444. * @return {Object} The state.
  30445. */
  30446. function resetRendererState( renderer, state ) {
  30447. state = saveRendererState( renderer, state );
  30448. renderer.setMRT( null );
  30449. renderer.setRenderObjectFunction( null );
  30450. renderer.setClearColor( 0x000000, 1 );
  30451. renderer.autoClear = true;
  30452. return state;
  30453. }
  30454. /**
  30455. * Restores the state of the given renderer from the given state object.
  30456. *
  30457. * @private
  30458. * @function
  30459. * @param {Renderer} renderer - The renderer.
  30460. * @param {Object} state - The state to restore.
  30461. */
  30462. function restoreRendererState( renderer, state ) {
  30463. renderer.toneMapping = state.toneMapping;
  30464. renderer.toneMappingExposure = state.toneMappingExposure;
  30465. renderer.outputColorSpace = state.outputColorSpace;
  30466. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  30467. renderer.setRenderObjectFunction( state.renderObjectFunction );
  30468. renderer.setPixelRatio( state.pixelRatio );
  30469. renderer.setMRT( state.mrt );
  30470. renderer.setClearColor( state.clearColor, state.clearAlpha );
  30471. renderer.autoClear = state.autoClear;
  30472. renderer.setScissorTest( state.scissorTest );
  30473. }
  30474. /**
  30475. * Saves the state of the given scene and stores it into the given state object.
  30476. *
  30477. * If not state object is provided, the function creates one.
  30478. *
  30479. * @private
  30480. * @function
  30481. * @param {Scene} scene - The scene.
  30482. * @param {Object} [state={}] - The state.
  30483. * @return {Object} The state.
  30484. */
  30485. function saveSceneState( scene, state = {} ) {
  30486. state.background = scene.background;
  30487. state.backgroundNode = scene.backgroundNode;
  30488. state.overrideMaterial = scene.overrideMaterial;
  30489. return state;
  30490. }
  30491. /**
  30492. * Saves the state of the given scene and stores it into the given state object.
  30493. * Besides, the function also resets the state of the scene to its default values.
  30494. *
  30495. * If not state object is provided, the function creates one.
  30496. *
  30497. * @private
  30498. * @function
  30499. * @param {Scene} scene - The scene.
  30500. * @param {Object} [state={}] - The state.
  30501. * @return {Object} The state.
  30502. */
  30503. function resetSceneState( scene, state ) {
  30504. state = saveSceneState( scene, state );
  30505. scene.background = null;
  30506. scene.backgroundNode = null;
  30507. scene.overrideMaterial = null;
  30508. return state;
  30509. }
  30510. /**
  30511. * Restores the state of the given scene from the given state object.
  30512. *
  30513. * @private
  30514. * @function
  30515. * @param {Scene} scene - The scene.
  30516. * @param {Object} state - The state to restore.
  30517. */
  30518. function restoreSceneState( scene, state ) {
  30519. scene.background = state.background;
  30520. scene.backgroundNode = state.backgroundNode;
  30521. scene.overrideMaterial = state.overrideMaterial;
  30522. }
  30523. /**
  30524. * Saves the state of the given renderer and scene and stores it into the given state object.
  30525. *
  30526. * If not state object is provided, the function creates one.
  30527. *
  30528. * @private
  30529. * @function
  30530. * @param {Renderer} renderer - The renderer.
  30531. * @param {Scene} scene - The scene.
  30532. * @param {Object} [state={}] - The state.
  30533. * @return {Object} The state.
  30534. */
  30535. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  30536. state = saveRendererState( renderer, state );
  30537. state = saveSceneState( scene, state );
  30538. return state;
  30539. }
  30540. /**
  30541. * Saves the state of the given renderer and scene and stores it into the given state object.
  30542. * Besides, the function also resets the state of the renderer and scene to its default values.
  30543. *
  30544. * If not state object is provided, the function creates one.
  30545. *
  30546. * @private
  30547. * @function
  30548. * @param {Renderer} renderer - The renderer.
  30549. * @param {Scene} scene - The scene.
  30550. * @param {Object} [state={}] - The state.
  30551. * @return {Object} The state.
  30552. */
  30553. function resetRendererAndSceneState( renderer, scene, state ) {
  30554. state = resetRendererState( renderer, state );
  30555. state = resetSceneState( scene, state );
  30556. return state;
  30557. }
  30558. /**
  30559. * Restores the state of the given renderer and scene from the given state object.
  30560. *
  30561. * @private
  30562. * @function
  30563. * @param {Renderer} renderer - The renderer.
  30564. * @param {Scene} scene - The scene.
  30565. * @param {Object} state - The state to restore.
  30566. */
  30567. function restoreRendererAndSceneState( renderer, scene, state ) {
  30568. restoreRendererState( renderer, state );
  30569. restoreSceneState( scene, state );
  30570. }
  30571. var RendererUtils = /*#__PURE__*/Object.freeze({
  30572. __proto__: null,
  30573. resetRendererAndSceneState: resetRendererAndSceneState,
  30574. resetRendererState: resetRendererState,
  30575. resetSceneState: resetSceneState,
  30576. restoreRendererAndSceneState: restoreRendererAndSceneState,
  30577. restoreRendererState: restoreRendererState,
  30578. restoreSceneState: restoreSceneState,
  30579. saveRendererAndSceneState: saveRendererAndSceneState,
  30580. saveRendererState: saveRendererState,
  30581. saveSceneState: saveSceneState
  30582. });
  30583. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  30584. /**
  30585. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  30586. * with a binary `[0,1]` result.
  30587. *
  30588. * @method
  30589. * @param {Object} inputs - The input parameter object.
  30590. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30591. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30592. * @return {Node<float>} The filtering result.
  30593. */
  30594. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  30595. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  30596. if ( depthTexture.isArrayTexture ) {
  30597. basic = basic.depth( depthLayer );
  30598. }
  30599. return basic.compare( shadowCoord.z );
  30600. } );
  30601. /**
  30602. * A shadow filtering function performing PCF filtering.
  30603. *
  30604. * @method
  30605. * @param {Object} inputs - The input parameter object.
  30606. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30607. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30608. * @param {LightShadow} inputs.shadow - The light shadow.
  30609. * @return {Node<float>} The filtering result.
  30610. */
  30611. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  30612. const depthCompare = ( uv, compare ) => {
  30613. let depth = texture( depthTexture, uv );
  30614. if ( depthTexture.isArrayTexture ) {
  30615. depth = depth.depth( depthLayer );
  30616. }
  30617. return depth.compare( compare );
  30618. };
  30619. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  30620. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  30621. const texelSize = vec2( 1 ).div( mapSize );
  30622. const dx0 = texelSize.x.negate().mul( radius );
  30623. const dy0 = texelSize.y.negate().mul( radius );
  30624. const dx1 = texelSize.x.mul( radius );
  30625. const dy1 = texelSize.y.mul( radius );
  30626. const dx2 = dx0.div( 2 );
  30627. const dy2 = dy0.div( 2 );
  30628. const dx3 = dx1.div( 2 );
  30629. const dy3 = dy1.div( 2 );
  30630. return add(
  30631. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  30632. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  30633. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  30634. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  30635. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  30636. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  30637. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  30638. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  30639. depthCompare( shadowCoord.xy, shadowCoord.z ),
  30640. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  30641. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  30642. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  30643. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  30644. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  30645. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  30646. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  30647. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  30648. ).mul( 1 / 17 );
  30649. } );
  30650. /**
  30651. * A shadow filtering function performing PCF soft filtering.
  30652. *
  30653. * @method
  30654. * @param {Object} inputs - The input parameter object.
  30655. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30656. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30657. * @param {LightShadow} inputs.shadow - The light shadow.
  30658. * @return {Node<float>} The filtering result.
  30659. */
  30660. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  30661. const depthCompare = ( uv, compare ) => {
  30662. let depth = texture( depthTexture, uv );
  30663. if ( depthTexture.isArrayTexture ) {
  30664. depth = depth.depth( depthLayer );
  30665. }
  30666. return depth.compare( compare );
  30667. };
  30668. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  30669. const texelSize = vec2( 1 ).div( mapSize );
  30670. const dx = texelSize.x;
  30671. const dy = texelSize.y;
  30672. const uv = shadowCoord.xy;
  30673. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  30674. uv.subAssign( f.mul( texelSize ) );
  30675. return add(
  30676. depthCompare( uv, shadowCoord.z ),
  30677. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  30678. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  30679. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  30680. mix(
  30681. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  30682. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  30683. f.x
  30684. ),
  30685. mix(
  30686. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  30687. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  30688. f.x
  30689. ),
  30690. mix(
  30691. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  30692. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  30693. f.y
  30694. ),
  30695. mix(
  30696. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  30697. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  30698. f.y
  30699. ),
  30700. mix(
  30701. mix(
  30702. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  30703. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  30704. f.x
  30705. ),
  30706. mix(
  30707. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  30708. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  30709. f.x
  30710. ),
  30711. f.y
  30712. )
  30713. ).mul( 1 / 9 );
  30714. } );
  30715. /**
  30716. * A shadow filtering function performing VSM filtering.
  30717. *
  30718. * @method
  30719. * @param {Object} inputs - The input parameter object.
  30720. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30721. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30722. * @return {Node<float>} The filtering result.
  30723. */
  30724. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  30725. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  30726. if ( depthTexture.isArrayTexture ) {
  30727. distribution = distribution.depth( depthLayer );
  30728. }
  30729. distribution = distribution.rg;
  30730. const mean = distribution.x;
  30731. const variance = max$1( 0.0000001, distribution.y.mul( distribution.y ) );
  30732. const hardShadow = step( shadowCoord.z, mean );
  30733. // Early return if fully lit
  30734. If( hardShadow.equal( 1.0 ), () => {
  30735. return float( 1.0 );
  30736. } );
  30737. // Distance from mean
  30738. const d = shadowCoord.z.sub( mean );
  30739. // Chebyshev's inequality for upper bound on probability
  30740. let p_max = variance.div( variance.add( d.mul( d ) ) );
  30741. // Reduce light bleeding by remapping [amount, 1] to [0, 1]
  30742. p_max = clamp( sub( p_max, 0.3 ).div( 0.65 ) );
  30743. return max$1( hardShadow, p_max );
  30744. } );
  30745. //
  30746. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  30747. let dist = positionWorld.sub( position ).length();
  30748. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  30749. dist = dist.saturate(); // clamp to [ 0, 1 ]
  30750. return dist;
  30751. } );
  30752. const linearShadowDistance = ( light ) => {
  30753. const camera = light.shadow.camera;
  30754. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  30755. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  30756. const referencePosition = objectPosition( light );
  30757. return linearDistance( referencePosition, nearDistance, farDistance );
  30758. };
  30759. /**
  30760. * Retrieves or creates a shadow material for the given light source.
  30761. *
  30762. * This function checks if a shadow material already exists for the provided light.
  30763. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  30764. * in the `shadowMaterialLib` for future use.
  30765. *
  30766. * @tsl
  30767. * @function
  30768. * @param {Light} light - The light source for which the shadow material is needed.
  30769. * If the light is a point light, a depth node is calculated
  30770. * using the linear shadow distance.
  30771. * @returns {NodeMaterial} The shadow material associated with the given light.
  30772. */
  30773. const getShadowMaterial = ( light ) => {
  30774. let material = shadowMaterialLib.get( light );
  30775. if ( material === undefined ) {
  30776. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  30777. material = new NodeMaterial();
  30778. material.colorNode = vec4( 0, 0, 0, 1 );
  30779. material.depthNode = depthNode;
  30780. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  30781. material.name = 'ShadowMaterial';
  30782. material.fog = false;
  30783. shadowMaterialLib.set( light, material );
  30784. }
  30785. return material;
  30786. };
  30787. //
  30788. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  30789. const _shadowRenderObjectKeys = [];
  30790. /**
  30791. * Creates a function to render shadow objects in a scene.
  30792. *
  30793. * @tsl
  30794. * @function
  30795. * @param {Renderer} renderer - The renderer.
  30796. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  30797. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  30798. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  30799. * @return {shadowRenderObjectFunction} A function that renders shadow objects.
  30800. */
  30801. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  30802. _shadowRenderObjectKeys[ 0 ] = renderer;
  30803. _shadowRenderObjectKeys[ 1 ] = shadow;
  30804. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  30805. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  30806. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  30807. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  30808. if ( useVelocity ) {
  30809. getDataFromObject( object ).useVelocity = true;
  30810. }
  30811. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  30812. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  30813. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  30814. }
  30815. };
  30816. renderObjectFunction.shadowType = shadowType;
  30817. renderObjectFunction.useVelocity = useVelocity;
  30818. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  30819. }
  30820. _shadowRenderObjectKeys[ 0 ] = null;
  30821. _shadowRenderObjectKeys[ 1 ] = null;
  30822. return renderObjectFunction;
  30823. };
  30824. /**
  30825. * Represents the shader code for the first VSM render pass.
  30826. *
  30827. * @private
  30828. * @method
  30829. * @param {Object} inputs - The input parameter object.
  30830. * @param {Node<float>} inputs.samples - The number of samples
  30831. * @param {Node<float>} inputs.radius - The radius.
  30832. * @param {Node<float>} inputs.size - The size.
  30833. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  30834. * @return {Node<vec2>} The VSM output.
  30835. */
  30836. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  30837. const mean = float( 0 ).toVar( 'meanVertical' );
  30838. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  30839. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  30840. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  30841. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  30842. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  30843. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  30844. if ( shadowPass.value.isArrayTexture ) {
  30845. depth = depth.depth( depthLayer );
  30846. }
  30847. depth = depth.x;
  30848. mean.addAssign( depth );
  30849. squaredMean.addAssign( depth.mul( depth ) );
  30850. } );
  30851. mean.divAssign( samples );
  30852. squaredMean.divAssign( samples );
  30853. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  30854. return vec2( mean, std_dev );
  30855. } );
  30856. /**
  30857. * Represents the shader code for the second VSM render pass.
  30858. *
  30859. * @private
  30860. * @method
  30861. * @param {Object} inputs - The input parameter object.
  30862. * @param {Node<float>} inputs.samples - The number of samples
  30863. * @param {Node<float>} inputs.radius - The radius.
  30864. * @param {Node<float>} inputs.size - The size.
  30865. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  30866. * @return {Node<vec2>} The VSM output.
  30867. */
  30868. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  30869. const mean = float( 0 ).toVar( 'meanHorizontal' );
  30870. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  30871. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  30872. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  30873. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  30874. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  30875. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  30876. if ( shadowPass.value.isArrayTexture ) {
  30877. distribution = distribution.depth( depthLayer );
  30878. }
  30879. mean.addAssign( distribution.x );
  30880. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  30881. } );
  30882. mean.divAssign( samples );
  30883. squaredMean.divAssign( samples );
  30884. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  30885. return vec2( mean, std_dev );
  30886. } );
  30887. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  30888. //
  30889. let _rendererState;
  30890. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  30891. /**
  30892. * Represents the default shadow implementation for lighting nodes.
  30893. *
  30894. * @augments ShadowBaseNode
  30895. */
  30896. class ShadowNode extends ShadowBaseNode {
  30897. static get type() {
  30898. return 'ShadowNode';
  30899. }
  30900. /**
  30901. * Constructs a new shadow node.
  30902. *
  30903. * @param {Light} light - The shadow casting light.
  30904. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  30905. */
  30906. constructor( light, shadow = null ) {
  30907. super( light );
  30908. /**
  30909. * The light shadow which defines the properties light's
  30910. * shadow.
  30911. *
  30912. * @type {?LightShadow}
  30913. * @default null
  30914. */
  30915. this.shadow = shadow || light.shadow;
  30916. /**
  30917. * A reference to the shadow map which is a render target.
  30918. *
  30919. * @type {?RenderTarget}
  30920. * @default null
  30921. */
  30922. this.shadowMap = null;
  30923. /**
  30924. * Only relevant for VSM shadows. Render target for the
  30925. * first VSM render pass.
  30926. *
  30927. * @type {?RenderTarget}
  30928. * @default null
  30929. */
  30930. this.vsmShadowMapVertical = null;
  30931. /**
  30932. * Only relevant for VSM shadows. Render target for the
  30933. * second VSM render pass.
  30934. *
  30935. * @type {?RenderTarget}
  30936. * @default null
  30937. */
  30938. this.vsmShadowMapHorizontal = null;
  30939. /**
  30940. * Only relevant for VSM shadows. Node material which
  30941. * is used to render the first VSM pass.
  30942. *
  30943. * @type {?NodeMaterial}
  30944. * @default null
  30945. */
  30946. this.vsmMaterialVertical = null;
  30947. /**
  30948. * Only relevant for VSM shadows. Node material which
  30949. * is used to render the second VSM pass.
  30950. *
  30951. * @type {?NodeMaterial}
  30952. * @default null
  30953. */
  30954. this.vsmMaterialHorizontal = null;
  30955. /**
  30956. * A reference to the output node which defines the
  30957. * final result of this shadow node.
  30958. *
  30959. * @type {?Node}
  30960. * @private
  30961. * @default null
  30962. */
  30963. this._node = null;
  30964. /**
  30965. * The current shadow map type of this shadow node.
  30966. *
  30967. * @type {?number}
  30968. * @private
  30969. * @default null
  30970. */
  30971. this._currentShadowType = null;
  30972. /**
  30973. * A Weak Map holding the current frame ID per camera. Used
  30974. * to control the update of shadow maps.
  30975. *
  30976. * @type {WeakMap<Camera,number>}
  30977. * @private
  30978. */
  30979. this._cameraFrameId = new WeakMap();
  30980. /**
  30981. * This flag can be used for type testing.
  30982. *
  30983. * @type {boolean}
  30984. * @readonly
  30985. * @default true
  30986. */
  30987. this.isShadowNode = true;
  30988. /**
  30989. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  30990. *
  30991. * @type {number}
  30992. * @readonly
  30993. * @default true
  30994. */
  30995. this.depthLayer = 0;
  30996. }
  30997. /**
  30998. * Setups the shadow filtering.
  30999. *
  31000. * @param {NodeBuilder} builder - A reference to the current node builder.
  31001. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  31002. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  31003. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31004. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  31005. * @param {LightShadow} inputs.shadow - The light shadow.
  31006. * @return {Node<float>} The result node of the shadow filtering.
  31007. */
  31008. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  31009. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  31010. .and( shadowCoord.x.lessThanEqual( 1 ) )
  31011. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  31012. .and( shadowCoord.y.lessThanEqual( 1 ) )
  31013. .and( shadowCoord.z.lessThanEqual( 1 ) );
  31014. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  31015. return frustumTest.select( shadowNode, float( 1 ) );
  31016. }
  31017. /**
  31018. * Setups the shadow coordinates.
  31019. *
  31020. * @param {NodeBuilder} builder - A reference to the current node builder.
  31021. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  31022. * @return {Node<vec3>} The shadow coordinates.
  31023. */
  31024. setupShadowCoord( builder, shadowPosition ) {
  31025. const { shadow } = this;
  31026. const { renderer } = builder;
  31027. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  31028. let shadowCoord = shadowPosition;
  31029. let coordZ;
  31030. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  31031. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  31032. coordZ = shadowCoord.z;
  31033. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  31034. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  31035. }
  31036. } else {
  31037. const w = shadowCoord.w;
  31038. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  31039. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  31040. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  31041. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  31042. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  31043. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  31044. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  31045. }
  31046. shadowCoord = vec3(
  31047. shadowCoord.x,
  31048. shadowCoord.y.oneMinus(), // follow webgpu standards
  31049. coordZ.add( bias )
  31050. );
  31051. return shadowCoord;
  31052. }
  31053. /**
  31054. * Returns the shadow filtering function for the given shadow type.
  31055. *
  31056. * @param {number} type - The shadow type.
  31057. * @return {Function} The filtering function.
  31058. */
  31059. getShadowFilterFn( type ) {
  31060. return _shadowFilterLib[ type ];
  31061. }
  31062. setupRenderTarget( shadow, builder ) {
  31063. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  31064. depthTexture.name = 'ShadowDepthTexture';
  31065. depthTexture.compareFunction = LessCompare;
  31066. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  31067. shadowMap.texture.name = 'ShadowMap';
  31068. shadowMap.texture.type = shadow.mapType;
  31069. shadowMap.depthTexture = depthTexture;
  31070. return { shadowMap, depthTexture };
  31071. }
  31072. /**
  31073. * Setups the shadow output node.
  31074. *
  31075. * @param {NodeBuilder} builder - A reference to the current node builder.
  31076. * @return {Node<vec3>} The shadow output node.
  31077. */
  31078. setupShadow( builder ) {
  31079. const { renderer, camera } = builder;
  31080. const { light, shadow } = this;
  31081. const shadowMapType = renderer.shadowMap.type;
  31082. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  31083. shadow.camera.coordinateSystem = camera.coordinateSystem;
  31084. shadow.camera.updateProjectionMatrix();
  31085. // VSM
  31086. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  31087. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  31088. if ( shadowMap.depth > 1 ) {
  31089. if ( ! shadowMap._vsmShadowMapVertical ) {
  31090. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  31091. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  31092. }
  31093. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  31094. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  31095. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  31096. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  31097. }
  31098. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  31099. } else {
  31100. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  31101. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  31102. }
  31103. let shadowPassVertical = texture( depthTexture );
  31104. if ( depthTexture.isArrayTexture ) {
  31105. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  31106. }
  31107. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  31108. if ( depthTexture.isArrayTexture ) {
  31109. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  31110. }
  31111. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  31112. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  31113. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31114. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  31115. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  31116. material.name = 'VSMVertical';
  31117. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  31118. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  31119. material.name = 'VSMHorizontal';
  31120. }
  31121. //
  31122. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  31123. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  31124. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( normalWorld.mul( normalBias ) ) );
  31125. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  31126. //
  31127. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  31128. if ( filterFn === null ) {
  31129. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  31130. }
  31131. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  31132. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  31133. let shadowColor = texture( shadowMap.texture, shadowCoord );
  31134. if ( depthTexture.isArrayTexture ) {
  31135. shadowColor = shadowColor.depth( this.depthLayer );
  31136. }
  31137. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  31138. this.shadowMap = shadowMap;
  31139. this.shadow.map = shadowMap;
  31140. // Shadow Output + Inspector
  31141. const inspectName = `${ this.light.type } Shadow [ ${ this.light.name || 'ID: ' + this.light.id } ]`;
  31142. return shadowOutput.toInspector( `${ inspectName } / Color`, () => {
  31143. return texture( this.shadowMap.texture );
  31144. } ).toInspector( `${ inspectName } / Depth`, () => {
  31145. return textureLoad( this.shadowMap.depthTexture, uv$1().mul( textureSize( texture( this.shadowMap.depthTexture ) ) ) ).x.oneMinus();
  31146. } );
  31147. }
  31148. /**
  31149. * The implementation performs the setup of the output node. An output is only
  31150. * produces if shadow mapping is globally enabled in the renderer.
  31151. *
  31152. * @param {NodeBuilder} builder - A reference to the current node builder.
  31153. * @return {ShaderCallNodeInternal} The output node.
  31154. */
  31155. setup( builder ) {
  31156. if ( builder.renderer.shadowMap.enabled === false ) return;
  31157. return Fn( () => {
  31158. const currentShadowType = builder.renderer.shadowMap.type;
  31159. if ( this._currentShadowType !== currentShadowType ) {
  31160. this._reset();
  31161. this._node = null;
  31162. }
  31163. let node = this._node;
  31164. this.setupShadowPosition( builder );
  31165. if ( node === null ) {
  31166. this._node = node = this.setupShadow( builder );
  31167. this._currentShadowType = currentShadowType;
  31168. }
  31169. if ( builder.material.shadowNode ) { // @deprecated, r171
  31170. warn( 'NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  31171. }
  31172. if ( builder.material.receivedShadowNode ) {
  31173. node = builder.material.receivedShadowNode( node );
  31174. }
  31175. return node;
  31176. } )();
  31177. }
  31178. /**
  31179. * Renders the shadow. The logic of this function could be included
  31180. * into {@link ShadowNode#updateShadow} however more specialized shadow
  31181. * nodes might require a custom shadow map rendering. By having a
  31182. * dedicated method, it's easier to overwrite the default behavior.
  31183. *
  31184. * @param {NodeFrame} frame - A reference to the current node frame.
  31185. */
  31186. renderShadow( frame ) {
  31187. const { shadow, shadowMap, light } = this;
  31188. const { renderer, scene } = frame;
  31189. shadow.updateMatrices( light );
  31190. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  31191. const currentSceneName = scene.name;
  31192. scene.name = `Shadow Map [ ${ light.name || 'ID: ' + light.id } ]`;
  31193. renderer.render( scene, shadow.camera );
  31194. scene.name = currentSceneName;
  31195. }
  31196. /**
  31197. * Updates the shadow.
  31198. *
  31199. * @param {NodeFrame} frame - A reference to the current node frame.
  31200. */
  31201. updateShadow( frame ) {
  31202. const { shadowMap, light, shadow } = this;
  31203. const { renderer, scene, camera } = frame;
  31204. const shadowType = renderer.shadowMap.type;
  31205. const depthVersion = shadowMap.depthTexture.version;
  31206. this._depthVersionCached = depthVersion;
  31207. const _shadowCameraLayer = shadow.camera.layers.mask;
  31208. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  31209. shadow.camera.layers.mask = camera.layers.mask;
  31210. }
  31211. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  31212. const currentMRT = renderer.getMRT();
  31213. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  31214. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  31215. scene.overrideMaterial = getShadowMaterial( light );
  31216. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  31217. renderer.setClearColor( 0x000000, 0 );
  31218. renderer.setRenderTarget( shadowMap );
  31219. this.renderShadow( frame );
  31220. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  31221. // vsm blur pass
  31222. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  31223. this.vsmPass( renderer );
  31224. }
  31225. shadow.camera.layers.mask = _shadowCameraLayer;
  31226. restoreRendererAndSceneState( renderer, scene, _rendererState );
  31227. }
  31228. /**
  31229. * For VSM additional render passes are required.
  31230. *
  31231. * @param {Renderer} renderer - A reference to the current renderer.
  31232. */
  31233. vsmPass( renderer ) {
  31234. const { shadow } = this;
  31235. const depth = this.shadowMap.depth;
  31236. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  31237. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  31238. renderer.setRenderTarget( this.vsmShadowMapVertical );
  31239. _quadMesh.material = this.vsmMaterialVertical;
  31240. _quadMesh.render( renderer );
  31241. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  31242. _quadMesh.material = this.vsmMaterialHorizontal;
  31243. _quadMesh.render( renderer );
  31244. }
  31245. /**
  31246. * Frees the internal resources of this shadow node.
  31247. */
  31248. dispose() {
  31249. this._reset();
  31250. super.dispose();
  31251. }
  31252. /**
  31253. * Resets the resouce state of this shadow node.
  31254. *
  31255. * @private
  31256. */
  31257. _reset() {
  31258. this._currentShadowType = null;
  31259. if ( this.shadowMap ) {
  31260. this.shadowMap.dispose();
  31261. this.shadowMap = null;
  31262. }
  31263. if ( this.vsmShadowMapVertical !== null ) {
  31264. this.vsmShadowMapVertical.dispose();
  31265. this.vsmShadowMapVertical = null;
  31266. this.vsmMaterialVertical.dispose();
  31267. this.vsmMaterialVertical = null;
  31268. }
  31269. if ( this.vsmShadowMapHorizontal !== null ) {
  31270. this.vsmShadowMapHorizontal.dispose();
  31271. this.vsmShadowMapHorizontal = null;
  31272. this.vsmMaterialHorizontal.dispose();
  31273. this.vsmMaterialHorizontal = null;
  31274. }
  31275. }
  31276. /**
  31277. * The implementation performs the update of the shadow map if necessary.
  31278. *
  31279. * @param {NodeFrame} frame - A reference to the current node frame.
  31280. */
  31281. updateBefore( frame ) {
  31282. const { shadow } = this;
  31283. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  31284. if ( needsUpdate ) {
  31285. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  31286. needsUpdate = false;
  31287. }
  31288. this._cameraFrameId[ frame.camera ] = frame.frameId;
  31289. }
  31290. if ( needsUpdate ) {
  31291. this.updateShadow( frame );
  31292. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  31293. shadow.needsUpdate = false;
  31294. }
  31295. }
  31296. }
  31297. }
  31298. /**
  31299. * Shadow Render Object Function.
  31300. *
  31301. * @function shadowRenderObjectFunction
  31302. * @param {Object3D} object - The 3D object to render.
  31303. * @param {Scene} scene - The scene containing the object.
  31304. * @param {Camera} _camera - The camera used for rendering.
  31305. * @param {BufferGeometry} geometry - The geometry of the object.
  31306. * @param {Material} material - The material of the object.
  31307. * @param {Group} group - The group the object belongs to.
  31308. * @param {...any} params - Additional parameters for rendering.
  31309. */
  31310. /**
  31311. * TSL function for creating an instance of `ShadowNode`.
  31312. *
  31313. * @tsl
  31314. * @function
  31315. * @param {Light} light - The shadow casting light.
  31316. * @param {?LightShadow} [shadow] - The light shadow.
  31317. * @return {ShadowNode} The created shadow node.
  31318. */
  31319. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  31320. const _clearColor$1 = /*@__PURE__*/ new Color();
  31321. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  31322. // vector suitable for 2D texture mapping. This code uses the following layout for the
  31323. // 2D texture:
  31324. //
  31325. // xzXZ
  31326. // y Y
  31327. //
  31328. // Y - Positive y direction
  31329. // y - Negative y direction
  31330. // X - Positive x direction
  31331. // x - Negative x direction
  31332. // Z - Positive z direction
  31333. // z - Negative z direction
  31334. //
  31335. // Source and test bed:
  31336. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  31337. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  31338. const v = pos.toVar();
  31339. // Number of texels to avoid at the edge of each square
  31340. const absV = abs( v );
  31341. // Intersect unit cube
  31342. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  31343. absV.mulAssign( scaleToCube );
  31344. // Apply scale to avoid seams
  31345. // two texels less per square (one texel will do for NEAREST)
  31346. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  31347. // Unwrap
  31348. // space: -1 ... 1 range for each square
  31349. //
  31350. // #X## dim := ( 4 , 2 )
  31351. // # # center := ( 1 , 1 )
  31352. const planar = vec2( v.xy ).toVar();
  31353. const almostATexel = texelSizeY.mul( 1.5 );
  31354. const almostOne = almostATexel.oneMinus();
  31355. If( absV.z.greaterThanEqual( almostOne ), () => {
  31356. If( v.z.greaterThan( 0.0 ), () => {
  31357. planar.x.assign( sub( 4.0, v.x ) );
  31358. } );
  31359. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  31360. const signX = sign( v.x );
  31361. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  31362. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  31363. const signY = sign( v.y );
  31364. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  31365. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  31366. } );
  31367. // Transform to UV space
  31368. // scale := 0.5 / dim
  31369. // translate := ( center + 0.5 ) / dim
  31370. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  31371. } ).setLayout( {
  31372. name: 'cubeToUV',
  31373. type: 'vec2',
  31374. inputs: [
  31375. { name: 'pos', type: 'vec3' },
  31376. { name: 'texelSizeY', type: 'float' }
  31377. ]
  31378. } );
  31379. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  31380. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  31381. } );
  31382. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  31383. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  31384. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  31385. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  31386. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  31387. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  31388. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  31389. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  31390. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  31391. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  31392. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  31393. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  31394. .mul( 1.0 / 9.0 );
  31395. } );
  31396. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  31397. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  31398. // the vector from the light to the world-space position of the fragment.
  31399. const lightToPosition = shadowCoord.xyz.toVar();
  31400. const lightToPositionLength = lightToPosition.length();
  31401. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  31402. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  31403. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  31404. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  31405. const result = float( 1.0 ).toVar();
  31406. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  31407. // dp = normalized distance from light to fragment position
  31408. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  31409. dp.addAssign( bias );
  31410. // bd3D = base direction 3D
  31411. const bd3D = lightToPosition.normalize();
  31412. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  31413. // percentage-closer filtering
  31414. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  31415. } );
  31416. return result;
  31417. } );
  31418. const _viewport = /*@__PURE__*/ new Vector4();
  31419. const _viewportSize = /*@__PURE__*/ new Vector2();
  31420. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  31421. /**
  31422. * Represents the shadow implementation for point light nodes.
  31423. *
  31424. * @augments ShadowNode
  31425. */
  31426. class PointShadowNode extends ShadowNode {
  31427. static get type() {
  31428. return 'PointShadowNode';
  31429. }
  31430. /**
  31431. * Constructs a new point shadow node.
  31432. *
  31433. * @param {PointLight} light - The shadow casting point light.
  31434. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  31435. */
  31436. constructor( light, shadow = null ) {
  31437. super( light, shadow );
  31438. }
  31439. /**
  31440. * Overwrites the default implementation to return point light shadow specific
  31441. * filtering functions.
  31442. *
  31443. * @param {number} type - The shadow type.
  31444. * @return {Function} The filtering function.
  31445. */
  31446. getShadowFilterFn( type ) {
  31447. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  31448. }
  31449. /**
  31450. * Overwrites the default implementation so the unaltered shadow position is used.
  31451. *
  31452. * @param {NodeBuilder} builder - A reference to the current node builder.
  31453. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  31454. * @return {Node<vec3>} The shadow coordinates.
  31455. */
  31456. setupShadowCoord( builder, shadowPosition ) {
  31457. return shadowPosition;
  31458. }
  31459. /**
  31460. * Overwrites the default implementation to only use point light specific
  31461. * shadow filter functions.
  31462. *
  31463. * @param {NodeBuilder} builder - A reference to the current node builder.
  31464. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  31465. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  31466. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  31467. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31468. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  31469. * @param {LightShadow} inputs.shadow - The light shadow.
  31470. * @return {Node<float>} The result node of the shadow filtering.
  31471. */
  31472. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  31473. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  31474. }
  31475. /**
  31476. * Overwrites the default implementation with point light specific
  31477. * rendering code.
  31478. *
  31479. * @param {NodeFrame} frame - A reference to the current node frame.
  31480. */
  31481. renderShadow( frame ) {
  31482. const { shadow, shadowMap, light } = this;
  31483. const { renderer, scene } = frame;
  31484. const shadowFrameExtents = shadow.getFrameExtents();
  31485. _shadowMapSize.copy( shadow.mapSize );
  31486. _shadowMapSize.multiply( shadowFrameExtents );
  31487. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  31488. _viewportSize.copy( shadow.mapSize );
  31489. //
  31490. const previousAutoClear = renderer.autoClear;
  31491. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  31492. const previousClearAlpha = renderer.getClearAlpha();
  31493. renderer.autoClear = false;
  31494. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  31495. renderer.clear();
  31496. const viewportCount = shadow.getViewportCount();
  31497. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  31498. const viewport = shadow.getViewport( vp );
  31499. const x = _viewportSize.x * viewport.x;
  31500. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  31501. _viewport.set(
  31502. x,
  31503. y,
  31504. _viewportSize.x * viewport.z,
  31505. _viewportSize.y * viewport.w
  31506. );
  31507. shadowMap.viewport.copy( _viewport );
  31508. shadow.updateMatrices( light, vp );
  31509. const currentSceneName = scene.name;
  31510. scene.name = `Point Light Shadow [ ${ light.name || 'ID: ' + light.id } ] - Face ${ vp + 1 }`;
  31511. renderer.render( scene, shadow.camera );
  31512. scene.name = currentSceneName;
  31513. }
  31514. //
  31515. renderer.autoClear = previousAutoClear;
  31516. renderer.setClearColor( previousClearColor, previousClearAlpha );
  31517. }
  31518. }
  31519. /**
  31520. * TSL function for creating an instance of `PointShadowNode`.
  31521. *
  31522. * @tsl
  31523. * @function
  31524. * @param {PointLight} light - The shadow casting point light.
  31525. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  31526. * @return {PointShadowNode} The created point shadow node.
  31527. */
  31528. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  31529. /**
  31530. * Base class for analytic light nodes.
  31531. *
  31532. * @augments LightingNode
  31533. */
  31534. class AnalyticLightNode extends LightingNode {
  31535. static get type() {
  31536. return 'AnalyticLightNode';
  31537. }
  31538. /**
  31539. * Constructs a new analytic light node.
  31540. *
  31541. * @param {?Light} [light=null] - The light source.
  31542. */
  31543. constructor( light = null ) {
  31544. super();
  31545. /**
  31546. * The light source.
  31547. *
  31548. * @type {?Light}
  31549. * @default null
  31550. */
  31551. this.light = light;
  31552. /**
  31553. * The light's color value.
  31554. *
  31555. * @type {Color}
  31556. */
  31557. this.color = new Color();
  31558. /**
  31559. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  31560. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  31561. *
  31562. * @type {Node}
  31563. */
  31564. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  31565. /**
  31566. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  31567. * The final color node is represented by a different node when using shadows.
  31568. *
  31569. * @type {?Node}
  31570. * @default null
  31571. */
  31572. this.baseColorNode = null;
  31573. /**
  31574. * Represents the light's shadow.
  31575. *
  31576. * @type {?ShadowNode}
  31577. * @default null
  31578. */
  31579. this.shadowNode = null;
  31580. /**
  31581. * Represents the light's shadow color.
  31582. *
  31583. * @type {?Node}
  31584. * @default null
  31585. */
  31586. this.shadowColorNode = null;
  31587. /**
  31588. * This flag can be used for type testing.
  31589. *
  31590. * @type {boolean}
  31591. * @readonly
  31592. * @default true
  31593. */
  31594. this.isAnalyticLightNode = true;
  31595. /**
  31596. * Overwritten since analytic light nodes are updated
  31597. * once per frame.
  31598. *
  31599. * @type {string}
  31600. * @default 'frame'
  31601. */
  31602. this.updateType = NodeUpdateType.FRAME;
  31603. }
  31604. getHash() {
  31605. return this.light.uuid;
  31606. }
  31607. /**
  31608. * Returns a node representing a direction vector which points from the current
  31609. * position in view space to the light's position in view space.
  31610. *
  31611. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  31612. * @return {Node<vec3>} The light vector node.
  31613. */
  31614. getLightVector( builder ) {
  31615. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  31616. }
  31617. /**
  31618. * Sets up the direct lighting for the analytic light node.
  31619. *
  31620. * @abstract
  31621. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  31622. * @return {Object|undefined} The direct light data (color and direction).
  31623. */
  31624. setupDirect( /*builder*/ ) { }
  31625. /**
  31626. * Sets up the direct rect area lighting for the analytic light node.
  31627. *
  31628. * @abstract
  31629. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  31630. * @return {Object|undefined} The direct rect area light data.
  31631. */
  31632. setupDirectRectArea( /*builder*/ ) { }
  31633. /**
  31634. * Setups the shadow node for this light. The method exists so concrete light classes
  31635. * can setup different types of shadow nodes.
  31636. *
  31637. * @return {ShadowNode} The created shadow node.
  31638. */
  31639. setupShadowNode() {
  31640. return shadow( this.light );
  31641. }
  31642. /**
  31643. * Setups the shadow for this light. This method is only executed if the light
  31644. * cast shadows and the current build object receives shadows. It incorporates
  31645. * shadows into the lighting computation.
  31646. *
  31647. * @param {NodeBuilder} builder - The current node builder.
  31648. */
  31649. setupShadow( builder ) {
  31650. const { renderer } = builder;
  31651. if ( renderer.shadowMap.enabled === false ) return;
  31652. let shadowColorNode = this.shadowColorNode;
  31653. if ( shadowColorNode === null ) {
  31654. const customShadowNode = this.light.shadow.shadowNode;
  31655. let shadowNode;
  31656. if ( customShadowNode !== undefined ) {
  31657. shadowNode = nodeObject( customShadowNode );
  31658. } else {
  31659. shadowNode = this.setupShadowNode();
  31660. }
  31661. this.shadowNode = shadowNode;
  31662. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  31663. this.baseColorNode = this.colorNode;
  31664. }
  31665. //
  31666. this.colorNode = shadowColorNode;
  31667. }
  31668. /**
  31669. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  31670. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  31671. * invocate the respective interface methods.
  31672. *
  31673. * @param {NodeBuilder} builder - The current node builder.
  31674. */
  31675. setup( builder ) {
  31676. this.colorNode = this.baseColorNode || this.colorNode;
  31677. if ( this.light.castShadow ) {
  31678. if ( builder.object.receiveShadow ) {
  31679. this.setupShadow( builder );
  31680. }
  31681. } else if ( this.shadowNode !== null ) {
  31682. this.shadowNode.dispose();
  31683. this.shadowNode = null;
  31684. this.shadowColorNode = null;
  31685. }
  31686. const directLightData = this.setupDirect( builder );
  31687. const directRectAreaLightData = this.setupDirectRectArea( builder );
  31688. if ( directLightData ) {
  31689. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  31690. }
  31691. if ( directRectAreaLightData ) {
  31692. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  31693. }
  31694. }
  31695. /**
  31696. * The update method is used to update light uniforms per frame.
  31697. * Potentially overwritten in concrete light nodes to update light
  31698. * specific uniforms.
  31699. *
  31700. * @param {NodeFrame} frame - A reference to the current node frame.
  31701. */
  31702. update( /*frame*/ ) {
  31703. const { light } = this;
  31704. this.color.copy( light.color ).multiplyScalar( light.intensity );
  31705. }
  31706. }
  31707. /**
  31708. * Represents a `discard` shader operation in TSL.
  31709. *
  31710. * @method
  31711. * @param {Object} inputs - The input parameter object.
  31712. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  31713. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  31714. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  31715. * @return {Node<float>} The distance falloff.
  31716. */
  31717. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  31718. // based upon Frostbite 3 Moving to Physically-based Rendering
  31719. // page 32, equation 26: E[window1]
  31720. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  31721. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  31722. return cutoffDistance.greaterThan( 0 ).select(
  31723. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  31724. distanceFalloff
  31725. );
  31726. } ); // validated
  31727. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  31728. const lightDirection = lightVector.normalize();
  31729. const lightDistance = lightVector.length();
  31730. const attenuation = getDistanceAttenuation( {
  31731. lightDistance,
  31732. cutoffDistance,
  31733. decayExponent
  31734. } );
  31735. const lightColor = color.mul( attenuation );
  31736. return { lightDirection, lightColor };
  31737. };
  31738. /**
  31739. * Module for representing point lights as nodes.
  31740. *
  31741. * @augments AnalyticLightNode
  31742. */
  31743. class PointLightNode extends AnalyticLightNode {
  31744. static get type() {
  31745. return 'PointLightNode';
  31746. }
  31747. /**
  31748. * Constructs a new point light node.
  31749. *
  31750. * @param {?PointLight} [light=null] - The point light source.
  31751. */
  31752. constructor( light = null ) {
  31753. super( light );
  31754. /**
  31755. * Uniform node representing the cutoff distance.
  31756. *
  31757. * @type {UniformNode<float>}
  31758. */
  31759. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  31760. /**
  31761. * Uniform node representing the decay exponent.
  31762. *
  31763. * @type {UniformNode<float>}
  31764. */
  31765. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  31766. }
  31767. /**
  31768. * Overwritten to updated point light specific uniforms.
  31769. *
  31770. * @param {NodeFrame} frame - A reference to the current node frame.
  31771. */
  31772. update( frame ) {
  31773. const { light } = this;
  31774. super.update( frame );
  31775. this.cutoffDistanceNode.value = light.distance;
  31776. this.decayExponentNode.value = light.decay;
  31777. }
  31778. /**
  31779. * Overwritten to setup point light specific shadow.
  31780. *
  31781. * @return {PointShadowNode}
  31782. */
  31783. setupShadowNode() {
  31784. return pointShadow( this.light );
  31785. }
  31786. setupDirect( builder ) {
  31787. return directPointLight( {
  31788. color: this.colorNode,
  31789. lightVector: this.getLightVector( builder ),
  31790. cutoffDistance: this.cutoffDistanceNode,
  31791. decayExponent: this.decayExponentNode
  31792. } );
  31793. }
  31794. }
  31795. /**
  31796. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  31797. *
  31798. * @tsl
  31799. * @function
  31800. * @param {Node<vec2>} coord - The uv coordinates.
  31801. * @return {Node<float>} The result data.
  31802. */
  31803. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  31804. const uv = coord.mul( 2.0 );
  31805. const cx = uv.x.floor();
  31806. const cy = uv.y.floor();
  31807. const result = cx.add( cy ).mod( 2.0 );
  31808. return result.sign();
  31809. } );
  31810. /**
  31811. * Generates a circle based on the uv coordinates.
  31812. *
  31813. * @tsl
  31814. * @function
  31815. * @param {Node<vec2>} coord - The uv to generate the circle.
  31816. * @return {Node<float>} The circle shape.
  31817. */
  31818. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  31819. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  31820. let alpha;
  31821. if ( material.alphaToCoverage && renderer.currentSamples > 0 ) {
  31822. const dlen = float( len2.fwidth() ).toVar();
  31823. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  31824. } else {
  31825. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  31826. }
  31827. return alpha;
  31828. } );
  31829. // Three.js Transpiler
  31830. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  31831. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  31832. const f = float( f_immutable ).toVar();
  31833. const t = float( t_immutable ).toVar();
  31834. const b = bool( b_immutable ).toVar();
  31835. return select( b, t, f );
  31836. } ).setLayout( {
  31837. name: 'mx_select',
  31838. type: 'float',
  31839. inputs: [
  31840. { name: 'b', type: 'bool' },
  31841. { name: 't', type: 'float' },
  31842. { name: 'f', type: 'float' }
  31843. ]
  31844. } );
  31845. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  31846. const b = bool( b_immutable ).toVar();
  31847. const val = float( val_immutable ).toVar();
  31848. return select( b, val.negate(), val );
  31849. } ).setLayout( {
  31850. name: 'mx_negate_if',
  31851. type: 'float',
  31852. inputs: [
  31853. { name: 'val', type: 'float' },
  31854. { name: 'b', type: 'bool' }
  31855. ]
  31856. } );
  31857. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  31858. const x = float( x_immutable ).toVar();
  31859. return int( floor( x ) );
  31860. } ).setLayout( {
  31861. name: 'mx_floor',
  31862. type: 'int',
  31863. inputs: [
  31864. { name: 'x', type: 'float' }
  31865. ]
  31866. } );
  31867. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  31868. const x = float( x_immutable ).toVar();
  31869. i.assign( mx_floor( x ) );
  31870. return x.sub( float( i ) );
  31871. } );
  31872. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  31873. const t = float( t_immutable ).toVar();
  31874. const s = float( s_immutable ).toVar();
  31875. const v3 = float( v3_immutable ).toVar();
  31876. const v2 = float( v2_immutable ).toVar();
  31877. const v1 = float( v1_immutable ).toVar();
  31878. const v0 = float( v0_immutable ).toVar();
  31879. const s1 = float( sub( 1.0, s ) ).toVar();
  31880. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  31881. } ).setLayout( {
  31882. name: 'mx_bilerp_0',
  31883. type: 'float',
  31884. inputs: [
  31885. { name: 'v0', type: 'float' },
  31886. { name: 'v1', type: 'float' },
  31887. { name: 'v2', type: 'float' },
  31888. { name: 'v3', type: 'float' },
  31889. { name: 's', type: 'float' },
  31890. { name: 't', type: 'float' }
  31891. ]
  31892. } );
  31893. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  31894. const t = float( t_immutable ).toVar();
  31895. const s = float( s_immutable ).toVar();
  31896. const v3 = vec3( v3_immutable ).toVar();
  31897. const v2 = vec3( v2_immutable ).toVar();
  31898. const v1 = vec3( v1_immutable ).toVar();
  31899. const v0 = vec3( v0_immutable ).toVar();
  31900. const s1 = float( sub( 1.0, s ) ).toVar();
  31901. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  31902. } ).setLayout( {
  31903. name: 'mx_bilerp_1',
  31904. type: 'vec3',
  31905. inputs: [
  31906. { name: 'v0', type: 'vec3' },
  31907. { name: 'v1', type: 'vec3' },
  31908. { name: 'v2', type: 'vec3' },
  31909. { name: 'v3', type: 'vec3' },
  31910. { name: 's', type: 'float' },
  31911. { name: 't', type: 'float' }
  31912. ]
  31913. } );
  31914. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  31915. 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 ] ) => {
  31916. const r = float( r_immutable ).toVar();
  31917. const t = float( t_immutable ).toVar();
  31918. const s = float( s_immutable ).toVar();
  31919. const v7 = float( v7_immutable ).toVar();
  31920. const v6 = float( v6_immutable ).toVar();
  31921. const v5 = float( v5_immutable ).toVar();
  31922. const v4 = float( v4_immutable ).toVar();
  31923. const v3 = float( v3_immutable ).toVar();
  31924. const v2 = float( v2_immutable ).toVar();
  31925. const v1 = float( v1_immutable ).toVar();
  31926. const v0 = float( v0_immutable ).toVar();
  31927. const s1 = float( sub( 1.0, s ) ).toVar();
  31928. const t1 = float( sub( 1.0, t ) ).toVar();
  31929. const r1 = float( sub( 1.0, r ) ).toVar();
  31930. 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 ) ) ) ) ) );
  31931. } ).setLayout( {
  31932. name: 'mx_trilerp_0',
  31933. type: 'float',
  31934. inputs: [
  31935. { name: 'v0', type: 'float' },
  31936. { name: 'v1', type: 'float' },
  31937. { name: 'v2', type: 'float' },
  31938. { name: 'v3', type: 'float' },
  31939. { name: 'v4', type: 'float' },
  31940. { name: 'v5', type: 'float' },
  31941. { name: 'v6', type: 'float' },
  31942. { name: 'v7', type: 'float' },
  31943. { name: 's', type: 'float' },
  31944. { name: 't', type: 'float' },
  31945. { name: 'r', type: 'float' }
  31946. ]
  31947. } );
  31948. 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 ] ) => {
  31949. const r = float( r_immutable ).toVar();
  31950. const t = float( t_immutable ).toVar();
  31951. const s = float( s_immutable ).toVar();
  31952. const v7 = vec3( v7_immutable ).toVar();
  31953. const v6 = vec3( v6_immutable ).toVar();
  31954. const v5 = vec3( v5_immutable ).toVar();
  31955. const v4 = vec3( v4_immutable ).toVar();
  31956. const v3 = vec3( v3_immutable ).toVar();
  31957. const v2 = vec3( v2_immutable ).toVar();
  31958. const v1 = vec3( v1_immutable ).toVar();
  31959. const v0 = vec3( v0_immutable ).toVar();
  31960. const s1 = float( sub( 1.0, s ) ).toVar();
  31961. const t1 = float( sub( 1.0, t ) ).toVar();
  31962. const r1 = float( sub( 1.0, r ) ).toVar();
  31963. 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 ) ) ) ) ) );
  31964. } ).setLayout( {
  31965. name: 'mx_trilerp_1',
  31966. type: 'vec3',
  31967. inputs: [
  31968. { name: 'v0', type: 'vec3' },
  31969. { name: 'v1', type: 'vec3' },
  31970. { name: 'v2', type: 'vec3' },
  31971. { name: 'v3', type: 'vec3' },
  31972. { name: 'v4', type: 'vec3' },
  31973. { name: 'v5', type: 'vec3' },
  31974. { name: 'v6', type: 'vec3' },
  31975. { name: 'v7', type: 'vec3' },
  31976. { name: 's', type: 'float' },
  31977. { name: 't', type: 'float' },
  31978. { name: 'r', type: 'float' }
  31979. ]
  31980. } );
  31981. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  31982. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  31983. const y = float( y_immutable ).toVar();
  31984. const x = float( x_immutable ).toVar();
  31985. const hash = uint( hash_immutable ).toVar();
  31986. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  31987. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  31988. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  31989. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  31990. } ).setLayout( {
  31991. name: 'mx_gradient_float_0',
  31992. type: 'float',
  31993. inputs: [
  31994. { name: 'hash', type: 'uint' },
  31995. { name: 'x', type: 'float' },
  31996. { name: 'y', type: 'float' }
  31997. ]
  31998. } );
  31999. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  32000. const z = float( z_immutable ).toVar();
  32001. const y = float( y_immutable ).toVar();
  32002. const x = float( x_immutable ).toVar();
  32003. const hash = uint( hash_immutable ).toVar();
  32004. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  32005. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  32006. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  32007. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  32008. } ).setLayout( {
  32009. name: 'mx_gradient_float_1',
  32010. type: 'float',
  32011. inputs: [
  32012. { name: 'hash', type: 'uint' },
  32013. { name: 'x', type: 'float' },
  32014. { name: 'y', type: 'float' },
  32015. { name: 'z', type: 'float' }
  32016. ]
  32017. } );
  32018. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  32019. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  32020. const y = float( y_immutable ).toVar();
  32021. const x = float( x_immutable ).toVar();
  32022. const hash = uvec3( hash_immutable ).toVar();
  32023. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  32024. } ).setLayout( {
  32025. name: 'mx_gradient_vec3_0',
  32026. type: 'vec3',
  32027. inputs: [
  32028. { name: 'hash', type: 'uvec3' },
  32029. { name: 'x', type: 'float' },
  32030. { name: 'y', type: 'float' }
  32031. ]
  32032. } );
  32033. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  32034. const z = float( z_immutable ).toVar();
  32035. const y = float( y_immutable ).toVar();
  32036. const x = float( x_immutable ).toVar();
  32037. const hash = uvec3( hash_immutable ).toVar();
  32038. 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 ) );
  32039. } ).setLayout( {
  32040. name: 'mx_gradient_vec3_1',
  32041. type: 'vec3',
  32042. inputs: [
  32043. { name: 'hash', type: 'uvec3' },
  32044. { name: 'x', type: 'float' },
  32045. { name: 'y', type: 'float' },
  32046. { name: 'z', type: 'float' }
  32047. ]
  32048. } );
  32049. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  32050. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32051. const v = float( v_immutable ).toVar();
  32052. return mul( 0.6616, v );
  32053. } ).setLayout( {
  32054. name: 'mx_gradient_scale2d_0',
  32055. type: 'float',
  32056. inputs: [
  32057. { name: 'v', type: 'float' }
  32058. ]
  32059. } );
  32060. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32061. const v = float( v_immutable ).toVar();
  32062. return mul( 0.9820, v );
  32063. } ).setLayout( {
  32064. name: 'mx_gradient_scale3d_0',
  32065. type: 'float',
  32066. inputs: [
  32067. { name: 'v', type: 'float' }
  32068. ]
  32069. } );
  32070. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32071. const v = vec3( v_immutable ).toVar();
  32072. return mul( 0.6616, v );
  32073. } ).setLayout( {
  32074. name: 'mx_gradient_scale2d_1',
  32075. type: 'vec3',
  32076. inputs: [
  32077. { name: 'v', type: 'vec3' }
  32078. ]
  32079. } );
  32080. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  32081. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32082. const v = vec3( v_immutable ).toVar();
  32083. return mul( 0.9820, v );
  32084. } ).setLayout( {
  32085. name: 'mx_gradient_scale3d_1',
  32086. type: 'vec3',
  32087. inputs: [
  32088. { name: 'v', type: 'vec3' }
  32089. ]
  32090. } );
  32091. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  32092. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  32093. const k = int( k_immutable ).toVar();
  32094. const x = uint( x_immutable ).toVar();
  32095. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  32096. } ).setLayout( {
  32097. name: 'mx_rotl32',
  32098. type: 'uint',
  32099. inputs: [
  32100. { name: 'x', type: 'uint' },
  32101. { name: 'k', type: 'int' }
  32102. ]
  32103. } );
  32104. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  32105. a.subAssign( c );
  32106. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  32107. c.addAssign( b );
  32108. b.subAssign( a );
  32109. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  32110. a.addAssign( c );
  32111. c.subAssign( b );
  32112. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  32113. b.addAssign( a );
  32114. a.subAssign( c );
  32115. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  32116. c.addAssign( b );
  32117. b.subAssign( a );
  32118. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  32119. a.addAssign( c );
  32120. c.subAssign( b );
  32121. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  32122. b.addAssign( a );
  32123. } );
  32124. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  32125. const c = uint( c_immutable ).toVar();
  32126. const b = uint( b_immutable ).toVar();
  32127. const a = uint( a_immutable ).toVar();
  32128. c.bitXorAssign( b );
  32129. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  32130. a.bitXorAssign( c );
  32131. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  32132. b.bitXorAssign( a );
  32133. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  32134. c.bitXorAssign( b );
  32135. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  32136. a.bitXorAssign( c );
  32137. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  32138. b.bitXorAssign( a );
  32139. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  32140. c.bitXorAssign( b );
  32141. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  32142. return c;
  32143. } ).setLayout( {
  32144. name: 'mx_bjfinal',
  32145. type: 'uint',
  32146. inputs: [
  32147. { name: 'a', type: 'uint' },
  32148. { name: 'b', type: 'uint' },
  32149. { name: 'c', type: 'uint' }
  32150. ]
  32151. } );
  32152. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  32153. const bits = uint( bits_immutable ).toVar();
  32154. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  32155. } ).setLayout( {
  32156. name: 'mx_bits_to_01',
  32157. type: 'float',
  32158. inputs: [
  32159. { name: 'bits', type: 'uint' }
  32160. ]
  32161. } );
  32162. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  32163. const t = float( t_immutable ).toVar();
  32164. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  32165. } ).setLayout( {
  32166. name: 'mx_fade',
  32167. type: 'float',
  32168. inputs: [
  32169. { name: 't', type: 'float' }
  32170. ]
  32171. } );
  32172. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  32173. const x = int( x_immutable ).toVar();
  32174. const len = uint( uint( 1 ) ).toVar();
  32175. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  32176. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  32177. } ).setLayout( {
  32178. name: 'mx_hash_int_0',
  32179. type: 'uint',
  32180. inputs: [
  32181. { name: 'x', type: 'int' }
  32182. ]
  32183. } );
  32184. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  32185. const y = int( y_immutable ).toVar();
  32186. const x = int( x_immutable ).toVar();
  32187. const len = uint( uint( 2 ) ).toVar();
  32188. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32189. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32190. a.addAssign( uint( x ) );
  32191. b.addAssign( uint( y ) );
  32192. return mx_bjfinal( a, b, c );
  32193. } ).setLayout( {
  32194. name: 'mx_hash_int_1',
  32195. type: 'uint',
  32196. inputs: [
  32197. { name: 'x', type: 'int' },
  32198. { name: 'y', type: 'int' }
  32199. ]
  32200. } );
  32201. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  32202. const z = int( z_immutable ).toVar();
  32203. const y = int( y_immutable ).toVar();
  32204. const x = int( x_immutable ).toVar();
  32205. const len = uint( uint( 3 ) ).toVar();
  32206. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32207. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32208. a.addAssign( uint( x ) );
  32209. b.addAssign( uint( y ) );
  32210. c.addAssign( uint( z ) );
  32211. return mx_bjfinal( a, b, c );
  32212. } ).setLayout( {
  32213. name: 'mx_hash_int_2',
  32214. type: 'uint',
  32215. inputs: [
  32216. { name: 'x', type: 'int' },
  32217. { name: 'y', type: 'int' },
  32218. { name: 'z', type: 'int' }
  32219. ]
  32220. } );
  32221. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  32222. const xx = int( xx_immutable ).toVar();
  32223. const z = int( z_immutable ).toVar();
  32224. const y = int( y_immutable ).toVar();
  32225. const x = int( x_immutable ).toVar();
  32226. const len = uint( uint( 4 ) ).toVar();
  32227. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32228. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32229. a.addAssign( uint( x ) );
  32230. b.addAssign( uint( y ) );
  32231. c.addAssign( uint( z ) );
  32232. mx_bjmix( a, b, c );
  32233. a.addAssign( uint( xx ) );
  32234. return mx_bjfinal( a, b, c );
  32235. } ).setLayout( {
  32236. name: 'mx_hash_int_3',
  32237. type: 'uint',
  32238. inputs: [
  32239. { name: 'x', type: 'int' },
  32240. { name: 'y', type: 'int' },
  32241. { name: 'z', type: 'int' },
  32242. { name: 'xx', type: 'int' }
  32243. ]
  32244. } );
  32245. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  32246. const yy = int( yy_immutable ).toVar();
  32247. const xx = int( xx_immutable ).toVar();
  32248. const z = int( z_immutable ).toVar();
  32249. const y = int( y_immutable ).toVar();
  32250. const x = int( x_immutable ).toVar();
  32251. const len = uint( uint( 5 ) ).toVar();
  32252. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32253. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32254. a.addAssign( uint( x ) );
  32255. b.addAssign( uint( y ) );
  32256. c.addAssign( uint( z ) );
  32257. mx_bjmix( a, b, c );
  32258. a.addAssign( uint( xx ) );
  32259. b.addAssign( uint( yy ) );
  32260. return mx_bjfinal( a, b, c );
  32261. } ).setLayout( {
  32262. name: 'mx_hash_int_4',
  32263. type: 'uint',
  32264. inputs: [
  32265. { name: 'x', type: 'int' },
  32266. { name: 'y', type: 'int' },
  32267. { name: 'z', type: 'int' },
  32268. { name: 'xx', type: 'int' },
  32269. { name: 'yy', type: 'int' }
  32270. ]
  32271. } );
  32272. 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 ] );
  32273. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  32274. const y = int( y_immutable ).toVar();
  32275. const x = int( x_immutable ).toVar();
  32276. const h = uint( mx_hash_int( x, y ) ).toVar();
  32277. const result = uvec3().toVar();
  32278. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  32279. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  32280. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  32281. return result;
  32282. } ).setLayout( {
  32283. name: 'mx_hash_vec3_0',
  32284. type: 'uvec3',
  32285. inputs: [
  32286. { name: 'x', type: 'int' },
  32287. { name: 'y', type: 'int' }
  32288. ]
  32289. } );
  32290. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  32291. const z = int( z_immutable ).toVar();
  32292. const y = int( y_immutable ).toVar();
  32293. const x = int( x_immutable ).toVar();
  32294. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  32295. const result = uvec3().toVar();
  32296. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  32297. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  32298. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  32299. return result;
  32300. } ).setLayout( {
  32301. name: 'mx_hash_vec3_1',
  32302. type: 'uvec3',
  32303. inputs: [
  32304. { name: 'x', type: 'int' },
  32305. { name: 'y', type: 'int' },
  32306. { name: 'z', type: 'int' }
  32307. ]
  32308. } );
  32309. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  32310. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32311. const p = vec2( p_immutable ).toVar();
  32312. const X = int().toVar(), Y = int().toVar();
  32313. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32314. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32315. const u = float( mx_fade( fx ) ).toVar();
  32316. const v = float( mx_fade( fy ) ).toVar();
  32317. 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();
  32318. return mx_gradient_scale2d( result );
  32319. } ).setLayout( {
  32320. name: 'mx_perlin_noise_float_0',
  32321. type: 'float',
  32322. inputs: [
  32323. { name: 'p', type: 'vec2' }
  32324. ]
  32325. } );
  32326. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32327. const p = vec3( p_immutable ).toVar();
  32328. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32329. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32330. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32331. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  32332. const u = float( mx_fade( fx ) ).toVar();
  32333. const v = float( mx_fade( fy ) ).toVar();
  32334. const w = float( mx_fade( fz ) ).toVar();
  32335. 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();
  32336. return mx_gradient_scale3d( result );
  32337. } ).setLayout( {
  32338. name: 'mx_perlin_noise_float_1',
  32339. type: 'float',
  32340. inputs: [
  32341. { name: 'p', type: 'vec3' }
  32342. ]
  32343. } );
  32344. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  32345. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32346. const p = vec2( p_immutable ).toVar();
  32347. const X = int().toVar(), Y = int().toVar();
  32348. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32349. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32350. const u = float( mx_fade( fx ) ).toVar();
  32351. const v = float( mx_fade( fy ) ).toVar();
  32352. 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();
  32353. return mx_gradient_scale2d( result );
  32354. } ).setLayout( {
  32355. name: 'mx_perlin_noise_vec3_0',
  32356. type: 'vec3',
  32357. inputs: [
  32358. { name: 'p', type: 'vec2' }
  32359. ]
  32360. } );
  32361. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32362. const p = vec3( p_immutable ).toVar();
  32363. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32364. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32365. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32366. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  32367. const u = float( mx_fade( fx ) ).toVar();
  32368. const v = float( mx_fade( fy ) ).toVar();
  32369. const w = float( mx_fade( fz ) ).toVar();
  32370. 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();
  32371. return mx_gradient_scale3d( result );
  32372. } ).setLayout( {
  32373. name: 'mx_perlin_noise_vec3_1',
  32374. type: 'vec3',
  32375. inputs: [
  32376. { name: 'p', type: 'vec3' }
  32377. ]
  32378. } );
  32379. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  32380. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32381. const p = float( p_immutable ).toVar();
  32382. const ix = int( mx_floor( p ) ).toVar();
  32383. return mx_bits_to_01( mx_hash_int( ix ) );
  32384. } ).setLayout( {
  32385. name: 'mx_cell_noise_float_0',
  32386. type: 'float',
  32387. inputs: [
  32388. { name: 'p', type: 'float' }
  32389. ]
  32390. } );
  32391. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32392. const p = vec2( p_immutable ).toVar();
  32393. const ix = int( mx_floor( p.x ) ).toVar();
  32394. const iy = int( mx_floor( p.y ) ).toVar();
  32395. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  32396. } ).setLayout( {
  32397. name: 'mx_cell_noise_float_1',
  32398. type: 'float',
  32399. inputs: [
  32400. { name: 'p', type: 'vec2' }
  32401. ]
  32402. } );
  32403. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32404. const p = vec3( p_immutable ).toVar();
  32405. const ix = int( mx_floor( p.x ) ).toVar();
  32406. const iy = int( mx_floor( p.y ) ).toVar();
  32407. const iz = int( mx_floor( p.z ) ).toVar();
  32408. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  32409. } ).setLayout( {
  32410. name: 'mx_cell_noise_float_2',
  32411. type: 'float',
  32412. inputs: [
  32413. { name: 'p', type: 'vec3' }
  32414. ]
  32415. } );
  32416. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32417. const p = vec4( p_immutable ).toVar();
  32418. const ix = int( mx_floor( p.x ) ).toVar();
  32419. const iy = int( mx_floor( p.y ) ).toVar();
  32420. const iz = int( mx_floor( p.z ) ).toVar();
  32421. const iw = int( mx_floor( p.w ) ).toVar();
  32422. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  32423. } ).setLayout( {
  32424. name: 'mx_cell_noise_float_3',
  32425. type: 'float',
  32426. inputs: [
  32427. { name: 'p', type: 'vec4' }
  32428. ]
  32429. } );
  32430. 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 ] );
  32431. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32432. const p = float( p_immutable ).toVar();
  32433. const ix = int( mx_floor( p ) ).toVar();
  32434. 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 ) ) ) );
  32435. } ).setLayout( {
  32436. name: 'mx_cell_noise_vec3_0',
  32437. type: 'vec3',
  32438. inputs: [
  32439. { name: 'p', type: 'float' }
  32440. ]
  32441. } );
  32442. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32443. const p = vec2( p_immutable ).toVar();
  32444. const ix = int( mx_floor( p.x ) ).toVar();
  32445. const iy = int( mx_floor( p.y ) ).toVar();
  32446. 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 ) ) ) );
  32447. } ).setLayout( {
  32448. name: 'mx_cell_noise_vec3_1',
  32449. type: 'vec3',
  32450. inputs: [
  32451. { name: 'p', type: 'vec2' }
  32452. ]
  32453. } );
  32454. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32455. const p = vec3( p_immutable ).toVar();
  32456. const ix = int( mx_floor( p.x ) ).toVar();
  32457. const iy = int( mx_floor( p.y ) ).toVar();
  32458. const iz = int( mx_floor( p.z ) ).toVar();
  32459. 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 ) ) ) );
  32460. } ).setLayout( {
  32461. name: 'mx_cell_noise_vec3_2',
  32462. type: 'vec3',
  32463. inputs: [
  32464. { name: 'p', type: 'vec3' }
  32465. ]
  32466. } );
  32467. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32468. const p = vec4( p_immutable ).toVar();
  32469. const ix = int( mx_floor( p.x ) ).toVar();
  32470. const iy = int( mx_floor( p.y ) ).toVar();
  32471. const iz = int( mx_floor( p.z ) ).toVar();
  32472. const iw = int( mx_floor( p.w ) ).toVar();
  32473. 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 ) ) ) );
  32474. } ).setLayout( {
  32475. name: 'mx_cell_noise_vec3_3',
  32476. type: 'vec3',
  32477. inputs: [
  32478. { name: 'p', type: 'vec4' }
  32479. ]
  32480. } );
  32481. 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 ] );
  32482. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32483. const diminish = float( diminish_immutable ).toVar();
  32484. const lacunarity = float( lacunarity_immutable ).toVar();
  32485. const octaves = int( octaves_immutable ).toVar();
  32486. const p = vec3( p_immutable ).toVar();
  32487. const result = float( 0.0 ).toVar();
  32488. const amplitude = float( 1.0 ).toVar();
  32489. Loop( octaves, () => {
  32490. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  32491. amplitude.mulAssign( diminish );
  32492. p.mulAssign( lacunarity );
  32493. } );
  32494. return result;
  32495. } ).setLayout( {
  32496. name: 'mx_fractal_noise_float',
  32497. type: 'float',
  32498. inputs: [
  32499. { name: 'p', type: 'vec3' },
  32500. { name: 'octaves', type: 'int' },
  32501. { name: 'lacunarity', type: 'float' },
  32502. { name: 'diminish', type: 'float' }
  32503. ]
  32504. } );
  32505. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32506. const diminish = float( diminish_immutable ).toVar();
  32507. const lacunarity = float( lacunarity_immutable ).toVar();
  32508. const octaves = int( octaves_immutable ).toVar();
  32509. const p = vec3( p_immutable ).toVar();
  32510. const result = vec3( 0.0 ).toVar();
  32511. const amplitude = float( 1.0 ).toVar();
  32512. Loop( octaves, () => {
  32513. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  32514. amplitude.mulAssign( diminish );
  32515. p.mulAssign( lacunarity );
  32516. } );
  32517. return result;
  32518. } ).setLayout( {
  32519. name: 'mx_fractal_noise_vec3',
  32520. type: 'vec3',
  32521. inputs: [
  32522. { name: 'p', type: 'vec3' },
  32523. { name: 'octaves', type: 'int' },
  32524. { name: 'lacunarity', type: 'float' },
  32525. { name: 'diminish', type: 'float' }
  32526. ]
  32527. } );
  32528. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32529. const diminish = float( diminish_immutable ).toVar();
  32530. const lacunarity = float( lacunarity_immutable ).toVar();
  32531. const octaves = int( octaves_immutable ).toVar();
  32532. const p = vec3( p_immutable ).toVar();
  32533. 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 ) );
  32534. } ).setLayout( {
  32535. name: 'mx_fractal_noise_vec2',
  32536. type: 'vec2',
  32537. inputs: [
  32538. { name: 'p', type: 'vec3' },
  32539. { name: 'octaves', type: 'int' },
  32540. { name: 'lacunarity', type: 'float' },
  32541. { name: 'diminish', type: 'float' }
  32542. ]
  32543. } );
  32544. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32545. const diminish = float( diminish_immutable ).toVar();
  32546. const lacunarity = float( lacunarity_immutable ).toVar();
  32547. const octaves = int( octaves_immutable ).toVar();
  32548. const p = vec3( p_immutable ).toVar();
  32549. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  32550. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  32551. return vec4( c, f );
  32552. } ).setLayout( {
  32553. name: 'mx_fractal_noise_vec4',
  32554. type: 'vec4',
  32555. inputs: [
  32556. { name: 'p', type: 'vec3' },
  32557. { name: 'octaves', type: 'int' },
  32558. { name: 'lacunarity', type: 'float' },
  32559. { name: 'diminish', type: 'float' }
  32560. ]
  32561. } );
  32562. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  32563. const metric = int( metric_immutable ).toVar();
  32564. const jitter = float( jitter_immutable ).toVar();
  32565. const yoff = int( yoff_immutable ).toVar();
  32566. const xoff = int( xoff_immutable ).toVar();
  32567. const y = int( y_immutable ).toVar();
  32568. const x = int( x_immutable ).toVar();
  32569. const p = vec2( p_immutable ).toVar();
  32570. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  32571. const off = vec2( tmp.x, tmp.y ).toVar();
  32572. off.subAssign( 0.5 );
  32573. off.mulAssign( jitter );
  32574. off.addAssign( 0.5 );
  32575. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  32576. const diff = vec2( cellpos.sub( p ) ).toVar();
  32577. If( metric.equal( int( 2 ) ), () => {
  32578. return abs( diff.x ).add( abs( diff.y ) );
  32579. } );
  32580. If( metric.equal( int( 3 ) ), () => {
  32581. return max$1( abs( diff.x ), abs( diff.y ) );
  32582. } );
  32583. return dot( diff, diff );
  32584. } ).setLayout( {
  32585. name: 'mx_worley_distance_0',
  32586. type: 'float',
  32587. inputs: [
  32588. { name: 'p', type: 'vec2' },
  32589. { name: 'x', type: 'int' },
  32590. { name: 'y', type: 'int' },
  32591. { name: 'xoff', type: 'int' },
  32592. { name: 'yoff', type: 'int' },
  32593. { name: 'jitter', type: 'float' },
  32594. { name: 'metric', type: 'int' }
  32595. ]
  32596. } );
  32597. 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 ] ) => {
  32598. const metric = int( metric_immutable ).toVar();
  32599. const jitter = float( jitter_immutable ).toVar();
  32600. const zoff = int( zoff_immutable ).toVar();
  32601. const yoff = int( yoff_immutable ).toVar();
  32602. const xoff = int( xoff_immutable ).toVar();
  32603. const z = int( z_immutable ).toVar();
  32604. const y = int( y_immutable ).toVar();
  32605. const x = int( x_immutable ).toVar();
  32606. const p = vec3( p_immutable ).toVar();
  32607. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  32608. off.subAssign( 0.5 );
  32609. off.mulAssign( jitter );
  32610. off.addAssign( 0.5 );
  32611. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  32612. const diff = vec3( cellpos.sub( p ) ).toVar();
  32613. If( metric.equal( int( 2 ) ), () => {
  32614. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  32615. } );
  32616. If( metric.equal( int( 3 ) ), () => {
  32617. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  32618. } );
  32619. return dot( diff, diff );
  32620. } ).setLayout( {
  32621. name: 'mx_worley_distance_1',
  32622. type: 'float',
  32623. inputs: [
  32624. { name: 'p', type: 'vec3' },
  32625. { name: 'x', type: 'int' },
  32626. { name: 'y', type: 'int' },
  32627. { name: 'z', type: 'int' },
  32628. { name: 'xoff', type: 'int' },
  32629. { name: 'yoff', type: 'int' },
  32630. { name: 'zoff', type: 'int' },
  32631. { name: 'jitter', type: 'float' },
  32632. { name: 'metric', type: 'int' }
  32633. ]
  32634. } );
  32635. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  32636. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32637. const metric = int( metric_immutable ).toVar();
  32638. const jitter = float( jitter_immutable ).toVar();
  32639. const p = vec2( p_immutable ).toVar();
  32640. const X = int().toVar(), Y = int().toVar();
  32641. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  32642. const sqdist = float( 1e6 ).toVar();
  32643. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32644. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32645. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  32646. sqdist.assign( min$1( sqdist, dist ) );
  32647. } );
  32648. } );
  32649. If( metric.equal( int( 0 ) ), () => {
  32650. sqdist.assign( sqrt( sqdist ) );
  32651. } );
  32652. return sqdist;
  32653. } ).setLayout( {
  32654. name: 'mx_worley_noise_float_0',
  32655. type: 'float',
  32656. inputs: [
  32657. { name: 'p', type: 'vec2' },
  32658. { name: 'jitter', type: 'float' },
  32659. { name: 'metric', type: 'int' }
  32660. ]
  32661. } );
  32662. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32663. const metric = int( metric_immutable ).toVar();
  32664. const jitter = float( jitter_immutable ).toVar();
  32665. const p = vec2( p_immutable ).toVar();
  32666. const X = int().toVar(), Y = int().toVar();
  32667. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  32668. const sqdist = vec2( 1e6, 1e6 ).toVar();
  32669. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32670. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32671. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  32672. If( dist.lessThan( sqdist.x ), () => {
  32673. sqdist.y.assign( sqdist.x );
  32674. sqdist.x.assign( dist );
  32675. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  32676. sqdist.y.assign( dist );
  32677. } );
  32678. } );
  32679. } );
  32680. If( metric.equal( int( 0 ) ), () => {
  32681. sqdist.assign( sqrt( sqdist ) );
  32682. } );
  32683. return sqdist;
  32684. } ).setLayout( {
  32685. name: 'mx_worley_noise_vec2_0',
  32686. type: 'vec2',
  32687. inputs: [
  32688. { name: 'p', type: 'vec2' },
  32689. { name: 'jitter', type: 'float' },
  32690. { name: 'metric', type: 'int' }
  32691. ]
  32692. } );
  32693. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32694. const metric = int( metric_immutable ).toVar();
  32695. const jitter = float( jitter_immutable ).toVar();
  32696. const p = vec2( p_immutable ).toVar();
  32697. const X = int().toVar(), Y = int().toVar();
  32698. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  32699. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  32700. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32701. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32702. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  32703. If( dist.lessThan( sqdist.x ), () => {
  32704. sqdist.z.assign( sqdist.y );
  32705. sqdist.y.assign( sqdist.x );
  32706. sqdist.x.assign( dist );
  32707. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  32708. sqdist.z.assign( sqdist.y );
  32709. sqdist.y.assign( dist );
  32710. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  32711. sqdist.z.assign( dist );
  32712. } );
  32713. } );
  32714. } );
  32715. If( metric.equal( int( 0 ) ), () => {
  32716. sqdist.assign( sqrt( sqdist ) );
  32717. } );
  32718. return sqdist;
  32719. } ).setLayout( {
  32720. name: 'mx_worley_noise_vec3_0',
  32721. type: 'vec3',
  32722. inputs: [
  32723. { name: 'p', type: 'vec2' },
  32724. { name: 'jitter', type: 'float' },
  32725. { name: 'metric', type: 'int' }
  32726. ]
  32727. } );
  32728. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32729. const metric = int( metric_immutable ).toVar();
  32730. const jitter = float( jitter_immutable ).toVar();
  32731. const p = vec3( p_immutable ).toVar();
  32732. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32733. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  32734. const sqdist = float( 1e6 ).toVar();
  32735. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32736. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32737. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  32738. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  32739. sqdist.assign( min$1( sqdist, dist ) );
  32740. } );
  32741. } );
  32742. } );
  32743. If( metric.equal( int( 0 ) ), () => {
  32744. sqdist.assign( sqrt( sqdist ) );
  32745. } );
  32746. return sqdist;
  32747. } ).setLayout( {
  32748. name: 'mx_worley_noise_float_1',
  32749. type: 'float',
  32750. inputs: [
  32751. { name: 'p', type: 'vec3' },
  32752. { name: 'jitter', type: 'float' },
  32753. { name: 'metric', type: 'int' }
  32754. ]
  32755. } );
  32756. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  32757. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32758. const metric = int( metric_immutable ).toVar();
  32759. const jitter = float( jitter_immutable ).toVar();
  32760. const p = vec3( p_immutable ).toVar();
  32761. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32762. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  32763. const sqdist = vec2( 1e6, 1e6 ).toVar();
  32764. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32765. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32766. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  32767. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  32768. If( dist.lessThan( sqdist.x ), () => {
  32769. sqdist.y.assign( sqdist.x );
  32770. sqdist.x.assign( dist );
  32771. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  32772. sqdist.y.assign( dist );
  32773. } );
  32774. } );
  32775. } );
  32776. } );
  32777. If( metric.equal( int( 0 ) ), () => {
  32778. sqdist.assign( sqrt( sqdist ) );
  32779. } );
  32780. return sqdist;
  32781. } ).setLayout( {
  32782. name: 'mx_worley_noise_vec2_1',
  32783. type: 'vec2',
  32784. inputs: [
  32785. { name: 'p', type: 'vec3' },
  32786. { name: 'jitter', type: 'float' },
  32787. { name: 'metric', type: 'int' }
  32788. ]
  32789. } );
  32790. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  32791. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32792. const metric = int( metric_immutable ).toVar();
  32793. const jitter = float( jitter_immutable ).toVar();
  32794. const p = vec3( p_immutable ).toVar();
  32795. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32796. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  32797. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  32798. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32799. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32800. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  32801. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  32802. If( dist.lessThan( sqdist.x ), () => {
  32803. sqdist.z.assign( sqdist.y );
  32804. sqdist.y.assign( sqdist.x );
  32805. sqdist.x.assign( dist );
  32806. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  32807. sqdist.z.assign( sqdist.y );
  32808. sqdist.y.assign( dist );
  32809. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  32810. sqdist.z.assign( dist );
  32811. } );
  32812. } );
  32813. } );
  32814. } );
  32815. If( metric.equal( int( 0 ) ), () => {
  32816. sqdist.assign( sqrt( sqdist ) );
  32817. } );
  32818. return sqdist;
  32819. } ).setLayout( {
  32820. name: 'mx_worley_noise_vec3_1',
  32821. type: 'vec3',
  32822. inputs: [
  32823. { name: 'p', type: 'vec3' },
  32824. { name: 'jitter', type: 'float' },
  32825. { name: 'metric', type: 'int' }
  32826. ]
  32827. } );
  32828. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  32829. // Unified Noise 2D
  32830. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  32831. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  32832. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  32833. octaves_immutable, lacunarity_immutable, diminish_immutable
  32834. ] ) => {
  32835. const noiseType = int( noiseType_immutable ).toVar();
  32836. const texcoord = vec2( texcoord_immutable ).toVar();
  32837. const freq = vec2( freq_immutable ).toVar();
  32838. const offset = vec2( offset_immutable ).toVar();
  32839. const jitter = float( jitter_immutable ).toVar();
  32840. const outmin = float( outmin_immutable ).toVar();
  32841. const outmax = float( outmax_immutable ).toVar();
  32842. const clampoutput = bool( clampoutput_immutable ).toVar();
  32843. const octaves = int( octaves_immutable ).toVar();
  32844. const lacunarity = float( lacunarity_immutable ).toVar();
  32845. const diminish = float( diminish_immutable ).toVar();
  32846. // Compute input position
  32847. const p = texcoord.mul( freq ).add( offset );
  32848. const result = float( 0.0 ).toVar();
  32849. // Perlin
  32850. If( noiseType.equal( int( 0 ) ), () => {
  32851. result.assign( mx_perlin_noise_vec3( p ) );
  32852. } );
  32853. // Cell
  32854. If( noiseType.equal( int( 1 ) ), () => {
  32855. result.assign( mx_cell_noise_vec3( p ) );
  32856. } );
  32857. // Worley (metric=0 = euclidean)
  32858. If( noiseType.equal( int( 2 ) ), () => {
  32859. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  32860. } );
  32861. // Fractal (use vec3(p, 0.0) for 2D input)
  32862. If( noiseType.equal( int( 3 ) ), () => {
  32863. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  32864. } );
  32865. // Remap output to [outmin, outmax]
  32866. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  32867. // Clamp if requested
  32868. If( clampoutput, () => {
  32869. result.assign( clamp( result, outmin, outmax ) );
  32870. } );
  32871. return result;
  32872. } ).setLayout( {
  32873. name: 'mx_unifiednoise2d',
  32874. type: 'float',
  32875. inputs: [
  32876. { name: 'noiseType', type: 'int' },
  32877. { name: 'texcoord', type: 'vec2' },
  32878. { name: 'freq', type: 'vec2' },
  32879. { name: 'offset', type: 'vec2' },
  32880. { name: 'jitter', type: 'float' },
  32881. { name: 'outmin', type: 'float' },
  32882. { name: 'outmax', type: 'float' },
  32883. { name: 'clampoutput', type: 'bool' },
  32884. { name: 'octaves', type: 'int' },
  32885. { name: 'lacunarity', type: 'float' },
  32886. { name: 'diminish', type: 'float' }
  32887. ]
  32888. } );
  32889. // Unified Noise 3D
  32890. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  32891. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  32892. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  32893. octaves_immutable, lacunarity_immutable, diminish_immutable
  32894. ] ) => {
  32895. const noiseType = int( noiseType_immutable ).toVar();
  32896. const position = vec3( position_immutable ).toVar();
  32897. const freq = vec3( freq_immutable ).toVar();
  32898. const offset = vec3( offset_immutable ).toVar();
  32899. const jitter = float( jitter_immutable ).toVar();
  32900. const outmin = float( outmin_immutable ).toVar();
  32901. const outmax = float( outmax_immutable ).toVar();
  32902. const clampoutput = bool( clampoutput_immutable ).toVar();
  32903. const octaves = int( octaves_immutable ).toVar();
  32904. const lacunarity = float( lacunarity_immutable ).toVar();
  32905. const diminish = float( diminish_immutable ).toVar();
  32906. // Compute input position
  32907. const p = position.mul( freq ).add( offset );
  32908. const result = float( 0.0 ).toVar();
  32909. // Perlin
  32910. If( noiseType.equal( int( 0 ) ), () => {
  32911. result.assign( mx_perlin_noise_vec3( p ) );
  32912. } );
  32913. // Cell
  32914. If( noiseType.equal( int( 1 ) ), () => {
  32915. result.assign( mx_cell_noise_vec3( p ) );
  32916. } );
  32917. // Worley (metric=0 = euclidean)
  32918. If( noiseType.equal( int( 2 ) ), () => {
  32919. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  32920. } );
  32921. // Fractal
  32922. If( noiseType.equal( int( 3 ) ), () => {
  32923. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  32924. } );
  32925. // Remap output to [outmin, outmax]
  32926. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  32927. // Clamp if requested
  32928. If( clampoutput, () => {
  32929. result.assign( clamp( result, outmin, outmax ) );
  32930. } );
  32931. return result;
  32932. } ).setLayout( {
  32933. name: 'mx_unifiednoise3d',
  32934. type: 'float',
  32935. inputs: [
  32936. { name: 'noiseType', type: 'int' },
  32937. { name: 'position', type: 'vec3' },
  32938. { name: 'freq', type: 'vec3' },
  32939. { name: 'offset', type: 'vec3' },
  32940. { name: 'jitter', type: 'float' },
  32941. { name: 'outmin', type: 'float' },
  32942. { name: 'outmax', type: 'float' },
  32943. { name: 'clampoutput', type: 'bool' },
  32944. { name: 'octaves', type: 'int' },
  32945. { name: 'lacunarity', type: 'float' },
  32946. { name: 'diminish', type: 'float' }
  32947. ]
  32948. } );
  32949. // Three.js Transpiler
  32950. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  32951. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  32952. const s = hsv.y;
  32953. const v = hsv.z;
  32954. const result = vec3().toVar();
  32955. If( s.lessThan( 0.0001 ), () => {
  32956. result.assign( vec3( v, v, v ) );
  32957. } ).Else( () => {
  32958. let h = hsv.x;
  32959. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  32960. const hi = int( trunc( h ) );
  32961. const f = h.sub( float( hi ) );
  32962. const p = v.mul( s.oneMinus() );
  32963. const q = v.mul( s.mul( f ).oneMinus() );
  32964. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  32965. If( hi.equal( int( 0 ) ), () => {
  32966. result.assign( vec3( v, t, p ) );
  32967. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  32968. result.assign( vec3( q, v, p ) );
  32969. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  32970. result.assign( vec3( p, v, t ) );
  32971. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  32972. result.assign( vec3( p, q, v ) );
  32973. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  32974. result.assign( vec3( t, p, v ) );
  32975. } ).Else( () => {
  32976. result.assign( vec3( v, p, q ) );
  32977. } );
  32978. } );
  32979. return result;
  32980. } ).setLayout( {
  32981. name: 'mx_hsvtorgb',
  32982. type: 'vec3',
  32983. inputs: [
  32984. { name: 'hsv', type: 'vec3' }
  32985. ]
  32986. } );
  32987. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  32988. const c = vec3( c_immutable ).toVar();
  32989. const r = float( c.x ).toVar();
  32990. const g = float( c.y ).toVar();
  32991. const b = float( c.z ).toVar();
  32992. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  32993. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  32994. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  32995. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  32996. v.assign( maxcomp );
  32997. If( maxcomp.greaterThan( 0.0 ), () => {
  32998. s.assign( delta.div( maxcomp ) );
  32999. } ).Else( () => {
  33000. s.assign( 0.0 );
  33001. } );
  33002. If( s.lessThanEqual( 0.0 ), () => {
  33003. h.assign( 0.0 );
  33004. } ).Else( () => {
  33005. If( r.greaterThanEqual( maxcomp ), () => {
  33006. h.assign( g.sub( b ).div( delta ) );
  33007. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  33008. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  33009. } ).Else( () => {
  33010. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  33011. } );
  33012. h.mulAssign( 1.0 / 6.0 );
  33013. If( h.lessThan( 0.0 ), () => {
  33014. h.addAssign( 1.0 );
  33015. } );
  33016. } );
  33017. return vec3( h, s, v );
  33018. } ).setLayout( {
  33019. name: 'mx_rgbtohsv',
  33020. type: 'vec3',
  33021. inputs: [
  33022. { name: 'c', type: 'vec3' }
  33023. ]
  33024. } );
  33025. // Three.js Transpiler
  33026. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  33027. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  33028. const color = vec3( color_immutable ).toVar();
  33029. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  33030. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  33031. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  33032. return mix( linSeg, powSeg, isAbove );
  33033. } ).setLayout( {
  33034. name: 'mx_srgb_texture_to_lin_rec709',
  33035. type: 'vec3',
  33036. inputs: [
  33037. { name: 'color', type: 'vec3' }
  33038. ]
  33039. } );
  33040. const mx_aastep = ( threshold, value ) => {
  33041. threshold = float( threshold );
  33042. value = float( value );
  33043. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  33044. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  33045. };
  33046. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  33047. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  33048. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  33049. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  33050. const mx_ramp4 = (
  33051. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  33052. ) => {
  33053. const u = texcoord.x.clamp();
  33054. const v = texcoord.y.clamp();
  33055. const top = mix( valuetl, valuetr, u );
  33056. const bottom = mix( valuebl, valuebr, u );
  33057. return mix( top, bottom, v );
  33058. };
  33059. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  33060. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  33061. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  33062. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  33063. const mx_safepower = ( in1, in2 = 1 ) => {
  33064. in1 = float( in1 );
  33065. return in1.abs().pow( in2 ).mul( in1.sign() );
  33066. };
  33067. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  33068. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33069. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33070. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33071. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  33072. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  33073. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  33074. return noise_vec4.mul( amplitude ).add( pivot );
  33075. };
  33076. 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 );
  33077. 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 );
  33078. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33079. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33080. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33081. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  33082. 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 );
  33083. 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 );
  33084. 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 );
  33085. 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 );
  33086. // === Moved from MaterialXLoader.js ===
  33087. // Math ops
  33088. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  33089. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  33090. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  33091. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  33092. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  33093. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  33094. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  33095. const mx_timer = () => time;
  33096. const mx_frame = () => frameId;
  33097. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  33098. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  33099. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  33100. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  33101. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  33102. const mx_separate = ( in1, channelOrOut = null ) => {
  33103. if ( typeof channelOrOut === 'string' ) {
  33104. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  33105. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  33106. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  33107. }
  33108. if ( typeof channelOrOut === 'number' ) {
  33109. return in1.element( channelOrOut );
  33110. }
  33111. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  33112. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  33113. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  33114. }
  33115. return in1;
  33116. };
  33117. const mx_place2d = (
  33118. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  33119. ) => {
  33120. let uv = texcoord;
  33121. if ( pivot ) uv = uv.sub( pivot );
  33122. if ( scale ) uv = uv.mul( scale );
  33123. if ( rotate ) {
  33124. const rad = rotate.mul( Math.PI / 180.0 );
  33125. const cosR = rad.cos();
  33126. const sinR = rad.sin();
  33127. uv = vec2(
  33128. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  33129. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  33130. );
  33131. }
  33132. if ( pivot ) uv = uv.add( pivot );
  33133. if ( offset ) uv = uv.add( offset );
  33134. return uv;
  33135. };
  33136. const mx_rotate2d = ( input, amount ) => {
  33137. input = vec2( input );
  33138. amount = float( amount );
  33139. const radians = amount.mul( Math.PI / 180.0 );
  33140. return rotate( input, radians );
  33141. };
  33142. const mx_rotate3d = ( input, amount, axis ) => {
  33143. input = vec3( input );
  33144. amount = float( amount );
  33145. axis = vec3( axis );
  33146. const radians = amount.mul( Math.PI / 180.0 );
  33147. const nAxis = axis.normalize();
  33148. const cosA = radians.cos();
  33149. const sinA = radians.sin();
  33150. const oneMinusCosA = float( 1 ).sub( cosA );
  33151. const rot =
  33152. input.mul( cosA )
  33153. .add( nAxis.cross( input ).mul( sinA ) )
  33154. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  33155. return rot;
  33156. };
  33157. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  33158. input = vec3( input );
  33159. scale = float( scale );
  33160. return bumpMap( input, scale );
  33161. };
  33162. /**
  33163. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  33164. *
  33165. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  33166. *
  33167. * ```js
  33168. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  33169. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  33170. * ```
  33171. *
  33172. * @tsl
  33173. * @function
  33174. * @param {Node<vec3>} normal - The normal to correct.
  33175. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  33176. * @param {Node<vec3>} cubePos - The cube position.
  33177. * @return {Node<vec3>} The parallax corrected normal.
  33178. */
  33179. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  33180. const nDir = normalize( normal ).toVar();
  33181. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  33182. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  33183. const rbminmax = vec3().toVar();
  33184. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  33185. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  33186. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  33187. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  33188. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  33189. return boxIntersection.sub( cubePos );
  33190. } );
  33191. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  33192. // normal is assumed to have unit length
  33193. const x = normal.x, y = normal.y, z = normal.z;
  33194. // band 0
  33195. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  33196. // band 1
  33197. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  33198. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  33199. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  33200. // band 2
  33201. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  33202. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  33203. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  33204. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  33205. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  33206. return result;
  33207. } );
  33208. // constants
  33209. var TSL = /*#__PURE__*/Object.freeze({
  33210. __proto__: null,
  33211. BRDF_GGX: BRDF_GGX,
  33212. BRDF_Lambert: BRDF_Lambert,
  33213. BasicPointShadowFilter: BasicPointShadowFilter,
  33214. BasicShadowFilter: BasicShadowFilter,
  33215. Break: Break,
  33216. Const: Const,
  33217. Continue: Continue,
  33218. DFGApprox: DFGApprox,
  33219. D_GGX: D_GGX,
  33220. Discard: Discard,
  33221. EPSILON: EPSILON,
  33222. F_Schlick: F_Schlick,
  33223. Fn: Fn,
  33224. HALF_PI: HALF_PI,
  33225. INFINITY: INFINITY,
  33226. If: If,
  33227. Loop: Loop,
  33228. NodeAccess: NodeAccess,
  33229. NodeShaderStage: NodeShaderStage,
  33230. NodeType: NodeType,
  33231. NodeUpdateType: NodeUpdateType,
  33232. OnBeforeMaterialUpdate: OnBeforeMaterialUpdate,
  33233. OnBeforeObjectUpdate: OnBeforeObjectUpdate,
  33234. OnMaterialUpdate: OnMaterialUpdate,
  33235. OnObjectUpdate: OnObjectUpdate,
  33236. PCFShadowFilter: PCFShadowFilter,
  33237. PCFSoftShadowFilter: PCFSoftShadowFilter,
  33238. PI: PI,
  33239. PI2: PI2,
  33240. PointShadowFilter: PointShadowFilter,
  33241. Return: Return,
  33242. Schlick_to_F0: Schlick_to_F0,
  33243. ScriptableNodeResources: ScriptableNodeResources,
  33244. ShaderNode: ShaderNode,
  33245. Stack: Stack,
  33246. Switch: Switch,
  33247. TBNViewMatrix: TBNViewMatrix,
  33248. TWO_PI: TWO_PI,
  33249. VSMShadowFilter: VSMShadowFilter,
  33250. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  33251. Var: Var,
  33252. VarIntent: VarIntent,
  33253. abs: abs,
  33254. acesFilmicToneMapping: acesFilmicToneMapping,
  33255. acos: acos,
  33256. add: add,
  33257. addMethodChaining: addMethodChaining,
  33258. addNodeElement: addNodeElement,
  33259. agxToneMapping: agxToneMapping,
  33260. all: all,
  33261. alphaT: alphaT,
  33262. and: and,
  33263. anisotropy: anisotropy,
  33264. anisotropyB: anisotropyB,
  33265. anisotropyT: anisotropyT,
  33266. any: any,
  33267. append: append,
  33268. array: array,
  33269. arrayBuffer: arrayBuffer,
  33270. asin: asin,
  33271. assign: assign,
  33272. atan: atan,
  33273. atan2: atan2,
  33274. atomicAdd: atomicAdd,
  33275. atomicAnd: atomicAnd,
  33276. atomicFunc: atomicFunc,
  33277. atomicLoad: atomicLoad,
  33278. atomicMax: atomicMax,
  33279. atomicMin: atomicMin,
  33280. atomicOr: atomicOr,
  33281. atomicStore: atomicStore,
  33282. atomicSub: atomicSub,
  33283. atomicXor: atomicXor,
  33284. attenuationColor: attenuationColor,
  33285. attenuationDistance: attenuationDistance,
  33286. attribute: attribute,
  33287. attributeArray: attributeArray,
  33288. backgroundBlurriness: backgroundBlurriness,
  33289. backgroundIntensity: backgroundIntensity,
  33290. backgroundRotation: backgroundRotation,
  33291. batch: batch,
  33292. bentNormalView: bentNormalView,
  33293. billboarding: billboarding,
  33294. bitAnd: bitAnd,
  33295. bitNot: bitNot,
  33296. bitOr: bitOr,
  33297. bitXor: bitXor,
  33298. bitangentGeometry: bitangentGeometry,
  33299. bitangentLocal: bitangentLocal,
  33300. bitangentView: bitangentView,
  33301. bitangentWorld: bitangentWorld,
  33302. bitcast: bitcast,
  33303. blendBurn: blendBurn,
  33304. blendColor: blendColor,
  33305. blendDodge: blendDodge,
  33306. blendOverlay: blendOverlay,
  33307. blendScreen: blendScreen,
  33308. blur: blur,
  33309. bool: bool,
  33310. buffer: buffer,
  33311. bufferAttribute: bufferAttribute,
  33312. builtin: builtin,
  33313. bumpMap: bumpMap,
  33314. burn: burn,
  33315. bvec2: bvec2,
  33316. bvec3: bvec3,
  33317. bvec4: bvec4,
  33318. bypass: bypass,
  33319. cache: cache,
  33320. call: call,
  33321. cameraFar: cameraFar,
  33322. cameraIndex: cameraIndex,
  33323. cameraNear: cameraNear,
  33324. cameraNormalMatrix: cameraNormalMatrix,
  33325. cameraPosition: cameraPosition,
  33326. cameraProjectionMatrix: cameraProjectionMatrix,
  33327. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  33328. cameraViewMatrix: cameraViewMatrix,
  33329. cameraViewport: cameraViewport,
  33330. cameraWorldMatrix: cameraWorldMatrix,
  33331. cbrt: cbrt,
  33332. cdl: cdl,
  33333. ceil: ceil,
  33334. checker: checker,
  33335. cineonToneMapping: cineonToneMapping,
  33336. clamp: clamp,
  33337. clearcoat: clearcoat,
  33338. clearcoatNormalView: clearcoatNormalView,
  33339. clearcoatRoughness: clearcoatRoughness,
  33340. code: code,
  33341. color: color,
  33342. colorSpaceToWorking: colorSpaceToWorking,
  33343. colorToDirection: colorToDirection,
  33344. compute: compute,
  33345. computeKernel: computeKernel,
  33346. computeSkinning: computeSkinning,
  33347. context: context,
  33348. convert: convert,
  33349. convertColorSpace: convertColorSpace,
  33350. convertToTexture: convertToTexture,
  33351. cos: cos,
  33352. countLeadingZeros: countLeadingZeros,
  33353. countOneBits: countOneBits,
  33354. countTrailingZeros: countTrailingZeros,
  33355. cross: cross,
  33356. cubeTexture: cubeTexture,
  33357. cubeTextureBase: cubeTextureBase,
  33358. cubeToUV: cubeToUV,
  33359. dFdx: dFdx,
  33360. dFdy: dFdy,
  33361. dashSize: dashSize,
  33362. debug: debug,
  33363. decrement: decrement,
  33364. decrementBefore: decrementBefore,
  33365. defaultBuildStages: defaultBuildStages,
  33366. defaultShaderStages: defaultShaderStages,
  33367. defined: defined,
  33368. degrees: degrees,
  33369. deltaTime: deltaTime,
  33370. densityFog: densityFog,
  33371. densityFogFactor: densityFogFactor,
  33372. depth: depth,
  33373. depthPass: depthPass,
  33374. determinant: determinant,
  33375. difference: difference,
  33376. diffuseColor: diffuseColor,
  33377. diffuseContribution: diffuseContribution,
  33378. directPointLight: directPointLight,
  33379. directionToColor: directionToColor,
  33380. directionToFaceDirection: directionToFaceDirection,
  33381. dispersion: dispersion,
  33382. distance: distance,
  33383. div: div,
  33384. dodge: dodge,
  33385. dot: dot,
  33386. drawIndex: drawIndex,
  33387. dynamicBufferAttribute: dynamicBufferAttribute,
  33388. element: element,
  33389. emissive: emissive,
  33390. equal: equal,
  33391. equals: equals,
  33392. equirectUV: equirectUV,
  33393. exp: exp,
  33394. exp2: exp2,
  33395. expression: expression,
  33396. faceDirection: faceDirection,
  33397. faceForward: faceForward,
  33398. faceforward: faceforward,
  33399. float: float,
  33400. floatBitsToInt: floatBitsToInt,
  33401. floatBitsToUint: floatBitsToUint,
  33402. floor: floor,
  33403. fog: fog,
  33404. fract: fract,
  33405. frameGroup: frameGroup,
  33406. frameId: frameId,
  33407. frontFacing: frontFacing,
  33408. fwidth: fwidth,
  33409. gain: gain,
  33410. gapSize: gapSize,
  33411. getConstNodeType: getConstNodeType,
  33412. getCurrentStack: getCurrentStack,
  33413. getDirection: getDirection,
  33414. getDistanceAttenuation: getDistanceAttenuation,
  33415. getGeometryRoughness: getGeometryRoughness,
  33416. getNormalFromDepth: getNormalFromDepth,
  33417. getParallaxCorrectNormal: getParallaxCorrectNormal,
  33418. getRoughness: getRoughness,
  33419. getScreenPosition: getScreenPosition,
  33420. getShIrradianceAt: getShIrradianceAt,
  33421. getShadowMaterial: getShadowMaterial,
  33422. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  33423. getTextureIndex: getTextureIndex,
  33424. getViewPosition: getViewPosition,
  33425. ggxConvolution: ggxConvolution,
  33426. globalId: globalId,
  33427. glsl: glsl,
  33428. glslFn: glslFn,
  33429. grayscale: grayscale,
  33430. greaterThan: greaterThan,
  33431. greaterThanEqual: greaterThanEqual,
  33432. hash: hash,
  33433. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  33434. highpModelViewMatrix: highpModelViewMatrix,
  33435. hue: hue,
  33436. increment: increment,
  33437. incrementBefore: incrementBefore,
  33438. inspector: inspector,
  33439. instance: instance,
  33440. instanceIndex: instanceIndex,
  33441. instancedArray: instancedArray,
  33442. instancedBufferAttribute: instancedBufferAttribute,
  33443. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  33444. instancedMesh: instancedMesh,
  33445. int: int,
  33446. intBitsToFloat: intBitsToFloat,
  33447. interleavedGradientNoise: interleavedGradientNoise,
  33448. inverse: inverse,
  33449. inverseSqrt: inverseSqrt,
  33450. inversesqrt: inversesqrt,
  33451. invocationLocalIndex: invocationLocalIndex,
  33452. invocationSubgroupIndex: invocationSubgroupIndex,
  33453. ior: ior,
  33454. iridescence: iridescence,
  33455. iridescenceIOR: iridescenceIOR,
  33456. iridescenceThickness: iridescenceThickness,
  33457. isolate: isolate,
  33458. ivec2: ivec2,
  33459. ivec3: ivec3,
  33460. ivec4: ivec4,
  33461. js: js,
  33462. label: label,
  33463. length: length,
  33464. lengthSq: lengthSq,
  33465. lessThan: lessThan,
  33466. lessThanEqual: lessThanEqual,
  33467. lightPosition: lightPosition,
  33468. lightProjectionUV: lightProjectionUV,
  33469. lightShadowMatrix: lightShadowMatrix,
  33470. lightTargetDirection: lightTargetDirection,
  33471. lightTargetPosition: lightTargetPosition,
  33472. lightViewPosition: lightViewPosition,
  33473. lightingContext: lightingContext,
  33474. lights: lights,
  33475. linearDepth: linearDepth,
  33476. linearToneMapping: linearToneMapping,
  33477. localId: localId,
  33478. log: log,
  33479. log2: log2,
  33480. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  33481. luminance: luminance,
  33482. mat2: mat2,
  33483. mat3: mat3,
  33484. mat4: mat4,
  33485. matcapUV: matcapUV,
  33486. materialAO: materialAO,
  33487. materialAlphaTest: materialAlphaTest,
  33488. materialAnisotropy: materialAnisotropy,
  33489. materialAnisotropyVector: materialAnisotropyVector,
  33490. materialAttenuationColor: materialAttenuationColor,
  33491. materialAttenuationDistance: materialAttenuationDistance,
  33492. materialClearcoat: materialClearcoat,
  33493. materialClearcoatNormal: materialClearcoatNormal,
  33494. materialClearcoatRoughness: materialClearcoatRoughness,
  33495. materialColor: materialColor,
  33496. materialDispersion: materialDispersion,
  33497. materialEmissive: materialEmissive,
  33498. materialEnvIntensity: materialEnvIntensity,
  33499. materialEnvRotation: materialEnvRotation,
  33500. materialIOR: materialIOR,
  33501. materialIridescence: materialIridescence,
  33502. materialIridescenceIOR: materialIridescenceIOR,
  33503. materialIridescenceThickness: materialIridescenceThickness,
  33504. materialLightMap: materialLightMap,
  33505. materialLineDashOffset: materialLineDashOffset,
  33506. materialLineDashSize: materialLineDashSize,
  33507. materialLineGapSize: materialLineGapSize,
  33508. materialLineScale: materialLineScale,
  33509. materialLineWidth: materialLineWidth,
  33510. materialMetalness: materialMetalness,
  33511. materialNormal: materialNormal,
  33512. materialOpacity: materialOpacity,
  33513. materialPointSize: materialPointSize,
  33514. materialReference: materialReference,
  33515. materialReflectivity: materialReflectivity,
  33516. materialRefractionRatio: materialRefractionRatio,
  33517. materialRotation: materialRotation,
  33518. materialRoughness: materialRoughness,
  33519. materialSheen: materialSheen,
  33520. materialSheenRoughness: materialSheenRoughness,
  33521. materialShininess: materialShininess,
  33522. materialSpecular: materialSpecular,
  33523. materialSpecularColor: materialSpecularColor,
  33524. materialSpecularIntensity: materialSpecularIntensity,
  33525. materialSpecularStrength: materialSpecularStrength,
  33526. materialThickness: materialThickness,
  33527. materialTransmission: materialTransmission,
  33528. max: max$1,
  33529. maxMipLevel: maxMipLevel,
  33530. mediumpModelViewMatrix: mediumpModelViewMatrix,
  33531. metalness: metalness,
  33532. min: min$1,
  33533. mix: mix,
  33534. mixElement: mixElement,
  33535. mod: mod,
  33536. modInt: modInt,
  33537. modelDirection: modelDirection,
  33538. modelNormalMatrix: modelNormalMatrix,
  33539. modelPosition: modelPosition,
  33540. modelRadius: modelRadius,
  33541. modelScale: modelScale,
  33542. modelViewMatrix: modelViewMatrix,
  33543. modelViewPosition: modelViewPosition,
  33544. modelViewProjection: modelViewProjection,
  33545. modelWorldMatrix: modelWorldMatrix,
  33546. modelWorldMatrixInverse: modelWorldMatrixInverse,
  33547. morphReference: morphReference,
  33548. mrt: mrt,
  33549. mul: mul,
  33550. mx_aastep: mx_aastep,
  33551. mx_add: mx_add,
  33552. mx_atan2: mx_atan2,
  33553. mx_cell_noise_float: mx_cell_noise_float,
  33554. mx_contrast: mx_contrast,
  33555. mx_divide: mx_divide,
  33556. mx_fractal_noise_float: mx_fractal_noise_float,
  33557. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  33558. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  33559. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  33560. mx_frame: mx_frame,
  33561. mx_heighttonormal: mx_heighttonormal,
  33562. mx_hsvtorgb: mx_hsvtorgb,
  33563. mx_ifequal: mx_ifequal,
  33564. mx_ifgreater: mx_ifgreater,
  33565. mx_ifgreatereq: mx_ifgreatereq,
  33566. mx_invert: mx_invert,
  33567. mx_modulo: mx_modulo,
  33568. mx_multiply: mx_multiply,
  33569. mx_noise_float: mx_noise_float,
  33570. mx_noise_vec3: mx_noise_vec3,
  33571. mx_noise_vec4: mx_noise_vec4,
  33572. mx_place2d: mx_place2d,
  33573. mx_power: mx_power,
  33574. mx_ramp4: mx_ramp4,
  33575. mx_ramplr: mx_ramplr,
  33576. mx_ramptb: mx_ramptb,
  33577. mx_rgbtohsv: mx_rgbtohsv,
  33578. mx_rotate2d: mx_rotate2d,
  33579. mx_rotate3d: mx_rotate3d,
  33580. mx_safepower: mx_safepower,
  33581. mx_separate: mx_separate,
  33582. mx_splitlr: mx_splitlr,
  33583. mx_splittb: mx_splittb,
  33584. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  33585. mx_subtract: mx_subtract,
  33586. mx_timer: mx_timer,
  33587. mx_transform_uv: mx_transform_uv,
  33588. mx_unifiednoise2d: mx_unifiednoise2d,
  33589. mx_unifiednoise3d: mx_unifiednoise3d,
  33590. mx_worley_noise_float: mx_worley_noise_float,
  33591. mx_worley_noise_vec2: mx_worley_noise_vec2,
  33592. mx_worley_noise_vec3: mx_worley_noise_vec3,
  33593. negate: negate,
  33594. neutralToneMapping: neutralToneMapping,
  33595. nodeArray: nodeArray,
  33596. nodeImmutable: nodeImmutable,
  33597. nodeObject: nodeObject,
  33598. nodeObjectIntent: nodeObjectIntent,
  33599. nodeObjects: nodeObjects,
  33600. nodeProxy: nodeProxy,
  33601. nodeProxyIntent: nodeProxyIntent,
  33602. normalFlat: normalFlat,
  33603. normalGeometry: normalGeometry,
  33604. normalLocal: normalLocal,
  33605. normalMap: normalMap,
  33606. normalView: normalView,
  33607. normalViewGeometry: normalViewGeometry,
  33608. normalWorld: normalWorld,
  33609. normalWorldGeometry: normalWorldGeometry,
  33610. normalize: normalize,
  33611. not: not,
  33612. notEqual: notEqual,
  33613. numWorkgroups: numWorkgroups,
  33614. objectDirection: objectDirection,
  33615. objectGroup: objectGroup,
  33616. objectPosition: objectPosition,
  33617. objectRadius: objectRadius,
  33618. objectScale: objectScale,
  33619. objectViewPosition: objectViewPosition,
  33620. objectWorldMatrix: objectWorldMatrix,
  33621. oneMinus: oneMinus,
  33622. or: or,
  33623. orthographicDepthToViewZ: orthographicDepthToViewZ,
  33624. oscSawtooth: oscSawtooth,
  33625. oscSine: oscSine,
  33626. oscSquare: oscSquare,
  33627. oscTriangle: oscTriangle,
  33628. output: output,
  33629. outputStruct: outputStruct,
  33630. overlay: overlay,
  33631. overloadingFn: overloadingFn,
  33632. parabola: parabola,
  33633. parallaxDirection: parallaxDirection,
  33634. parallaxUV: parallaxUV,
  33635. parameter: parameter,
  33636. pass: pass,
  33637. passTexture: passTexture,
  33638. pcurve: pcurve,
  33639. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  33640. pmremTexture: pmremTexture,
  33641. pointShadow: pointShadow,
  33642. pointUV: pointUV,
  33643. pointWidth: pointWidth,
  33644. positionGeometry: positionGeometry,
  33645. positionLocal: positionLocal,
  33646. positionPrevious: positionPrevious,
  33647. positionView: positionView,
  33648. positionViewDirection: positionViewDirection,
  33649. positionWorld: positionWorld,
  33650. positionWorldDirection: positionWorldDirection,
  33651. posterize: posterize,
  33652. pow: pow,
  33653. pow2: pow2,
  33654. pow3: pow3,
  33655. pow4: pow4,
  33656. premultiplyAlpha: premultiplyAlpha,
  33657. property: property,
  33658. quadBroadcast: quadBroadcast,
  33659. quadSwapDiagonal: quadSwapDiagonal,
  33660. quadSwapX: quadSwapX,
  33661. quadSwapY: quadSwapY,
  33662. radians: radians,
  33663. rand: rand,
  33664. range: range,
  33665. rangeFog: rangeFog,
  33666. rangeFogFactor: rangeFogFactor,
  33667. reciprocal: reciprocal,
  33668. reference: reference,
  33669. referenceBuffer: referenceBuffer,
  33670. reflect: reflect,
  33671. reflectVector: reflectVector,
  33672. reflectView: reflectView,
  33673. reflector: reflector,
  33674. refract: refract,
  33675. refractVector: refractVector,
  33676. refractView: refractView,
  33677. reinhardToneMapping: reinhardToneMapping,
  33678. remap: remap,
  33679. remapClamp: remapClamp,
  33680. renderGroup: renderGroup,
  33681. renderOutput: renderOutput,
  33682. rendererReference: rendererReference,
  33683. replaceDefaultUV: replaceDefaultUV,
  33684. rotate: rotate,
  33685. rotateUV: rotateUV,
  33686. roughness: roughness,
  33687. round: round,
  33688. rtt: rtt,
  33689. sRGBTransferEOTF: sRGBTransferEOTF,
  33690. sRGBTransferOETF: sRGBTransferOETF,
  33691. sample: sample,
  33692. sampler: sampler,
  33693. samplerComparison: samplerComparison,
  33694. saturate: saturate,
  33695. saturation: saturation,
  33696. screen: screen,
  33697. screenCoordinate: screenCoordinate,
  33698. screenDPR: screenDPR,
  33699. screenSize: screenSize,
  33700. screenUV: screenUV,
  33701. scriptable: scriptable,
  33702. scriptableValue: scriptableValue,
  33703. select: select,
  33704. setCurrentStack: setCurrentStack,
  33705. setName: setName,
  33706. shaderStages: shaderStages,
  33707. shadow: shadow,
  33708. shadowPositionWorld: shadowPositionWorld,
  33709. shapeCircle: shapeCircle,
  33710. sharedUniformGroup: sharedUniformGroup,
  33711. sheen: sheen,
  33712. sheenRoughness: sheenRoughness,
  33713. shiftLeft: shiftLeft,
  33714. shiftRight: shiftRight,
  33715. shininess: shininess,
  33716. sign: sign,
  33717. sin: sin,
  33718. sinc: sinc,
  33719. skinning: skinning,
  33720. smoothstep: smoothstep,
  33721. smoothstepElement: smoothstepElement,
  33722. specularColor: specularColor,
  33723. specularColorBlended: specularColorBlended,
  33724. specularF90: specularF90,
  33725. spherizeUV: spherizeUV,
  33726. split: split,
  33727. spritesheetUV: spritesheetUV,
  33728. sqrt: sqrt,
  33729. stack: stack,
  33730. step: step,
  33731. stepElement: stepElement,
  33732. storage: storage,
  33733. storageBarrier: storageBarrier,
  33734. storageObject: storageObject,
  33735. storageTexture: storageTexture,
  33736. string: string,
  33737. struct: struct,
  33738. sub: sub,
  33739. subBuild: subBuild,
  33740. subgroupAdd: subgroupAdd,
  33741. subgroupAll: subgroupAll,
  33742. subgroupAnd: subgroupAnd,
  33743. subgroupAny: subgroupAny,
  33744. subgroupBallot: subgroupBallot,
  33745. subgroupBroadcast: subgroupBroadcast,
  33746. subgroupBroadcastFirst: subgroupBroadcastFirst,
  33747. subgroupElect: subgroupElect,
  33748. subgroupExclusiveAdd: subgroupExclusiveAdd,
  33749. subgroupExclusiveMul: subgroupExclusiveMul,
  33750. subgroupInclusiveAdd: subgroupInclusiveAdd,
  33751. subgroupInclusiveMul: subgroupInclusiveMul,
  33752. subgroupIndex: subgroupIndex,
  33753. subgroupMax: subgroupMax,
  33754. subgroupMin: subgroupMin,
  33755. subgroupMul: subgroupMul,
  33756. subgroupOr: subgroupOr,
  33757. subgroupShuffle: subgroupShuffle,
  33758. subgroupShuffleDown: subgroupShuffleDown,
  33759. subgroupShuffleUp: subgroupShuffleUp,
  33760. subgroupShuffleXor: subgroupShuffleXor,
  33761. subgroupSize: subgroupSize,
  33762. subgroupXor: subgroupXor,
  33763. tan: tan,
  33764. tangentGeometry: tangentGeometry,
  33765. tangentLocal: tangentLocal,
  33766. tangentView: tangentView,
  33767. tangentWorld: tangentWorld,
  33768. texture: texture,
  33769. texture3D: texture3D,
  33770. texture3DLevel: texture3DLevel,
  33771. texture3DLoad: texture3DLoad,
  33772. textureBarrier: textureBarrier,
  33773. textureBicubic: textureBicubic,
  33774. textureBicubicLevel: textureBicubicLevel,
  33775. textureCubeUV: textureCubeUV,
  33776. textureLevel: textureLevel,
  33777. textureLoad: textureLoad,
  33778. textureSize: textureSize,
  33779. textureStore: textureStore,
  33780. thickness: thickness,
  33781. time: time,
  33782. toneMapping: toneMapping,
  33783. toneMappingExposure: toneMappingExposure,
  33784. toonOutlinePass: toonOutlinePass,
  33785. transformDirection: transformDirection,
  33786. transformNormal: transformNormal,
  33787. transformNormalToView: transformNormalToView,
  33788. transformedClearcoatNormalView: transformedClearcoatNormalView,
  33789. transformedNormalView: transformedNormalView,
  33790. transformedNormalWorld: transformedNormalWorld,
  33791. transmission: transmission,
  33792. transpose: transpose,
  33793. triNoise3D: triNoise3D,
  33794. triplanarTexture: triplanarTexture,
  33795. triplanarTextures: triplanarTextures,
  33796. trunc: trunc,
  33797. uint: uint,
  33798. uintBitsToFloat: uintBitsToFloat,
  33799. uniform: uniform,
  33800. uniformArray: uniformArray,
  33801. uniformCubeTexture: uniformCubeTexture,
  33802. uniformFlow: uniformFlow,
  33803. uniformGroup: uniformGroup,
  33804. uniformTexture: uniformTexture,
  33805. unpackNormal: unpackNormal,
  33806. unpremultiplyAlpha: unpremultiplyAlpha,
  33807. userData: userData,
  33808. uv: uv$1,
  33809. uvec2: uvec2,
  33810. uvec3: uvec3,
  33811. uvec4: uvec4,
  33812. varying: varying,
  33813. varyingProperty: varyingProperty,
  33814. vec2: vec2,
  33815. vec3: vec3,
  33816. vec4: vec4,
  33817. vectorComponents: vectorComponents,
  33818. velocity: velocity,
  33819. vertexColor: vertexColor,
  33820. vertexIndex: vertexIndex,
  33821. vertexStage: vertexStage,
  33822. vibrance: vibrance,
  33823. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  33824. viewZToOrthographicDepth: viewZToOrthographicDepth,
  33825. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  33826. viewport: viewport,
  33827. viewportCoordinate: viewportCoordinate,
  33828. viewportDepthTexture: viewportDepthTexture,
  33829. viewportLinearDepth: viewportLinearDepth,
  33830. viewportMipTexture: viewportMipTexture,
  33831. viewportResolution: viewportResolution,
  33832. viewportSafeUV: viewportSafeUV,
  33833. viewportSharedTexture: viewportSharedTexture,
  33834. viewportSize: viewportSize,
  33835. viewportTexture: viewportTexture,
  33836. viewportUV: viewportUV,
  33837. wgsl: wgsl,
  33838. wgslFn: wgslFn,
  33839. workgroupArray: workgroupArray,
  33840. workgroupBarrier: workgroupBarrier,
  33841. workgroupId: workgroupId,
  33842. workingToColorSpace: workingToColorSpace,
  33843. xor: xor
  33844. });
  33845. const _clearColor = /*@__PURE__*/ new Color4();
  33846. /**
  33847. * This renderer module manages the background.
  33848. *
  33849. * @private
  33850. * @augments DataMap
  33851. */
  33852. class Background extends DataMap {
  33853. /**
  33854. * Constructs a new background management component.
  33855. *
  33856. * @param {Renderer} renderer - The renderer.
  33857. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  33858. */
  33859. constructor( renderer, nodes ) {
  33860. super();
  33861. /**
  33862. * The renderer.
  33863. *
  33864. * @type {Renderer}
  33865. */
  33866. this.renderer = renderer;
  33867. /**
  33868. * Renderer component for managing nodes related logic.
  33869. *
  33870. * @type {Nodes}
  33871. */
  33872. this.nodes = nodes;
  33873. }
  33874. /**
  33875. * Updates the background for the given scene. Depending on how `Scene.background`
  33876. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  33877. * or add a mesh to the render list for rendering the background as a textured plane
  33878. * or skybox.
  33879. *
  33880. * @param {Scene} scene - The scene.
  33881. * @param {RenderList} renderList - The current render list.
  33882. * @param {RenderContext} renderContext - The current render context.
  33883. */
  33884. update( scene, renderList, renderContext ) {
  33885. const renderer = this.renderer;
  33886. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  33887. let forceClear = false;
  33888. if ( background === null ) {
  33889. // no background settings, use clear color configuration from the renderer
  33890. renderer._clearColor.getRGB( _clearColor );
  33891. _clearColor.a = renderer._clearColor.a;
  33892. } else if ( background.isColor === true ) {
  33893. // background is an opaque color
  33894. background.getRGB( _clearColor );
  33895. _clearColor.a = 1;
  33896. forceClear = true;
  33897. } else if ( background.isNode === true ) {
  33898. const sceneData = this.get( scene );
  33899. const backgroundNode = background;
  33900. _clearColor.copy( renderer._clearColor );
  33901. let backgroundMesh = sceneData.backgroundMesh;
  33902. if ( backgroundMesh === undefined ) {
  33903. const backgroundMeshNode = vec4( backgroundNode ).mul( backgroundIntensity ).context( {
  33904. // @TODO: Add Texture2D support using node context
  33905. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  33906. getTextureLevel: () => backgroundBlurriness
  33907. } );
  33908. // when using orthographic cameras, we must scale the skybox sphere
  33909. // up to exceed the dimensions of the camera's viewing box.
  33910. const isOrtho = cameraProjectionMatrix.element( 3 ).element( 3 ).equal( 1.0 );
  33911. // calculate the orthographic scale
  33912. // projectionMatrix[1][1] is (1 / top). Invert it to get the height and multiply by 3.0
  33913. // (an arbitrary safety factor) to ensure the skybox is large enough to cover the corners
  33914. // of the rectangular screen
  33915. const orthoScale = div( 1.0, cameraProjectionMatrix.element( 1 ).element( 1 ) ).mul( 3.0 );
  33916. // compute vertex position
  33917. const modifiedPosition = isOrtho.select( positionLocal.mul( orthoScale ), positionLocal );
  33918. let viewProj = cameraProjectionMatrix.mul( modelViewMatrix.mul( vec4( modifiedPosition, 1.0 ) ) );
  33919. // force background to far plane so it does not occlude objects
  33920. viewProj = viewProj.setZ( viewProj.w );
  33921. const nodeMaterial = new NodeMaterial();
  33922. nodeMaterial.name = 'Background.material';
  33923. nodeMaterial.side = BackSide;
  33924. nodeMaterial.depthTest = false;
  33925. nodeMaterial.depthWrite = false;
  33926. nodeMaterial.allowOverride = false;
  33927. nodeMaterial.fog = false;
  33928. nodeMaterial.lights = false;
  33929. nodeMaterial.vertexNode = viewProj;
  33930. nodeMaterial.colorNode = backgroundMeshNode;
  33931. sceneData.backgroundMeshNode = backgroundMeshNode;
  33932. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  33933. backgroundMesh.frustumCulled = false;
  33934. backgroundMesh.name = 'Background.mesh';
  33935. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  33936. this.matrixWorld.copyPosition( camera.matrixWorld );
  33937. };
  33938. function onBackgroundDispose() {
  33939. background.removeEventListener( 'dispose', onBackgroundDispose );
  33940. backgroundMesh.material.dispose();
  33941. backgroundMesh.geometry.dispose();
  33942. }
  33943. background.addEventListener( 'dispose', onBackgroundDispose );
  33944. }
  33945. const backgroundCacheKey = backgroundNode.getCacheKey();
  33946. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  33947. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  33948. sceneData.backgroundMeshNode.needsUpdate = true;
  33949. backgroundMesh.material.needsUpdate = true;
  33950. sceneData.backgroundCacheKey = backgroundCacheKey;
  33951. }
  33952. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  33953. } else {
  33954. error( 'Renderer: Unsupported background configuration.', background );
  33955. }
  33956. //
  33957. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  33958. if ( environmentBlendMode === 'additive' ) {
  33959. _clearColor.set( 0, 0, 0, 1 );
  33960. } else if ( environmentBlendMode === 'alpha-blend' ) {
  33961. _clearColor.set( 0, 0, 0, 0 );
  33962. }
  33963. //
  33964. if ( renderer.autoClear === true || forceClear === true ) {
  33965. const clearColorValue = renderContext.clearColorValue;
  33966. clearColorValue.r = _clearColor.r;
  33967. clearColorValue.g = _clearColor.g;
  33968. clearColorValue.b = _clearColor.b;
  33969. clearColorValue.a = _clearColor.a;
  33970. // premultiply alpha
  33971. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  33972. clearColorValue.r *= clearColorValue.a;
  33973. clearColorValue.g *= clearColorValue.a;
  33974. clearColorValue.b *= clearColorValue.a;
  33975. }
  33976. //
  33977. renderContext.depthClearValue = renderer._clearDepth;
  33978. renderContext.stencilClearValue = renderer._clearStencil;
  33979. renderContext.clearColor = renderer.autoClearColor === true;
  33980. renderContext.clearDepth = renderer.autoClearDepth === true;
  33981. renderContext.clearStencil = renderer.autoClearStencil === true;
  33982. } else {
  33983. renderContext.clearColor = false;
  33984. renderContext.clearDepth = false;
  33985. renderContext.clearStencil = false;
  33986. }
  33987. }
  33988. }
  33989. let _id$7 = 0;
  33990. /**
  33991. * A bind group represents a collection of bindings and thus a collection
  33992. * or resources. Bind groups are assigned to pipelines to provide them
  33993. * with the required resources (like uniform buffers or textures).
  33994. *
  33995. * @private
  33996. */
  33997. class BindGroup {
  33998. /**
  33999. * Constructs a new bind group.
  34000. *
  34001. * @param {string} name - The bind group's name.
  34002. * @param {Array<Binding>} bindings - An array of bindings.
  34003. * @param {number} index - The group index.
  34004. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  34005. */
  34006. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  34007. /**
  34008. * The bind group's name.
  34009. *
  34010. * @type {string}
  34011. */
  34012. this.name = name;
  34013. /**
  34014. * An array of bindings.
  34015. *
  34016. * @type {Array<Binding>}
  34017. */
  34018. this.bindings = bindings;
  34019. /**
  34020. * The group index.
  34021. *
  34022. * @type {number}
  34023. */
  34024. this.index = index;
  34025. /**
  34026. * An array of reference bindings.
  34027. *
  34028. * @type {Array<Binding>}
  34029. */
  34030. this.bindingsReference = bindingsReference;
  34031. /**
  34032. * The group's ID.
  34033. *
  34034. * @type {number}
  34035. */
  34036. this.id = _id$7 ++;
  34037. }
  34038. }
  34039. /**
  34040. * This module represents the state of a node builder after it was
  34041. * used to build the nodes for a render object. The state holds the
  34042. * results of the build for further processing in the renderer.
  34043. *
  34044. * Render objects with identical cache keys share the same node builder state.
  34045. *
  34046. * @private
  34047. */
  34048. class NodeBuilderState {
  34049. /**
  34050. * Constructs a new node builder state.
  34051. *
  34052. * @param {string} vertexShader - The native vertex shader code.
  34053. * @param {string} fragmentShader - The native fragment shader code.
  34054. * @param {string} computeShader - The native compute shader code.
  34055. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  34056. * @param {Array<BindGroup>} bindings - An array of bind groups.
  34057. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  34058. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  34059. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  34060. * @param {NodeMaterialObserver} observer - A node material observer.
  34061. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  34062. */
  34063. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  34064. /**
  34065. * The native vertex shader code.
  34066. *
  34067. * @type {string}
  34068. */
  34069. this.vertexShader = vertexShader;
  34070. /**
  34071. * The native fragment shader code.
  34072. *
  34073. * @type {string}
  34074. */
  34075. this.fragmentShader = fragmentShader;
  34076. /**
  34077. * The native compute shader code.
  34078. *
  34079. * @type {string}
  34080. */
  34081. this.computeShader = computeShader;
  34082. /**
  34083. * An array with transform attribute objects.
  34084. * Only relevant when using compute shaders with WebGL 2.
  34085. *
  34086. * @type {Array<Object>}
  34087. */
  34088. this.transforms = transforms;
  34089. /**
  34090. * An array of node attributes representing
  34091. * the attributes of the shaders.
  34092. *
  34093. * @type {Array<NodeAttribute>}
  34094. */
  34095. this.nodeAttributes = nodeAttributes;
  34096. /**
  34097. * An array of bind groups representing the uniform or storage
  34098. * buffers, texture or samplers of the shader.
  34099. *
  34100. * @type {Array<BindGroup>}
  34101. */
  34102. this.bindings = bindings;
  34103. /**
  34104. * An array of nodes that implement their `update()` method.
  34105. *
  34106. * @type {Array<Node>}
  34107. */
  34108. this.updateNodes = updateNodes;
  34109. /**
  34110. * An array of nodes that implement their `updateBefore()` method.
  34111. *
  34112. * @type {Array<Node>}
  34113. */
  34114. this.updateBeforeNodes = updateBeforeNodes;
  34115. /**
  34116. * An array of nodes that implement their `updateAfter()` method.
  34117. *
  34118. * @type {Array<Node>}
  34119. */
  34120. this.updateAfterNodes = updateAfterNodes;
  34121. /**
  34122. * A node material observer.
  34123. *
  34124. * @type {NodeMaterialObserver}
  34125. */
  34126. this.observer = observer;
  34127. /**
  34128. * How often this state is used by render objects.
  34129. *
  34130. * @type {number}
  34131. */
  34132. this.usedTimes = 0;
  34133. }
  34134. /**
  34135. * This method is used to create a array of bind groups based
  34136. * on the existing bind groups of this state. Shared groups are
  34137. * not cloned.
  34138. *
  34139. * @return {Array<BindGroup>} A array of bind groups.
  34140. */
  34141. createBindings() {
  34142. const bindings = [];
  34143. for ( const instanceGroup of this.bindings ) {
  34144. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  34145. if ( shared !== true ) {
  34146. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup.bindingsReference );
  34147. bindings.push( bindingsGroup );
  34148. for ( const instanceBinding of instanceGroup.bindings ) {
  34149. bindingsGroup.bindings.push( instanceBinding.clone() );
  34150. }
  34151. } else {
  34152. bindings.push( instanceGroup );
  34153. }
  34154. }
  34155. return bindings;
  34156. }
  34157. }
  34158. /**
  34159. * {@link NodeBuilder} is going to create instances of this class during the build process
  34160. * of nodes. They represent the final shader attributes that are going to be generated
  34161. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  34162. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  34163. */
  34164. class NodeAttribute {
  34165. /**
  34166. * Constructs a new node attribute.
  34167. *
  34168. * @param {string} name - The name of the attribute.
  34169. * @param {string} type - The type of the attribute.
  34170. * @param {?Node} node - An optional reference to the node.
  34171. */
  34172. constructor( name, type, node = null ) {
  34173. /**
  34174. * This flag can be used for type testing.
  34175. *
  34176. * @type {boolean}
  34177. * @readonly
  34178. * @default true
  34179. */
  34180. this.isNodeAttribute = true;
  34181. /**
  34182. * The name of the attribute.
  34183. *
  34184. * @type {string}
  34185. */
  34186. this.name = name;
  34187. /**
  34188. * The type of the attribute.
  34189. *
  34190. * @type {string}
  34191. */
  34192. this.type = type;
  34193. /**
  34194. * An optional reference to the node.
  34195. *
  34196. * @type {?Node}
  34197. * @default null
  34198. */
  34199. this.node = node;
  34200. }
  34201. }
  34202. /**
  34203. * {@link NodeBuilder} is going to create instances of this class during the build process
  34204. * of nodes. They represent the final shader uniforms that are going to be generated
  34205. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  34206. * for this purpose.
  34207. */
  34208. class NodeUniform {
  34209. /**
  34210. * Constructs a new node uniform.
  34211. *
  34212. * @param {string} name - The name of the uniform.
  34213. * @param {string} type - The type of the uniform.
  34214. * @param {UniformNode} node - An reference to the node.
  34215. */
  34216. constructor( name, type, node ) {
  34217. /**
  34218. * This flag can be used for type testing.
  34219. *
  34220. * @type {boolean}
  34221. * @readonly
  34222. * @default true
  34223. */
  34224. this.isNodeUniform = true;
  34225. /**
  34226. * The name of the uniform.
  34227. *
  34228. * @type {string}
  34229. */
  34230. this.name = name;
  34231. /**
  34232. * The type of the uniform.
  34233. *
  34234. * @type {string}
  34235. */
  34236. this.type = type;
  34237. /**
  34238. * An reference to the node.
  34239. *
  34240. * @type {UniformNode}
  34241. */
  34242. this.node = node;
  34243. }
  34244. /**
  34245. * The value of the uniform node.
  34246. *
  34247. * @type {any}
  34248. */
  34249. get value() {
  34250. return this.node.value;
  34251. }
  34252. set value( val ) {
  34253. this.node.value = val;
  34254. }
  34255. /**
  34256. * The id of the uniform node.
  34257. *
  34258. * @type {number}
  34259. */
  34260. get id() {
  34261. return this.node.id;
  34262. }
  34263. /**
  34264. * The uniform node's group.
  34265. *
  34266. * @type {UniformGroupNode}
  34267. */
  34268. get groupNode() {
  34269. return this.node.groupNode;
  34270. }
  34271. }
  34272. /**
  34273. * {@link NodeBuilder} is going to create instances of this class during the build process
  34274. * of nodes. They represent the final shader variables that are going to be generated
  34275. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  34276. * this purpose.
  34277. */
  34278. class NodeVar {
  34279. /**
  34280. * Constructs a new node variable.
  34281. *
  34282. * @param {string} name - The name of the variable.
  34283. * @param {string} type - The type of the variable.
  34284. * @param {boolean} [readOnly=false] - The read-only flag.
  34285. * @param {?number} [count=null] - The size.
  34286. */
  34287. constructor( name, type, readOnly = false, count = null ) {
  34288. /**
  34289. * This flag can be used for type testing.
  34290. *
  34291. * @type {boolean}
  34292. * @readonly
  34293. * @default true
  34294. */
  34295. this.isNodeVar = true;
  34296. /**
  34297. * The name of the variable.
  34298. *
  34299. * @type {string}
  34300. */
  34301. this.name = name;
  34302. /**
  34303. * The type of the variable.
  34304. *
  34305. * @type {string}
  34306. */
  34307. this.type = type;
  34308. /**
  34309. * The read-only flag.
  34310. *
  34311. * @type {boolean}
  34312. */
  34313. this.readOnly = readOnly;
  34314. /**
  34315. * The size.
  34316. *
  34317. * @type {?number}
  34318. */
  34319. this.count = count;
  34320. }
  34321. }
  34322. /**
  34323. * {@link NodeBuilder} is going to create instances of this class during the build process
  34324. * of nodes. They represent the final shader varyings that are going to be generated
  34325. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  34326. * this purpose.
  34327. *
  34328. * @augments NodeVar
  34329. */
  34330. class NodeVarying extends NodeVar {
  34331. /**
  34332. * Constructs a new node varying.
  34333. *
  34334. * @param {string} name - The name of the varying.
  34335. * @param {string} type - The type of the varying.
  34336. * @param {?string} interpolationType - The interpolation type of the varying.
  34337. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  34338. */
  34339. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  34340. super( name, type );
  34341. /**
  34342. * Whether this varying requires interpolation or not. This property can be used
  34343. * to check if the varying can be optimized for a variable.
  34344. *
  34345. * @type {boolean}
  34346. * @default false
  34347. */
  34348. this.needsInterpolation = false;
  34349. /**
  34350. * This flag can be used for type testing.
  34351. *
  34352. * @type {boolean}
  34353. * @readonly
  34354. * @default true
  34355. */
  34356. this.isNodeVarying = true;
  34357. /**
  34358. * The interpolation type of the varying data.
  34359. *
  34360. * @type {?string}
  34361. * @default null
  34362. */
  34363. this.interpolationType = interpolationType;
  34364. /**
  34365. * The interpolation sampling type of varying data.
  34366. *
  34367. * @type {?string}
  34368. * @default null
  34369. */
  34370. this.interpolationSampling = interpolationSampling;
  34371. }
  34372. }
  34373. /**
  34374. * {@link NodeBuilder} is going to create instances of this class during the build process
  34375. * of nodes. They represent user-defined, native shader code portions that are going to be
  34376. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  34377. * for this purpose.
  34378. */
  34379. class NodeCode {
  34380. /**
  34381. * Constructs a new code node.
  34382. *
  34383. * @param {string} name - The name of the code.
  34384. * @param {string} type - The node type.
  34385. * @param {string} [code=''] - The native shader code.
  34386. */
  34387. constructor( name, type, code = '' ) {
  34388. /**
  34389. * The name of the code.
  34390. *
  34391. * @type {string}
  34392. */
  34393. this.name = name;
  34394. /**
  34395. * The node type.
  34396. *
  34397. * @type {string}
  34398. */
  34399. this.type = type;
  34400. /**
  34401. * The native shader code.
  34402. *
  34403. * @type {string}
  34404. * @default ''
  34405. */
  34406. this.code = code;
  34407. Object.defineProperty( this, 'isNodeCode', { value: true } );
  34408. }
  34409. }
  34410. let _id$6 = 0;
  34411. /**
  34412. * This utility class is used in {@link NodeBuilder} as an internal
  34413. * cache data structure for node data.
  34414. */
  34415. class NodeCache {
  34416. /**
  34417. * Constructs a new node cache.
  34418. *
  34419. * @param {?NodeCache} parent - A reference to a parent cache.
  34420. */
  34421. constructor( parent = null ) {
  34422. /**
  34423. * The id of the cache.
  34424. *
  34425. * @type {number}
  34426. * @readonly
  34427. */
  34428. this.id = _id$6 ++;
  34429. /**
  34430. * A weak map for managing node data.
  34431. *
  34432. * @type {WeakMap<Node, Object>}
  34433. */
  34434. this.nodesData = new WeakMap();
  34435. /**
  34436. * Reference to a parent node cache.
  34437. *
  34438. * @type {?NodeCache}
  34439. * @default null
  34440. */
  34441. this.parent = parent;
  34442. }
  34443. /**
  34444. * Returns the data for the given node.
  34445. *
  34446. * @param {Node} node - The node.
  34447. * @return {?Object} The data for the node.
  34448. */
  34449. getData( node ) {
  34450. let data = this.nodesData.get( node );
  34451. if ( data === undefined && this.parent !== null ) {
  34452. data = this.parent.getData( node );
  34453. }
  34454. return data;
  34455. }
  34456. /**
  34457. * Sets the data for a given node.
  34458. *
  34459. * @param {Node} node - The node.
  34460. * @param {Object} data - The data that should be cached.
  34461. */
  34462. setData( node, data ) {
  34463. this.nodesData.set( node, data );
  34464. }
  34465. }
  34466. class StructType {
  34467. constructor( name, members ) {
  34468. this.name = name;
  34469. this.members = members;
  34470. this.output = false;
  34471. }
  34472. }
  34473. /**
  34474. * Abstract base class for uniforms.
  34475. *
  34476. * @abstract
  34477. * @private
  34478. */
  34479. class Uniform {
  34480. /**
  34481. * Constructs a new uniform.
  34482. *
  34483. * @param {string} name - The uniform's name.
  34484. * @param {any} value - The uniform's value.
  34485. */
  34486. constructor( name, value ) {
  34487. /**
  34488. * The uniform's name.
  34489. *
  34490. * @type {string}
  34491. */
  34492. this.name = name;
  34493. /**
  34494. * The uniform's value.
  34495. *
  34496. * @type {any}
  34497. */
  34498. this.value = value;
  34499. /**
  34500. * Used to build the uniform buffer according to the STD140 layout.
  34501. * Derived uniforms will set this property to a data type specific
  34502. * value.
  34503. *
  34504. * @type {number}
  34505. */
  34506. this.boundary = 0;
  34507. /**
  34508. * The item size. Derived uniforms will set this property to a data
  34509. * type specific value.
  34510. *
  34511. * @type {number}
  34512. */
  34513. this.itemSize = 0;
  34514. /**
  34515. * This property is set by {@link UniformsGroup} and marks
  34516. * the start position in the uniform buffer.
  34517. *
  34518. * @type {number}
  34519. */
  34520. this.offset = 0;
  34521. }
  34522. /**
  34523. * Sets the uniform's value.
  34524. *
  34525. * @param {any} value - The value to set.
  34526. */
  34527. setValue( value ) {
  34528. this.value = value;
  34529. }
  34530. /**
  34531. * Returns the uniform's value.
  34532. *
  34533. * @return {any} The value.
  34534. */
  34535. getValue() {
  34536. return this.value;
  34537. }
  34538. }
  34539. /**
  34540. * Represents a Number uniform.
  34541. *
  34542. * @private
  34543. * @augments Uniform
  34544. */
  34545. class NumberUniform extends Uniform {
  34546. /**
  34547. * Constructs a new Number uniform.
  34548. *
  34549. * @param {string} name - The uniform's name.
  34550. * @param {number} value - The uniform's value.
  34551. */
  34552. constructor( name, value = 0 ) {
  34553. super( name, value );
  34554. /**
  34555. * This flag can be used for type testing.
  34556. *
  34557. * @type {boolean}
  34558. * @readonly
  34559. * @default true
  34560. */
  34561. this.isNumberUniform = true;
  34562. this.boundary = 4;
  34563. this.itemSize = 1;
  34564. }
  34565. }
  34566. /**
  34567. * Represents a Vector2 uniform.
  34568. *
  34569. * @private
  34570. * @augments Uniform
  34571. */
  34572. class Vector2Uniform extends Uniform {
  34573. /**
  34574. * Constructs a new Number uniform.
  34575. *
  34576. * @param {string} name - The uniform's name.
  34577. * @param {Vector2} value - The uniform's value.
  34578. */
  34579. constructor( name, value = new Vector2() ) {
  34580. super( name, value );
  34581. /**
  34582. * This flag can be used for type testing.
  34583. *
  34584. * @type {boolean}
  34585. * @readonly
  34586. * @default true
  34587. */
  34588. this.isVector2Uniform = true;
  34589. this.boundary = 8;
  34590. this.itemSize = 2;
  34591. }
  34592. }
  34593. /**
  34594. * Represents a Vector3 uniform.
  34595. *
  34596. * @private
  34597. * @augments Uniform
  34598. */
  34599. class Vector3Uniform extends Uniform {
  34600. /**
  34601. * Constructs a new Number uniform.
  34602. *
  34603. * @param {string} name - The uniform's name.
  34604. * @param {Vector3} value - The uniform's value.
  34605. */
  34606. constructor( name, value = new Vector3() ) {
  34607. super( name, value );
  34608. /**
  34609. * This flag can be used for type testing.
  34610. *
  34611. * @type {boolean}
  34612. * @readonly
  34613. * @default true
  34614. */
  34615. this.isVector3Uniform = true;
  34616. this.boundary = 16;
  34617. this.itemSize = 3;
  34618. }
  34619. }
  34620. /**
  34621. * Represents a Vector4 uniform.
  34622. *
  34623. * @private
  34624. * @augments Uniform
  34625. */
  34626. class Vector4Uniform extends Uniform {
  34627. /**
  34628. * Constructs a new Number uniform.
  34629. *
  34630. * @param {string} name - The uniform's name.
  34631. * @param {Vector4} value - The uniform's value.
  34632. */
  34633. constructor( name, value = new Vector4() ) {
  34634. super( name, value );
  34635. /**
  34636. * This flag can be used for type testing.
  34637. *
  34638. * @type {boolean}
  34639. * @readonly
  34640. * @default true
  34641. */
  34642. this.isVector4Uniform = true;
  34643. this.boundary = 16;
  34644. this.itemSize = 4;
  34645. }
  34646. }
  34647. /**
  34648. * Represents a Color uniform.
  34649. *
  34650. * @private
  34651. * @augments Uniform
  34652. */
  34653. class ColorUniform extends Uniform {
  34654. /**
  34655. * Constructs a new Number uniform.
  34656. *
  34657. * @param {string} name - The uniform's name.
  34658. * @param {Color} value - The uniform's value.
  34659. */
  34660. constructor( name, value = new Color() ) {
  34661. super( name, value );
  34662. /**
  34663. * This flag can be used for type testing.
  34664. *
  34665. * @type {boolean}
  34666. * @readonly
  34667. * @default true
  34668. */
  34669. this.isColorUniform = true;
  34670. this.boundary = 16;
  34671. this.itemSize = 3;
  34672. }
  34673. }
  34674. /**
  34675. * Represents a Matrix2 uniform.
  34676. *
  34677. * @private
  34678. * @augments Uniform
  34679. */
  34680. class Matrix2Uniform extends Uniform {
  34681. /**
  34682. * Constructs a new Number uniform.
  34683. *
  34684. * @param {string} name - The uniform's name.
  34685. * @param {Matrix2} value - The uniform's value.
  34686. */
  34687. constructor( name, value = new Matrix2() ) {
  34688. super( name, value );
  34689. /**
  34690. * This flag can be used for type testing.
  34691. *
  34692. * @type {boolean}
  34693. * @readonly
  34694. * @default true
  34695. */
  34696. this.isMatrix2Uniform = true;
  34697. this.boundary = 8;
  34698. this.itemSize = 4;
  34699. }
  34700. }
  34701. /**
  34702. * Represents a Matrix3 uniform.
  34703. *
  34704. * @private
  34705. * @augments Uniform
  34706. */
  34707. class Matrix3Uniform extends Uniform {
  34708. /**
  34709. * Constructs a new Number uniform.
  34710. *
  34711. * @param {string} name - The uniform's name.
  34712. * @param {Matrix3} value - The uniform's value.
  34713. */
  34714. constructor( name, value = new Matrix3() ) {
  34715. super( name, value );
  34716. /**
  34717. * This flag can be used for type testing.
  34718. *
  34719. * @type {boolean}
  34720. * @readonly
  34721. * @default true
  34722. */
  34723. this.isMatrix3Uniform = true;
  34724. this.boundary = 48;
  34725. this.itemSize = 12;
  34726. }
  34727. }
  34728. /**
  34729. * Represents a Matrix4 uniform.
  34730. *
  34731. * @private
  34732. * @augments Uniform
  34733. */
  34734. class Matrix4Uniform extends Uniform {
  34735. /**
  34736. * Constructs a new Number uniform.
  34737. *
  34738. * @param {string} name - The uniform's name.
  34739. * @param {Matrix4} value - The uniform's value.
  34740. */
  34741. constructor( name, value = new Matrix4() ) {
  34742. super( name, value );
  34743. /**
  34744. * This flag can be used for type testing.
  34745. *
  34746. * @type {boolean}
  34747. * @readonly
  34748. * @default true
  34749. */
  34750. this.isMatrix4Uniform = true;
  34751. this.boundary = 64;
  34752. this.itemSize = 16;
  34753. }
  34754. }
  34755. /**
  34756. * A special form of Number uniform binding type.
  34757. * It's value is managed by a node object.
  34758. *
  34759. * @private
  34760. * @augments NumberUniform
  34761. */
  34762. class NumberNodeUniform extends NumberUniform {
  34763. /**
  34764. * Constructs a new node-based Number uniform.
  34765. *
  34766. * @param {NodeUniform} nodeUniform - The node uniform.
  34767. */
  34768. constructor( nodeUniform ) {
  34769. super( nodeUniform.name, nodeUniform.value );
  34770. /**
  34771. * The node uniform.
  34772. *
  34773. * @type {NodeUniform}
  34774. */
  34775. this.nodeUniform = nodeUniform;
  34776. }
  34777. /**
  34778. * Overwritten to return the value of the node uniform.
  34779. *
  34780. * @return {number} The value.
  34781. */
  34782. getValue() {
  34783. return this.nodeUniform.value;
  34784. }
  34785. /**
  34786. * Returns the node uniform data type.
  34787. *
  34788. * @return {string} The data type.
  34789. */
  34790. getType() {
  34791. return this.nodeUniform.type;
  34792. }
  34793. }
  34794. /**
  34795. * A special form of Vector2 uniform binding type.
  34796. * It's value is managed by a node object.
  34797. *
  34798. * @private
  34799. * @augments Vector2Uniform
  34800. */
  34801. class Vector2NodeUniform extends Vector2Uniform {
  34802. /**
  34803. * Constructs a new node-based Vector2 uniform.
  34804. *
  34805. * @param {NodeUniform} nodeUniform - The node uniform.
  34806. */
  34807. constructor( nodeUniform ) {
  34808. super( nodeUniform.name, nodeUniform.value );
  34809. /**
  34810. * The node uniform.
  34811. *
  34812. * @type {NodeUniform}
  34813. */
  34814. this.nodeUniform = nodeUniform;
  34815. }
  34816. /**
  34817. * Overwritten to return the value of the node uniform.
  34818. *
  34819. * @return {Vector2} The value.
  34820. */
  34821. getValue() {
  34822. return this.nodeUniform.value;
  34823. }
  34824. /**
  34825. * Returns the node uniform data type.
  34826. *
  34827. * @return {string} The data type.
  34828. */
  34829. getType() {
  34830. return this.nodeUniform.type;
  34831. }
  34832. }
  34833. /**
  34834. * A special form of Vector3 uniform binding type.
  34835. * It's value is managed by a node object.
  34836. *
  34837. * @private
  34838. * @augments Vector3Uniform
  34839. */
  34840. class Vector3NodeUniform extends Vector3Uniform {
  34841. /**
  34842. * Constructs a new node-based Vector3 uniform.
  34843. *
  34844. * @param {NodeUniform} nodeUniform - The node uniform.
  34845. */
  34846. constructor( nodeUniform ) {
  34847. super( nodeUniform.name, nodeUniform.value );
  34848. /**
  34849. * The node uniform.
  34850. *
  34851. * @type {NodeUniform}
  34852. */
  34853. this.nodeUniform = nodeUniform;
  34854. }
  34855. /**
  34856. * Overwritten to return the value of the node uniform.
  34857. *
  34858. * @return {Vector3} The value.
  34859. */
  34860. getValue() {
  34861. return this.nodeUniform.value;
  34862. }
  34863. /**
  34864. * Returns the node uniform data type.
  34865. *
  34866. * @return {string} The data type.
  34867. */
  34868. getType() {
  34869. return this.nodeUniform.type;
  34870. }
  34871. }
  34872. /**
  34873. * A special form of Vector4 uniform binding type.
  34874. * It's value is managed by a node object.
  34875. *
  34876. * @private
  34877. * @augments Vector4Uniform
  34878. */
  34879. class Vector4NodeUniform extends Vector4Uniform {
  34880. /**
  34881. * Constructs a new node-based Vector4 uniform.
  34882. *
  34883. * @param {NodeUniform} nodeUniform - The node uniform.
  34884. */
  34885. constructor( nodeUniform ) {
  34886. super( nodeUniform.name, nodeUniform.value );
  34887. /**
  34888. * The node uniform.
  34889. *
  34890. * @type {NodeUniform}
  34891. */
  34892. this.nodeUniform = nodeUniform;
  34893. }
  34894. /**
  34895. * Overwritten to return the value of the node uniform.
  34896. *
  34897. * @return {Vector4} The value.
  34898. */
  34899. getValue() {
  34900. return this.nodeUniform.value;
  34901. }
  34902. /**
  34903. * Returns the node uniform data type.
  34904. *
  34905. * @return {string} The data type.
  34906. */
  34907. getType() {
  34908. return this.nodeUniform.type;
  34909. }
  34910. }
  34911. /**
  34912. * A special form of Color uniform binding type.
  34913. * It's value is managed by a node object.
  34914. *
  34915. * @private
  34916. * @augments ColorUniform
  34917. */
  34918. class ColorNodeUniform extends ColorUniform {
  34919. /**
  34920. * Constructs a new node-based Color uniform.
  34921. *
  34922. * @param {NodeUniform} nodeUniform - The node uniform.
  34923. */
  34924. constructor( nodeUniform ) {
  34925. super( nodeUniform.name, nodeUniform.value );
  34926. /**
  34927. * The node uniform.
  34928. *
  34929. * @type {NodeUniform}
  34930. */
  34931. this.nodeUniform = nodeUniform;
  34932. }
  34933. /**
  34934. * Overwritten to return the value of the node uniform.
  34935. *
  34936. * @return {Color} The value.
  34937. */
  34938. getValue() {
  34939. return this.nodeUniform.value;
  34940. }
  34941. /**
  34942. * Returns the node uniform data type.
  34943. *
  34944. * @return {string} The data type.
  34945. */
  34946. getType() {
  34947. return this.nodeUniform.type;
  34948. }
  34949. }
  34950. /**
  34951. * A special form of Matrix2 uniform binding type.
  34952. * It's value is managed by a node object.
  34953. *
  34954. * @private
  34955. * @augments Matrix2Uniform
  34956. */
  34957. class Matrix2NodeUniform extends Matrix2Uniform {
  34958. /**
  34959. * Constructs a new node-based Matrix2 uniform.
  34960. *
  34961. * @param {NodeUniform} nodeUniform - The node uniform.
  34962. */
  34963. constructor( nodeUniform ) {
  34964. super( nodeUniform.name, nodeUniform.value );
  34965. /**
  34966. * The node uniform.
  34967. *
  34968. * @type {NodeUniform}
  34969. */
  34970. this.nodeUniform = nodeUniform;
  34971. }
  34972. /**
  34973. * Overwritten to return the value of the node uniform.
  34974. *
  34975. * @return {Matrix2} The value.
  34976. */
  34977. getValue() {
  34978. return this.nodeUniform.value;
  34979. }
  34980. /**
  34981. * Returns the node uniform data type.
  34982. *
  34983. * @return {string} The data type.
  34984. */
  34985. getType() {
  34986. return this.nodeUniform.type;
  34987. }
  34988. }
  34989. /**
  34990. * A special form of Matrix3 uniform binding type.
  34991. * It's value is managed by a node object.
  34992. *
  34993. * @private
  34994. * @augments Matrix3Uniform
  34995. */
  34996. class Matrix3NodeUniform extends Matrix3Uniform {
  34997. /**
  34998. * Constructs a new node-based Matrix3 uniform.
  34999. *
  35000. * @param {NodeUniform} nodeUniform - The node uniform.
  35001. */
  35002. constructor( nodeUniform ) {
  35003. super( nodeUniform.name, nodeUniform.value );
  35004. /**
  35005. * The node uniform.
  35006. *
  35007. * @type {NodeUniform}
  35008. */
  35009. this.nodeUniform = nodeUniform;
  35010. }
  35011. /**
  35012. * Overwritten to return the value of the node uniform.
  35013. *
  35014. * @return {Matrix3} The value.
  35015. */
  35016. getValue() {
  35017. return this.nodeUniform.value;
  35018. }
  35019. /**
  35020. * Returns the node uniform data type.
  35021. *
  35022. * @return {string} The data type.
  35023. */
  35024. getType() {
  35025. return this.nodeUniform.type;
  35026. }
  35027. }
  35028. /**
  35029. * A special form of Matrix4 uniform binding type.
  35030. * It's value is managed by a node object.
  35031. *
  35032. * @private
  35033. * @augments Matrix4Uniform
  35034. */
  35035. class Matrix4NodeUniform extends Matrix4Uniform {
  35036. /**
  35037. * Constructs a new node-based Matrix4 uniform.
  35038. *
  35039. * @param {NodeUniform} nodeUniform - The node uniform.
  35040. */
  35041. constructor( nodeUniform ) {
  35042. super( nodeUniform.name, nodeUniform.value );
  35043. /**
  35044. * The node uniform.
  35045. *
  35046. * @type {NodeUniform}
  35047. */
  35048. this.nodeUniform = nodeUniform;
  35049. }
  35050. /**
  35051. * Overwritten to return the value of the node uniform.
  35052. *
  35053. * @return {Matrix4} The value.
  35054. */
  35055. getValue() {
  35056. return this.nodeUniform.value;
  35057. }
  35058. /**
  35059. * Returns the node uniform data type.
  35060. *
  35061. * @return {string} The data type.
  35062. */
  35063. getType() {
  35064. return this.nodeUniform.type;
  35065. }
  35066. }
  35067. let _id$5 = 0;
  35068. const sharedNodeData = new WeakMap();
  35069. const rendererCache = new WeakMap();
  35070. const typeFromArray = new Map( [
  35071. [ Int8Array, 'int' ],
  35072. [ Int16Array, 'int' ],
  35073. [ Int32Array, 'int' ],
  35074. [ Uint8Array, 'uint' ],
  35075. [ Uint16Array, 'uint' ],
  35076. [ Uint32Array, 'uint' ],
  35077. [ Float32Array, 'float' ]
  35078. ] );
  35079. const toFloat = ( value ) => {
  35080. if ( /e/g.test( value ) ) {
  35081. return String( value ).replace( /\+/g, '' );
  35082. } else {
  35083. value = Number( value );
  35084. return value + ( value % 1 ? '' : '.0' );
  35085. }
  35086. };
  35087. /**
  35088. * Base class for builders which generate a shader program based
  35089. * on a 3D object and its node material definition.
  35090. */
  35091. class NodeBuilder {
  35092. /**
  35093. * Constructs a new node builder.
  35094. *
  35095. * @param {Object3D} object - The 3D object.
  35096. * @param {Renderer} renderer - The current renderer.
  35097. * @param {NodeParser} parser - A reference to a node parser.
  35098. */
  35099. constructor( object, renderer, parser ) {
  35100. /**
  35101. * The 3D object.
  35102. *
  35103. * @type {Object3D}
  35104. */
  35105. this.object = object;
  35106. /**
  35107. * The material of the 3D object.
  35108. *
  35109. * @type {?Material}
  35110. */
  35111. this.material = ( object && object.material ) || null;
  35112. /**
  35113. * The geometry of the 3D object.
  35114. *
  35115. * @type {?BufferGeometry}
  35116. */
  35117. this.geometry = ( object && object.geometry ) || null;
  35118. /**
  35119. * The current renderer.
  35120. *
  35121. * @type {Renderer}
  35122. */
  35123. this.renderer = renderer;
  35124. /**
  35125. * A reference to a node parser.
  35126. *
  35127. * @type {NodeParser}
  35128. */
  35129. this.parser = parser;
  35130. /**
  35131. * The scene the 3D object belongs to.
  35132. *
  35133. * @type {?Scene}
  35134. * @default null
  35135. */
  35136. this.scene = null;
  35137. /**
  35138. * The camera the 3D object is rendered with.
  35139. *
  35140. * @type {?Camera}
  35141. * @default null
  35142. */
  35143. this.camera = null;
  35144. /**
  35145. * A list of all nodes the builder is processing
  35146. * for this 3D object.
  35147. *
  35148. * @type {Array<Node>}
  35149. */
  35150. this.nodes = [];
  35151. /**
  35152. * A list of all sequential nodes.
  35153. *
  35154. * @type {Array<Node>}
  35155. */
  35156. this.sequentialNodes = [];
  35157. /**
  35158. * A list of all nodes which {@link Node#update} method should be executed.
  35159. *
  35160. * @type {Array<Node>}
  35161. */
  35162. this.updateNodes = [];
  35163. /**
  35164. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  35165. *
  35166. * @type {Array<Node>}
  35167. */
  35168. this.updateBeforeNodes = [];
  35169. /**
  35170. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  35171. *
  35172. * @type {Array<Node>}
  35173. */
  35174. this.updateAfterNodes = [];
  35175. /**
  35176. * A dictionary that assigns each node to a unique hash.
  35177. *
  35178. * @type {Object<number,Node>}
  35179. */
  35180. this.hashNodes = {};
  35181. /**
  35182. * A reference to a node material observer.
  35183. *
  35184. * @type {?NodeMaterialObserver}
  35185. * @default null
  35186. */
  35187. this.observer = null;
  35188. /**
  35189. * A reference to the current lights node.
  35190. *
  35191. * @type {?LightsNode}
  35192. * @default null
  35193. */
  35194. this.lightsNode = null;
  35195. /**
  35196. * A reference to the current environment node.
  35197. *
  35198. * @type {?Node}
  35199. * @default null
  35200. */
  35201. this.environmentNode = null;
  35202. /**
  35203. * A reference to the current fog node.
  35204. *
  35205. * @type {?Node}
  35206. * @default null
  35207. */
  35208. this.fogNode = null;
  35209. /**
  35210. * The current clipping context.
  35211. *
  35212. * @type {?ClippingContext}
  35213. */
  35214. this.clippingContext = null;
  35215. /**
  35216. * The generated vertex shader.
  35217. *
  35218. * @type {?string}
  35219. */
  35220. this.vertexShader = null;
  35221. /**
  35222. * The generated fragment shader.
  35223. *
  35224. * @type {?string}
  35225. */
  35226. this.fragmentShader = null;
  35227. /**
  35228. * The generated compute shader.
  35229. *
  35230. * @type {?string}
  35231. */
  35232. this.computeShader = null;
  35233. /**
  35234. * Nodes used in the primary flow of code generation.
  35235. *
  35236. * @type {Object<string,Array<Node>>}
  35237. */
  35238. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  35239. /**
  35240. * Nodes code from `.flowNodes`.
  35241. *
  35242. * @type {Object<string,string>}
  35243. */
  35244. this.flowCode = { vertex: '', fragment: '', compute: '' };
  35245. /**
  35246. * This dictionary holds the node uniforms of the builder.
  35247. * The uniforms are maintained in an array for each shader stage.
  35248. *
  35249. * @type {Object}
  35250. */
  35251. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  35252. /**
  35253. * This dictionary holds the output structs of the builder.
  35254. * The structs are maintained in an array for each shader stage.
  35255. *
  35256. * @type {Object}
  35257. */
  35258. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  35259. /**
  35260. * This dictionary holds the types of the builder.
  35261. *
  35262. * @type {Object}
  35263. */
  35264. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  35265. /**
  35266. * This dictionary holds the bindings for each shader stage.
  35267. *
  35268. * @type {Object}
  35269. */
  35270. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  35271. /**
  35272. * This dictionary maintains the binding indices per bind group.
  35273. *
  35274. * @type {Object}
  35275. */
  35276. this.bindingsIndexes = {};
  35277. /**
  35278. * Reference to the array of bind groups.
  35279. *
  35280. * @type {?Array<BindGroup>}
  35281. */
  35282. this.bindGroups = null;
  35283. /**
  35284. * This array holds the node attributes of this builder
  35285. * created via {@link AttributeNode}.
  35286. *
  35287. * @type {Array<NodeAttribute>}
  35288. */
  35289. this.attributes = [];
  35290. /**
  35291. * This array holds the node attributes of this builder
  35292. * created via {@link BufferAttributeNode}.
  35293. *
  35294. * @type {Array<NodeAttribute>}
  35295. */
  35296. this.bufferAttributes = [];
  35297. /**
  35298. * This array holds the node varyings of this builder.
  35299. *
  35300. * @type {Array<NodeVarying>}
  35301. */
  35302. this.varyings = [];
  35303. /**
  35304. * This dictionary holds the (native) node codes of this builder.
  35305. * The codes are maintained in an array for each shader stage.
  35306. *
  35307. * @type {Object<string,Array<NodeCode>>}
  35308. */
  35309. this.codes = {};
  35310. /**
  35311. * This dictionary holds the node variables of this builder.
  35312. * The variables are maintained in an array for each shader stage.
  35313. * This dictionary is also used to count the number of variables
  35314. * according to their type (const, vars).
  35315. *
  35316. * @type {Object<string,Array<NodeVar>|number>}
  35317. */
  35318. this.vars = {};
  35319. /**
  35320. * This dictionary holds the declarations for each shader stage.
  35321. *
  35322. * @type {Object}
  35323. */
  35324. this.declarations = {};
  35325. /**
  35326. * Current code flow.
  35327. * All code generated in this stack will be stored in `.flow`.
  35328. *
  35329. * @type {{code: string}}
  35330. */
  35331. this.flow = { code: '' };
  35332. /**
  35333. * A chain of nodes.
  35334. * Used to check recursive calls in node-graph.
  35335. *
  35336. * @type {Array<Node>}
  35337. */
  35338. this.chaining = [];
  35339. /**
  35340. * The current stack.
  35341. * This reflects the current process in the code block hierarchy,
  35342. * it is useful to know if the current process is inside a conditional for example.
  35343. *
  35344. * @type {StackNode}
  35345. */
  35346. this.stack = stack();
  35347. /**
  35348. * List of stack nodes.
  35349. * The current stack hierarchy is stored in an array.
  35350. *
  35351. * @type {Array<StackNode>}
  35352. */
  35353. this.stacks = [];
  35354. /**
  35355. * A tab value. Used for shader string generation.
  35356. *
  35357. * @type {string}
  35358. * @default '\t'
  35359. */
  35360. this.tab = '\t';
  35361. /**
  35362. * Reference to the current function node.
  35363. *
  35364. * @type {?FunctionNode}
  35365. * @default null
  35366. */
  35367. this.currentFunctionNode = null;
  35368. /**
  35369. * The builder's context.
  35370. *
  35371. * @type {Object}
  35372. */
  35373. this.context = {
  35374. material: this.material
  35375. };
  35376. /**
  35377. * The builder's cache.
  35378. *
  35379. * @type {NodeCache}
  35380. */
  35381. this.cache = new NodeCache();
  35382. /**
  35383. * Since the {@link NodeBuilder#cache} might be temporarily
  35384. * overwritten by other caches, this member retains the reference
  35385. * to the builder's own cache.
  35386. *
  35387. * @type {NodeCache}
  35388. * @default this.cache
  35389. */
  35390. this.globalCache = this.cache;
  35391. this.flowsData = new WeakMap();
  35392. /**
  35393. * The current shader stage.
  35394. *
  35395. * @type {?('vertex'|'fragment'|'compute'|'any')}
  35396. */
  35397. this.shaderStage = null;
  35398. /**
  35399. * The current build stage.
  35400. *
  35401. * @type {?('setup'|'analyze'|'generate')}
  35402. */
  35403. this.buildStage = null;
  35404. /**
  35405. * The sub-build layers.
  35406. *
  35407. * @type {Array<SubBuildNode>}
  35408. * @default []
  35409. */
  35410. this.subBuildLayers = [];
  35411. /**
  35412. * The active stack nodes.
  35413. *
  35414. * @type {Array<StackNode>}
  35415. */
  35416. this.activeStacks = [];
  35417. /**
  35418. * The current sub-build TSL function(Fn).
  35419. *
  35420. * @type {?string}
  35421. * @default null
  35422. */
  35423. this.subBuildFn = null;
  35424. /**
  35425. * The current TSL function(Fn) call node.
  35426. *
  35427. * @type {?Node}
  35428. * @default null
  35429. */
  35430. this.fnCall = null;
  35431. Object.defineProperty( this, 'id', { value: _id$5 ++ } );
  35432. }
  35433. /**
  35434. * Whether the material is opaque or not.
  35435. *
  35436. * @return {boolean} Whether the material is opaque or not.
  35437. */
  35438. isOpaque() {
  35439. const material = this.material;
  35440. return material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false;
  35441. }
  35442. /**
  35443. * Returns the bind groups of the current renderer.
  35444. *
  35445. * @return {ChainMap} The cache.
  35446. */
  35447. getBindGroupsCache() {
  35448. let bindGroupsCache = rendererCache.get( this.renderer );
  35449. if ( bindGroupsCache === undefined ) {
  35450. bindGroupsCache = new ChainMap();
  35451. rendererCache.set( this.renderer, bindGroupsCache );
  35452. }
  35453. return bindGroupsCache;
  35454. }
  35455. /**
  35456. * Factory method for creating an instance of {@link RenderTarget} with the given
  35457. * dimensions and options.
  35458. *
  35459. * @param {number} width - The width of the render target.
  35460. * @param {number} height - The height of the render target.
  35461. * @param {Object} options - The options of the render target.
  35462. * @return {RenderTarget} The render target.
  35463. */
  35464. createRenderTarget( width, height, options ) {
  35465. return new RenderTarget( width, height, options );
  35466. }
  35467. /**
  35468. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  35469. * dimensions and options.
  35470. *
  35471. * @param {number} size - The size of the cube render target.
  35472. * @param {Object} options - The options of the cube render target.
  35473. * @return {CubeRenderTarget} The cube render target.
  35474. */
  35475. createCubeRenderTarget( size, options ) {
  35476. return new CubeRenderTarget( size, options );
  35477. }
  35478. /**
  35479. * Whether the given node is included in the internal array of nodes or not.
  35480. *
  35481. * @param {Node} node - The node to test.
  35482. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  35483. */
  35484. includes( node ) {
  35485. return this.nodes.includes( node );
  35486. }
  35487. /**
  35488. * Returns the output struct name which is required by
  35489. * {@link OutputStructNode}.
  35490. *
  35491. * @abstract
  35492. * @return {string} The name of the output struct.
  35493. */
  35494. getOutputStructName() {}
  35495. /**
  35496. * Returns a bind group for the given group name and binding.
  35497. *
  35498. * @private
  35499. * @param {string} groupName - The group name.
  35500. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  35501. * @return {BindGroup} The bind group
  35502. */
  35503. _getBindGroup( groupName, bindings ) {
  35504. const bindGroupsCache = this.getBindGroupsCache();
  35505. //
  35506. const bindingsArray = [];
  35507. let sharedGroup = true;
  35508. for ( const binding of bindings ) {
  35509. bindingsArray.push( binding );
  35510. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  35511. }
  35512. //
  35513. let bindGroup;
  35514. if ( sharedGroup ) {
  35515. bindGroup = bindGroupsCache.get( bindingsArray );
  35516. if ( bindGroup === undefined ) {
  35517. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  35518. bindGroupsCache.set( bindingsArray, bindGroup );
  35519. }
  35520. } else {
  35521. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  35522. }
  35523. return bindGroup;
  35524. }
  35525. /**
  35526. * Returns an array of node uniform groups for the given group name and shader stage.
  35527. *
  35528. * @param {string} groupName - The group name.
  35529. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35530. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  35531. */
  35532. getBindGroupArray( groupName, shaderStage ) {
  35533. const bindings = this.bindings[ shaderStage ];
  35534. let bindGroup = bindings[ groupName ];
  35535. if ( bindGroup === undefined ) {
  35536. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  35537. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  35538. }
  35539. bindings[ groupName ] = bindGroup = [];
  35540. }
  35541. return bindGroup;
  35542. }
  35543. /**
  35544. * Returns a list bindings of all shader stages separated by groups.
  35545. *
  35546. * @return {Array<BindGroup>} The list of bindings.
  35547. */
  35548. getBindings() {
  35549. let bindingsGroups = this.bindGroups;
  35550. if ( bindingsGroups === null ) {
  35551. const groups = {};
  35552. const bindings = this.bindings;
  35553. for ( const shaderStage of shaderStages ) {
  35554. for ( const groupName in bindings[ shaderStage ] ) {
  35555. const uniforms = bindings[ shaderStage ][ groupName ];
  35556. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  35557. groupUniforms.push( ...uniforms );
  35558. }
  35559. }
  35560. bindingsGroups = [];
  35561. for ( const groupName in groups ) {
  35562. const group = groups[ groupName ];
  35563. const bindingsGroup = this._getBindGroup( groupName, group );
  35564. bindingsGroups.push( bindingsGroup );
  35565. }
  35566. this.bindGroups = bindingsGroups;
  35567. }
  35568. return bindingsGroups;
  35569. }
  35570. /**
  35571. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  35572. */
  35573. sortBindingGroups() {
  35574. const bindingsGroups = this.getBindings();
  35575. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  35576. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  35577. const bindingGroup = bindingsGroups[ i ];
  35578. this.bindingsIndexes[ bindingGroup.name ].group = i;
  35579. bindingGroup.index = i;
  35580. }
  35581. }
  35582. /**
  35583. * The builder maintains each node in a hash-based dictionary.
  35584. * This method sets the given node (value) with the given hash (key) into this dictionary.
  35585. *
  35586. * @param {Node} node - The node to add.
  35587. * @param {number} hash - The hash of the node.
  35588. */
  35589. setHashNode( node, hash ) {
  35590. this.hashNodes[ hash ] = node;
  35591. }
  35592. /**
  35593. * Adds a node to this builder.
  35594. *
  35595. * @param {Node} node - The node to add.
  35596. */
  35597. addNode( node ) {
  35598. if ( this.nodes.includes( node ) === false ) {
  35599. this.nodes.push( node );
  35600. this.setHashNode( node, node.getHash( this ) );
  35601. }
  35602. }
  35603. /**
  35604. * It is used to add Nodes that will be used as FRAME and RENDER events,
  35605. * and need to follow a certain sequence in the calls to work correctly.
  35606. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  35607. *
  35608. * @param {Node} node - The node to add.
  35609. */
  35610. addSequentialNode( node ) {
  35611. if ( this.sequentialNodes.includes( node ) === false ) {
  35612. this.sequentialNodes.push( node );
  35613. }
  35614. }
  35615. /**
  35616. * Checks the update types of nodes
  35617. */
  35618. buildUpdateNodes() {
  35619. for ( const node of this.nodes ) {
  35620. const updateType = node.getUpdateType();
  35621. if ( updateType !== NodeUpdateType.NONE ) {
  35622. this.updateNodes.push( node );
  35623. }
  35624. }
  35625. for ( const node of this.sequentialNodes ) {
  35626. const updateBeforeType = node.getUpdateBeforeType();
  35627. const updateAfterType = node.getUpdateAfterType();
  35628. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  35629. this.updateBeforeNodes.push( node );
  35630. }
  35631. if ( updateAfterType !== NodeUpdateType.NONE ) {
  35632. this.updateAfterNodes.push( node );
  35633. }
  35634. }
  35635. }
  35636. /**
  35637. * A reference the current node which is the
  35638. * last node in the chain of nodes.
  35639. *
  35640. * @type {Node}
  35641. */
  35642. get currentNode() {
  35643. return this.chaining[ this.chaining.length - 1 ];
  35644. }
  35645. /**
  35646. * Whether the given texture is filtered or not.
  35647. *
  35648. * @param {Texture} texture - The texture to check.
  35649. * @return {boolean} Whether the given texture is filtered or not.
  35650. */
  35651. isFilteredTexture( texture ) {
  35652. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  35653. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  35654. }
  35655. /**
  35656. * Adds the given node to the internal node chain.
  35657. * This is used to check recursive calls in node-graph.
  35658. *
  35659. * @param {Node} node - The node to add.
  35660. */
  35661. addChain( node ) {
  35662. /*
  35663. if ( this.chaining.indexOf( node ) !== - 1 ) {
  35664. warn( 'Recursive node: ', node );
  35665. }
  35666. */
  35667. this.chaining.push( node );
  35668. }
  35669. /**
  35670. * Removes the given node from the internal node chain.
  35671. *
  35672. * @param {Node} node - The node to remove.
  35673. */
  35674. removeChain( node ) {
  35675. const lastChain = this.chaining.pop();
  35676. if ( lastChain !== node ) {
  35677. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  35678. }
  35679. }
  35680. /**
  35681. * Returns the native shader method name for a given generic name. E.g.
  35682. * the method name `textureDimensions` matches the WGSL name but must be
  35683. * resolved to `textureSize` in GLSL.
  35684. *
  35685. * @abstract
  35686. * @param {string} method - The method name to resolve.
  35687. * @return {string} The resolved method name.
  35688. */
  35689. getMethod( method ) {
  35690. return method;
  35691. }
  35692. /**
  35693. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  35694. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  35695. *
  35696. * @abstract
  35697. * @param {string} condSnippet - The condition determining which expression gets resolved.
  35698. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  35699. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  35700. * @return {string} The resolved method name.
  35701. */
  35702. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  35703. return null;
  35704. }
  35705. /**
  35706. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  35707. *
  35708. * @param {number} hash - The hash of the node.
  35709. * @return {Node} The found node.
  35710. */
  35711. getNodeFromHash( hash ) {
  35712. return this.hashNodes[ hash ];
  35713. }
  35714. /**
  35715. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  35716. *
  35717. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  35718. * @param {Node} node - The node to add.
  35719. * @return {Node} The node.
  35720. */
  35721. addFlow( shaderStage, node ) {
  35722. this.flowNodes[ shaderStage ].push( node );
  35723. return node;
  35724. }
  35725. /**
  35726. * Sets builder's context.
  35727. *
  35728. * @param {Object} context - The context to set.
  35729. */
  35730. setContext( context ) {
  35731. this.context = context;
  35732. }
  35733. /**
  35734. * Returns the builder's current context.
  35735. *
  35736. * @return {Object} The builder's current context.
  35737. */
  35738. getContext() {
  35739. return this.context;
  35740. }
  35741. /**
  35742. * Adds context data to the builder's current context.
  35743. *
  35744. * @param {Object} context - The context to add.
  35745. * @return {Object} The previous context.
  35746. */
  35747. addContext( context ) {
  35748. const previousContext = this.getContext();
  35749. this.setContext( { ...this.context, ...context } );
  35750. return previousContext;
  35751. }
  35752. /**
  35753. * Gets a context used in shader construction that can be shared across different materials.
  35754. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  35755. *
  35756. * @return {Object} The builder's current context without material.
  35757. */
  35758. getSharedContext() {
  35759. ({ ...this.context });
  35760. return this.context;
  35761. }
  35762. /**
  35763. * Sets builder's cache.
  35764. *
  35765. * @param {NodeCache} cache - The cache to set.
  35766. */
  35767. setCache( cache ) {
  35768. this.cache = cache;
  35769. }
  35770. /**
  35771. * Returns the builder's current cache.
  35772. *
  35773. * @return {NodeCache} The builder's current cache.
  35774. */
  35775. getCache() {
  35776. return this.cache;
  35777. }
  35778. /**
  35779. * Returns a cache for the given node.
  35780. *
  35781. * @param {Node} node - The node.
  35782. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  35783. * @return {NodeCache} The cache.
  35784. */
  35785. getCacheFromNode( node, parent = true ) {
  35786. const data = this.getDataFromNode( node );
  35787. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  35788. return data.cache;
  35789. }
  35790. /**
  35791. * Whether the requested feature is available or not.
  35792. *
  35793. * @abstract
  35794. * @param {string} name - The requested feature.
  35795. * @return {boolean} Whether the requested feature is supported or not.
  35796. */
  35797. isAvailable( /*name*/ ) {
  35798. return false;
  35799. }
  35800. /**
  35801. * Returns the vertexIndex input variable as a native shader string.
  35802. *
  35803. * @abstract
  35804. * @return {string} The instanceIndex shader string.
  35805. */
  35806. getVertexIndex() {
  35807. warn( 'Abstract function.' );
  35808. }
  35809. /**
  35810. * Contextually returns either the vertex stage instance index builtin
  35811. * or the linearized index of an compute invocation within a grid of workgroups.
  35812. *
  35813. * @abstract
  35814. * @return {string} The instanceIndex shader string.
  35815. */
  35816. getInstanceIndex() {
  35817. warn( 'Abstract function.' );
  35818. }
  35819. /**
  35820. * Returns the drawIndex input variable as a native shader string.
  35821. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  35822. *
  35823. * @abstract
  35824. * @return {?string} The drawIndex shader string.
  35825. */
  35826. getDrawIndex() {
  35827. warn( 'Abstract function.' );
  35828. }
  35829. /**
  35830. * Returns the frontFacing input variable as a native shader string.
  35831. *
  35832. * @abstract
  35833. * @return {string} The frontFacing shader string.
  35834. */
  35835. getFrontFacing() {
  35836. warn( 'Abstract function.' );
  35837. }
  35838. /**
  35839. * Returns the fragCoord input variable as a native shader string.
  35840. *
  35841. * @abstract
  35842. * @return {string} The fragCoord shader string.
  35843. */
  35844. getFragCoord() {
  35845. warn( 'Abstract function.' );
  35846. }
  35847. /**
  35848. * Whether to flip texture data along its vertical axis or not. WebGL needs
  35849. * this method evaluate to `true`, WebGPU to `false`.
  35850. *
  35851. * @abstract
  35852. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  35853. */
  35854. isFlipY() {
  35855. return false;
  35856. }
  35857. /**
  35858. * Calling this method increases the usage count for the given node by one.
  35859. *
  35860. * @param {Node} node - The node to increase the usage count for.
  35861. * @return {number} The updated usage count.
  35862. */
  35863. increaseUsage( node ) {
  35864. const nodeData = this.getDataFromNode( node );
  35865. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  35866. return nodeData.usageCount;
  35867. }
  35868. /**
  35869. * Generates a texture sample shader string for the given texture data.
  35870. *
  35871. * @abstract
  35872. * @param {Texture} texture - The texture.
  35873. * @param {string} textureProperty - The texture property name.
  35874. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  35875. * @return {string} The generated shader string.
  35876. */
  35877. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  35878. warn( 'Abstract function.' );
  35879. }
  35880. /**
  35881. * Generates a texture LOD shader string for the given texture data.
  35882. *
  35883. * @abstract
  35884. * @param {Texture} texture - The texture.
  35885. * @param {string} textureProperty - The texture property name.
  35886. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  35887. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  35888. * @param {string} levelSnippet - Snippet defining the mip level.
  35889. * @return {string} The generated shader string.
  35890. */
  35891. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  35892. warn( 'Abstract function.' );
  35893. }
  35894. /**
  35895. * Generates the array declaration string.
  35896. *
  35897. * @param {string} type - The type.
  35898. * @param {?number} [count] - The count.
  35899. * @return {string} The generated value as a shader string.
  35900. */
  35901. generateArrayDeclaration( type, count ) {
  35902. return this.getType( type ) + '[ ' + count + ' ]';
  35903. }
  35904. /**
  35905. * Generates the array shader string for the given type and value.
  35906. *
  35907. * @param {string} type - The type.
  35908. * @param {?number} [count] - The count.
  35909. * @param {?Array<Node>} [values=null] - The default values.
  35910. * @return {string} The generated value as a shader string.
  35911. */
  35912. generateArray( type, count, values = null ) {
  35913. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  35914. for ( let i = 0; i < count; i ++ ) {
  35915. const value = values ? values[ i ] : null;
  35916. if ( value !== null ) {
  35917. snippet += value.build( this, type );
  35918. } else {
  35919. snippet += this.generateConst( type );
  35920. }
  35921. if ( i < count - 1 ) snippet += ', ';
  35922. }
  35923. snippet += ' )';
  35924. return snippet;
  35925. }
  35926. /**
  35927. * Generates the struct shader string.
  35928. *
  35929. * @param {string} type - The type.
  35930. * @param {Array<Object>} [membersLayout] - The count.
  35931. * @param {?Array<Node>} [values=null] - The default values.
  35932. * @return {string} The generated value as a shader string.
  35933. */
  35934. generateStruct( type, membersLayout, values = null ) {
  35935. const snippets = [];
  35936. for ( const member of membersLayout ) {
  35937. const { name, type } = member;
  35938. if ( values && values[ name ] && values[ name ].isNode ) {
  35939. snippets.push( values[ name ].build( this, type ) );
  35940. } else {
  35941. snippets.push( this.generateConst( type ) );
  35942. }
  35943. }
  35944. return type + '( ' + snippets.join( ', ' ) + ' )';
  35945. }
  35946. /**
  35947. * Generates the shader string for the given type and value.
  35948. *
  35949. * @param {string} type - The type.
  35950. * @param {?any} [value=null] - The value.
  35951. * @return {string} The generated value as a shader string.
  35952. */
  35953. generateConst( type, value = null ) {
  35954. if ( value === null ) {
  35955. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  35956. else if ( type === 'bool' ) value = false;
  35957. else if ( type === 'color' ) value = new Color();
  35958. else if ( type === 'vec2' || type === 'uvec2' || type === 'ivec2' ) value = new Vector2();
  35959. else if ( type === 'vec3' || type === 'uvec3' || type === 'ivec3' ) value = new Vector3();
  35960. else if ( type === 'vec4' || type === 'uvec4' || type === 'ivec4' ) value = new Vector4();
  35961. }
  35962. if ( type === 'float' ) return toFloat( value );
  35963. if ( type === 'int' ) return `${ Math.round( value ) }`;
  35964. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  35965. if ( type === 'bool' ) return value ? 'true' : 'false';
  35966. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  35967. const typeLength = this.getTypeLength( type );
  35968. const componentType = this.getComponentType( type );
  35969. const generateConst = value => this.generateConst( componentType, value );
  35970. if ( typeLength === 2 ) {
  35971. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  35972. } else if ( typeLength === 3 ) {
  35973. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  35974. } else if ( typeLength === 4 && type !== 'mat2' ) {
  35975. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  35976. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  35977. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  35978. } else if ( typeLength > 4 ) {
  35979. return `${ this.getType( type ) }()`;
  35980. }
  35981. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  35982. }
  35983. /**
  35984. * It might be necessary to convert certain data types to different ones
  35985. * so this method can be used to hide the conversion.
  35986. *
  35987. * @param {string} type - The type.
  35988. * @return {string} The updated type.
  35989. */
  35990. getType( type ) {
  35991. if ( type === 'color' ) return 'vec3';
  35992. return type;
  35993. }
  35994. /**
  35995. * Whether the given attribute name is defined in the geometry or not.
  35996. *
  35997. * @param {string} name - The attribute name.
  35998. * @return {boolean} Whether the given attribute name is defined in the geometry.
  35999. */
  36000. hasGeometryAttribute( name ) {
  36001. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  36002. }
  36003. /**
  36004. * Returns a node attribute for the given name and type.
  36005. *
  36006. * @param {string} name - The attribute's name.
  36007. * @param {string} type - The attribute's type.
  36008. * @return {NodeAttribute} The node attribute.
  36009. */
  36010. getAttribute( name, type ) {
  36011. const attributes = this.attributes;
  36012. // find attribute
  36013. for ( const attribute of attributes ) {
  36014. if ( attribute.name === name ) {
  36015. return attribute;
  36016. }
  36017. }
  36018. // create a new if no exist
  36019. const attribute = new NodeAttribute( name, type );
  36020. this.registerDeclaration( attribute );
  36021. attributes.push( attribute );
  36022. return attribute;
  36023. }
  36024. /**
  36025. * Returns for the given node and shader stage the property name for the shader.
  36026. *
  36027. * @param {Node} node - The node.
  36028. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36029. * @return {string} The property name.
  36030. */
  36031. getPropertyName( node/*, shaderStage*/ ) {
  36032. return node.name;
  36033. }
  36034. /**
  36035. * Whether the given type is a vector type or not.
  36036. *
  36037. * @param {string} type - The type to check.
  36038. * @return {boolean} Whether the given type is a vector type or not.
  36039. */
  36040. isVector( type ) {
  36041. return /vec\d/.test( type );
  36042. }
  36043. /**
  36044. * Whether the given type is a matrix type or not.
  36045. *
  36046. * @param {string} type - The type to check.
  36047. * @return {boolean} Whether the given type is a matrix type or not.
  36048. */
  36049. isMatrix( type ) {
  36050. return /mat\d/.test( type );
  36051. }
  36052. /**
  36053. * Whether the given type is a reference type or not.
  36054. *
  36055. * @param {string} type - The type to check.
  36056. * @return {boolean} Whether the given type is a reference type or not.
  36057. */
  36058. isReference( type ) {
  36059. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  36060. }
  36061. /**
  36062. * Checks if the given texture requires a manual conversion to the working color space.
  36063. *
  36064. * @abstract
  36065. * @param {Texture} texture - The texture to check.
  36066. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  36067. */
  36068. needsToWorkingColorSpace( /*texture*/ ) {
  36069. return false;
  36070. }
  36071. /**
  36072. * Returns the component type of a given texture.
  36073. *
  36074. * @param {Texture} texture - The texture.
  36075. * @return {string} The component type.
  36076. */
  36077. getComponentTypeFromTexture( texture ) {
  36078. const type = texture.type;
  36079. if ( texture.isDataTexture ) {
  36080. if ( type === IntType ) return 'int';
  36081. if ( type === UnsignedIntType ) return 'uint';
  36082. }
  36083. return 'float';
  36084. }
  36085. /**
  36086. * Returns the element type for a given type.
  36087. *
  36088. * @param {string} type - The type.
  36089. * @return {string} The element type.
  36090. */
  36091. getElementType( type ) {
  36092. if ( type === 'mat2' ) return 'vec2';
  36093. if ( type === 'mat3' ) return 'vec3';
  36094. if ( type === 'mat4' ) return 'vec4';
  36095. return this.getComponentType( type );
  36096. }
  36097. /**
  36098. * Returns the component type for a given type.
  36099. *
  36100. * @param {string} type - The type.
  36101. * @return {string} The component type.
  36102. */
  36103. getComponentType( type ) {
  36104. type = this.getVectorType( type );
  36105. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  36106. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  36107. if ( componentType === null ) return null;
  36108. if ( componentType[ 1 ] === 'b' ) return 'bool';
  36109. if ( componentType[ 1 ] === 'i' ) return 'int';
  36110. if ( componentType[ 1 ] === 'u' ) return 'uint';
  36111. return 'float';
  36112. }
  36113. /**
  36114. * Returns the vector type for a given type.
  36115. *
  36116. * @param {string} type - The type.
  36117. * @return {string} The vector type.
  36118. */
  36119. getVectorType( type ) {
  36120. if ( type === 'color' ) return 'vec3';
  36121. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  36122. return type;
  36123. }
  36124. /**
  36125. * Returns the data type for the given the length and component type.
  36126. *
  36127. * @param {number} length - The length.
  36128. * @param {string} [componentType='float'] - The component type.
  36129. * @return {string} The type.
  36130. */
  36131. getTypeFromLength( length, componentType = 'float' ) {
  36132. if ( length === 1 ) return componentType;
  36133. let baseType = getTypeFromLength( length );
  36134. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  36135. // fix edge case for mat2x2 being same size as vec4
  36136. if ( /mat2/.test( componentType ) === true ) {
  36137. baseType = baseType.replace( 'vec', 'mat' );
  36138. }
  36139. return prefix + baseType;
  36140. }
  36141. /**
  36142. * Returns the type for a given typed array.
  36143. *
  36144. * @param {TypedArray} array - The typed array.
  36145. * @return {string} The type.
  36146. */
  36147. getTypeFromArray( array ) {
  36148. return typeFromArray.get( array.constructor );
  36149. }
  36150. /**
  36151. * Returns the type is an integer type.
  36152. *
  36153. * @param {string} type - The type.
  36154. * @return {boolean} Whether the type is an integer type or not.
  36155. */
  36156. isInteger( type ) {
  36157. return /int|uint|(i|u)vec/.test( type );
  36158. }
  36159. /**
  36160. * Returns the type for a given buffer attribute.
  36161. *
  36162. * @param {BufferAttribute} attribute - The buffer attribute.
  36163. * @return {string} The type.
  36164. */
  36165. getTypeFromAttribute( attribute ) {
  36166. let dataAttribute = attribute;
  36167. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  36168. const array = dataAttribute.array;
  36169. const itemSize = attribute.itemSize;
  36170. const normalized = attribute.normalized;
  36171. let arrayType;
  36172. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  36173. arrayType = this.getTypeFromArray( array );
  36174. }
  36175. return this.getTypeFromLength( itemSize, arrayType );
  36176. }
  36177. /**
  36178. * Returns the length for the given data type.
  36179. *
  36180. * @param {string} type - The data type.
  36181. * @return {number} The length.
  36182. */
  36183. getTypeLength( type ) {
  36184. const vecType = this.getVectorType( type );
  36185. const vecNum = /vec([2-4])/.exec( vecType );
  36186. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  36187. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  36188. if ( /mat2/.test( type ) === true ) return 4;
  36189. if ( /mat3/.test( type ) === true ) return 9;
  36190. if ( /mat4/.test( type ) === true ) return 16;
  36191. return 0;
  36192. }
  36193. /**
  36194. * Returns the vector type for a given matrix type.
  36195. *
  36196. * @param {string} type - The matrix type.
  36197. * @return {string} The vector type.
  36198. */
  36199. getVectorFromMatrix( type ) {
  36200. return type.replace( 'mat', 'vec' );
  36201. }
  36202. /**
  36203. * For a given type this method changes the component type to the
  36204. * given value. E.g. `vec4` should be changed to the new component type
  36205. * `uint` which results in `uvec4`.
  36206. *
  36207. * @param {string} type - The type.
  36208. * @param {string} newComponentType - The new component type.
  36209. * @return {string} The new type.
  36210. */
  36211. changeComponentType( type, newComponentType ) {
  36212. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  36213. }
  36214. /**
  36215. * Returns the integer type pendant for the given type.
  36216. *
  36217. * @param {string} type - The type.
  36218. * @return {string} The integer type.
  36219. */
  36220. getIntegerType( type ) {
  36221. const componentType = this.getComponentType( type );
  36222. if ( componentType === 'int' || componentType === 'uint' ) return type;
  36223. return this.changeComponentType( type, 'int' );
  36224. }
  36225. /**
  36226. * Adds an active stack to the internal stack.
  36227. *
  36228. * @param {StackNode} stack - The stack node to add.
  36229. */
  36230. setActiveStack( stack ) {
  36231. this.activeStacks.push( stack );
  36232. }
  36233. /**
  36234. * Removes the active stack from the internal stack.
  36235. *
  36236. * @param {StackNode} stack - The stack node to remove.
  36237. */
  36238. removeActiveStack( stack ) {
  36239. if ( this.activeStacks[ this.activeStacks.length - 1 ] === stack ) {
  36240. this.activeStacks.pop();
  36241. } else {
  36242. throw new Error( 'NodeBuilder: Invalid active stack removal.' );
  36243. }
  36244. }
  36245. /**
  36246. * Returns the active stack.
  36247. *
  36248. * @return {StackNode} The active stack.
  36249. */
  36250. getActiveStack() {
  36251. return this.activeStacks[ this.activeStacks.length - 1 ];
  36252. }
  36253. /**
  36254. * Returns the base stack.
  36255. *
  36256. * @return {StackNode} The base stack.
  36257. */
  36258. getBaseStack() {
  36259. return this.activeStacks[ 0 ];
  36260. }
  36261. /**
  36262. * Adds a stack node to the internal stack.
  36263. *
  36264. * @return {StackNode} The added stack node.
  36265. */
  36266. addStack() {
  36267. this.stack = stack( this.stack );
  36268. const previousStack = getCurrentStack();
  36269. this.stacks.push( previousStack );
  36270. setCurrentStack( this.stack );
  36271. return this.stack;
  36272. }
  36273. /**
  36274. * Removes the last stack node from the internal stack.
  36275. *
  36276. * @return {StackNode} The removed stack node.
  36277. */
  36278. removeStack() {
  36279. const lastStack = this.stack;
  36280. for ( const node of lastStack.nodes ) {
  36281. const nodeData = this.getDataFromNode( node );
  36282. nodeData.stack = lastStack;
  36283. }
  36284. this.stack = lastStack.parent;
  36285. setCurrentStack( this.stacks.pop() );
  36286. return lastStack;
  36287. }
  36288. /**
  36289. * The builder maintains (cached) data for each node during the building process. This method
  36290. * can be used to get these data for a specific shader stage and cache.
  36291. *
  36292. * @param {Node} node - The node to get the data for.
  36293. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36294. * @param {?NodeCache} cache - An optional cache.
  36295. * @return {Object} The node data.
  36296. */
  36297. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  36298. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  36299. let nodeData = cache.getData( node );
  36300. if ( nodeData === undefined ) {
  36301. nodeData = {};
  36302. cache.setData( node, nodeData );
  36303. }
  36304. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  36305. //
  36306. let data = nodeData[ shaderStage ];
  36307. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  36308. const subBuild = this.getClosestSubBuild( subBuilds );
  36309. if ( subBuild ) {
  36310. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  36311. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  36312. data.subBuilds = subBuilds;
  36313. }
  36314. return data;
  36315. }
  36316. /**
  36317. * Returns the properties for the given node and shader stage.
  36318. *
  36319. * Properties are typically used within a build stage to reference a node's
  36320. * child node or nodes manually assigned to the properties in a separate build stage.
  36321. * A typical usage pattern for defining nodes manually would be assigning dependency nodes
  36322. * to the current node's properties in the setup stage and building those properties in the generate stage.
  36323. *
  36324. * @param {Node} node - The node to get the properties for.
  36325. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  36326. * @return {Object} The node properties.
  36327. */
  36328. getNodeProperties( node, shaderStage = 'any' ) {
  36329. const nodeData = this.getDataFromNode( node, shaderStage );
  36330. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  36331. }
  36332. /**
  36333. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  36334. *
  36335. * @param {BufferAttributeNode} node - The buffer attribute node.
  36336. * @param {string} type - The node type.
  36337. * @return {NodeAttribute} The node attribute.
  36338. */
  36339. getBufferAttributeFromNode( node, type ) {
  36340. const nodeData = this.getDataFromNode( node, 'vertex' );
  36341. let bufferAttribute = nodeData.bufferAttribute;
  36342. if ( bufferAttribute === undefined ) {
  36343. const index = this.uniforms.index ++;
  36344. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  36345. this.bufferAttributes.push( bufferAttribute );
  36346. nodeData.bufferAttribute = bufferAttribute;
  36347. }
  36348. return bufferAttribute;
  36349. }
  36350. /**
  36351. * Returns an instance of {@link StructType} for the given struct name and shader stage
  36352. * or null if not found.
  36353. *
  36354. * @param {string} name - The name of the struct.
  36355. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36356. * @return {?StructType} The struct type or null if not found.
  36357. */
  36358. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  36359. return this.types[ shaderStage ][ name ] || null;
  36360. }
  36361. /**
  36362. * Returns an instance of {@link StructType} for the given output struct node.
  36363. *
  36364. * @param {OutputStructNode} node - The output struct node.
  36365. * @param {Array<Object>} membersLayout - The output struct types.
  36366. * @param {?string} [name=null] - The name of the struct.
  36367. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36368. * @return {StructType} The struct type attribute.
  36369. */
  36370. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  36371. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36372. let structType = nodeData.structType;
  36373. if ( structType === undefined ) {
  36374. const index = this.structs.index ++;
  36375. if ( name === null ) name = 'StructType' + index;
  36376. structType = new StructType( name, membersLayout );
  36377. this.structs[ shaderStage ].push( structType );
  36378. this.types[ shaderStage ][ name ] = node;
  36379. nodeData.structType = structType;
  36380. }
  36381. return structType;
  36382. }
  36383. /**
  36384. * Returns an instance of {@link StructType} for the given output struct node.
  36385. *
  36386. * @param {OutputStructNode} node - The output struct node.
  36387. * @param {Array<Object>} membersLayout - The output struct types.
  36388. * @return {StructType} The struct type attribute.
  36389. */
  36390. getOutputStructTypeFromNode( node, membersLayout ) {
  36391. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  36392. structType.output = true;
  36393. return structType;
  36394. }
  36395. /**
  36396. * Returns an instance of {@link NodeUniform} for the given uniform node.
  36397. *
  36398. * @param {UniformNode} node - The uniform node.
  36399. * @param {string} type - The uniform type.
  36400. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36401. * @param {?string} name - The name of the uniform.
  36402. * @return {NodeUniform} The node uniform.
  36403. */
  36404. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  36405. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36406. let nodeUniform = nodeData.uniform;
  36407. if ( nodeUniform === undefined ) {
  36408. const index = this.uniforms.index ++;
  36409. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  36410. this.uniforms[ shaderStage ].push( nodeUniform );
  36411. this.registerDeclaration( nodeUniform );
  36412. nodeData.uniform = nodeUniform;
  36413. }
  36414. return nodeUniform;
  36415. }
  36416. /**
  36417. * Returns an instance of {@link NodeVar} for the given variable node.
  36418. *
  36419. * @param {VarNode} node - The variable node.
  36420. * @param {?string} name - The variable's name.
  36421. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  36422. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36423. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  36424. *
  36425. * @return {NodeVar} The node variable.
  36426. */
  36427. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  36428. const nodeData = this.getDataFromNode( node, shaderStage );
  36429. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  36430. let nodeVar = nodeData[ subBuildVariable ];
  36431. if ( nodeVar === undefined ) {
  36432. const idNS = readOnly ? '_const' : '_var';
  36433. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  36434. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  36435. if ( name === null ) {
  36436. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  36437. this.vars[ idNS ] ++;
  36438. }
  36439. //
  36440. if ( subBuildVariable !== 'variable' ) {
  36441. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  36442. }
  36443. //
  36444. const count = node.getArrayCount( this );
  36445. nodeVar = new NodeVar( name, type, readOnly, count );
  36446. if ( ! readOnly ) {
  36447. vars.push( nodeVar );
  36448. }
  36449. this.registerDeclaration( nodeVar );
  36450. nodeData[ subBuildVariable ] = nodeVar;
  36451. }
  36452. return nodeVar;
  36453. }
  36454. /**
  36455. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  36456. *
  36457. * @param {Node} node - The varying node.
  36458. * @return {boolean} Returns true if deterministic.
  36459. */
  36460. isDeterministic( node ) {
  36461. if ( node.isMathNode ) {
  36462. return this.isDeterministic( node.aNode ) &&
  36463. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  36464. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  36465. } else if ( node.isOperatorNode ) {
  36466. return this.isDeterministic( node.aNode ) &&
  36467. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  36468. } else if ( node.isArrayNode ) {
  36469. if ( node.values !== null ) {
  36470. for ( const n of node.values ) {
  36471. if ( ! this.isDeterministic( n ) ) {
  36472. return false;
  36473. }
  36474. }
  36475. }
  36476. return true;
  36477. } else if ( node.isConstNode ) {
  36478. return true;
  36479. }
  36480. return false;
  36481. }
  36482. /**
  36483. * Returns an instance of {@link NodeVarying} for the given varying node.
  36484. *
  36485. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  36486. * @param {?string} name - The varying's name.
  36487. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  36488. * @param {?string} interpolationType - The interpolation type of the varying.
  36489. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  36490. * @return {NodeVar} The node varying.
  36491. */
  36492. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  36493. const nodeData = this.getDataFromNode( node, 'any' );
  36494. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  36495. let nodeVarying = nodeData[ subBuildVarying ];
  36496. if ( nodeVarying === undefined ) {
  36497. const varyings = this.varyings;
  36498. const index = varyings.length;
  36499. if ( name === null ) name = 'nodeVarying' + index;
  36500. //
  36501. if ( subBuildVarying !== 'varying' ) {
  36502. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  36503. }
  36504. //
  36505. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  36506. varyings.push( nodeVarying );
  36507. this.registerDeclaration( nodeVarying );
  36508. nodeData[ subBuildVarying ] = nodeVarying;
  36509. }
  36510. return nodeVarying;
  36511. }
  36512. /**
  36513. * Registers a node declaration in the current shader stage.
  36514. *
  36515. * @param {Object} node - The node to be registered.
  36516. */
  36517. registerDeclaration( node ) {
  36518. const shaderStage = this.shaderStage;
  36519. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  36520. const property = this.getPropertyName( node );
  36521. let index = 1;
  36522. let name = property;
  36523. // Automatically renames the property if the name is already in use.
  36524. while ( declarations[ name ] !== undefined ) {
  36525. name = property + '_' + index ++;
  36526. }
  36527. if ( index > 1 ) {
  36528. node.name = name;
  36529. warn( `TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  36530. }
  36531. declarations[ name ] = node;
  36532. }
  36533. /**
  36534. * Returns an instance of {@link NodeCode} for the given code node.
  36535. *
  36536. * @param {CodeNode} node - The code node.
  36537. * @param {string} type - The node type.
  36538. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36539. * @return {NodeCode} The node code.
  36540. */
  36541. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  36542. const nodeData = this.getDataFromNode( node );
  36543. let nodeCode = nodeData.code;
  36544. if ( nodeCode === undefined ) {
  36545. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  36546. const index = codes.length;
  36547. nodeCode = new NodeCode( 'nodeCode' + index, type );
  36548. codes.push( nodeCode );
  36549. nodeData.code = nodeCode;
  36550. }
  36551. return nodeCode;
  36552. }
  36553. /**
  36554. * Adds a code flow based on the code-block hierarchy.
  36555. * This is used so that code-blocks like If,Else create their variables locally if the Node
  36556. * is only used inside one of these conditionals in the current shader stage.
  36557. *
  36558. * @param {Node} node - The node to add.
  36559. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  36560. */
  36561. addFlowCodeHierarchy( node, nodeBlock ) {
  36562. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  36563. let needsFlowCode = true;
  36564. let nodeBlockHierarchy = nodeBlock;
  36565. while ( nodeBlockHierarchy ) {
  36566. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  36567. needsFlowCode = false;
  36568. break;
  36569. }
  36570. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  36571. }
  36572. if ( needsFlowCode ) {
  36573. for ( const flowCode of flowCodes ) {
  36574. this.addLineFlowCode( flowCode );
  36575. }
  36576. }
  36577. }
  36578. /**
  36579. * Add a inline-code to the current flow code-block.
  36580. *
  36581. * @param {Node} node - The node to add.
  36582. * @param {string} code - The code to add.
  36583. * @param {Node} nodeBlock - Current ConditionalNode
  36584. */
  36585. addLineFlowCodeBlock( node, code, nodeBlock ) {
  36586. const nodeData = this.getDataFromNode( node );
  36587. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  36588. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  36589. flowCodes.push( code );
  36590. codeBlock.set( nodeBlock, true );
  36591. }
  36592. /**
  36593. * Add a inline-code to the current flow.
  36594. *
  36595. * @param {string} code - The code to add.
  36596. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  36597. * @return {NodeBuilder} A reference to this node builder.
  36598. */
  36599. addLineFlowCode( code, node = null ) {
  36600. if ( code === '' ) return this;
  36601. if ( node !== null && this.context.nodeBlock ) {
  36602. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  36603. }
  36604. code = this.tab + code;
  36605. if ( ! /;\s*$/.test( code ) ) {
  36606. code = code + ';\n';
  36607. }
  36608. this.flow.code += code;
  36609. return this;
  36610. }
  36611. /**
  36612. * Adds a code to the current code flow.
  36613. *
  36614. * @param {string} code - Shader code.
  36615. * @return {NodeBuilder} A reference to this node builder.
  36616. */
  36617. addFlowCode( code ) {
  36618. this.flow.code += code;
  36619. return this;
  36620. }
  36621. /**
  36622. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  36623. * Typically used in codes with If,Else.
  36624. *
  36625. * @return {NodeBuilder} A reference to this node builder.
  36626. */
  36627. addFlowTab() {
  36628. this.tab += '\t';
  36629. return this;
  36630. }
  36631. /**
  36632. * Removes a tab.
  36633. *
  36634. * @return {NodeBuilder} A reference to this node builder.
  36635. */
  36636. removeFlowTab() {
  36637. this.tab = this.tab.slice( 0, -1 );
  36638. return this;
  36639. }
  36640. /**
  36641. * Gets the current flow data based on a Node.
  36642. *
  36643. * @param {Node} node - Node that the flow was started.
  36644. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36645. * @return {Object} The flow data.
  36646. */
  36647. getFlowData( node/*, shaderStage*/ ) {
  36648. return this.flowsData.get( node );
  36649. }
  36650. /**
  36651. * Executes the node flow based on a root node to generate the final shader code.
  36652. *
  36653. * @param {Node} node - The node to execute.
  36654. * @return {Object} The code flow.
  36655. */
  36656. flowNode( node ) {
  36657. const output = node.getNodeType( this );
  36658. const flowData = this.flowChildNode( node, output );
  36659. this.flowsData.set( node, flowData );
  36660. return flowData;
  36661. }
  36662. /**
  36663. * Includes a node in the current function node.
  36664. *
  36665. * @param {Node} node - The node to include.
  36666. * @returns {void}
  36667. */
  36668. addInclude( node ) {
  36669. if ( this.currentFunctionNode !== null ) {
  36670. this.currentFunctionNode.includes.push( node );
  36671. }
  36672. }
  36673. /**
  36674. * Returns the native shader operator name for a given generic name.
  36675. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  36676. *
  36677. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  36678. * @return {FunctionNode} The build function node.
  36679. */
  36680. buildFunctionNode( shaderNode ) {
  36681. const fn = new FunctionNode();
  36682. const previous = this.currentFunctionNode;
  36683. this.currentFunctionNode = fn;
  36684. fn.code = this.buildFunctionCode( shaderNode );
  36685. this.currentFunctionNode = previous;
  36686. return fn;
  36687. }
  36688. /**
  36689. * Generates a code flow based on a TSL function: Fn().
  36690. *
  36691. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  36692. * @return {Object}
  36693. */
  36694. flowShaderNode( shaderNode ) {
  36695. const layout = shaderNode.layout;
  36696. const inputs = {
  36697. [ Symbol.iterator ]() {
  36698. let index = 0;
  36699. const values = Object.values( this );
  36700. return {
  36701. next: () => ( {
  36702. value: values[ index ],
  36703. done: index ++ >= values.length
  36704. } )
  36705. };
  36706. }
  36707. };
  36708. for ( const input of layout.inputs ) {
  36709. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  36710. }
  36711. //
  36712. shaderNode.layout = null;
  36713. const callNode = shaderNode.call( inputs );
  36714. const flowData = this.flowStagesNode( callNode, layout.type );
  36715. shaderNode.layout = layout;
  36716. return flowData;
  36717. }
  36718. /**
  36719. * Executes the node in a specific build stage.
  36720. *
  36721. * This function can be used to arbitrarily execute the specified build stage
  36722. * outside of the standard build process. For instance, if a node's type depends
  36723. * on properties created by the 'setup' stage, then flowBuildStage(node, 'setup')
  36724. * can be used to execute the setup build stage and access its generated nodes
  36725. * before the standard build process begins.
  36726. *
  36727. * @param {Node} node - The node to execute.
  36728. * @param {string} buildStage - The build stage to execute the node in.
  36729. * @param {?(Node|string)} [output=null] - Expected output type. For example 'vec3'.
  36730. * @return {?(Node|string)} The result of the node build.
  36731. */
  36732. flowBuildStage( node, buildStage, output = null ) {
  36733. const previousBuildStage = this.getBuildStage();
  36734. this.setBuildStage( buildStage );
  36735. const result = node.build( this, output );
  36736. this.setBuildStage( previousBuildStage );
  36737. return result;
  36738. }
  36739. /**
  36740. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  36741. *
  36742. * @param {Node} node - The node to execute.
  36743. * @param {?string} output - Expected output type. For example 'vec3'.
  36744. * @return {Object}
  36745. */
  36746. flowStagesNode( node, output = null ) {
  36747. const previousFlow = this.flow;
  36748. const previousVars = this.vars;
  36749. const previousDeclarations = this.declarations;
  36750. const previousCache = this.cache;
  36751. const previousBuildStage = this.buildStage;
  36752. const previousStack = this.stack;
  36753. const flow = {
  36754. code: ''
  36755. };
  36756. this.flow = flow;
  36757. this.vars = {};
  36758. this.declarations = {};
  36759. this.cache = new NodeCache();
  36760. this.stack = stack();
  36761. for ( const buildStage of defaultBuildStages ) {
  36762. this.setBuildStage( buildStage );
  36763. flow.result = node.build( this, output );
  36764. }
  36765. flow.vars = this.getVars( this.shaderStage );
  36766. this.flow = previousFlow;
  36767. this.vars = previousVars;
  36768. this.declarations = previousDeclarations;
  36769. this.cache = previousCache;
  36770. this.stack = previousStack;
  36771. this.setBuildStage( previousBuildStage );
  36772. return flow;
  36773. }
  36774. /**
  36775. * Returns the native shader operator name for a given generic name.
  36776. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  36777. *
  36778. * @abstract
  36779. * @param {string} op - The operator name to resolve.
  36780. * @return {?string} The resolved operator name.
  36781. */
  36782. getFunctionOperator( /* op */ ) {
  36783. return null;
  36784. }
  36785. /**
  36786. * Builds the given shader node.
  36787. *
  36788. * @abstract
  36789. * @param {ShaderNodeInternal} shaderNode - The shader node.
  36790. * @return {string} The function code.
  36791. */
  36792. buildFunctionCode( /* shaderNode */ ) {
  36793. warn( 'Abstract function.' );
  36794. }
  36795. /**
  36796. * Generates a code flow based on a child Node.
  36797. *
  36798. * @param {Node} node - The node to execute.
  36799. * @param {?string} output - Expected output type. For example 'vec3'.
  36800. * @return {Object} The code flow.
  36801. */
  36802. flowChildNode( node, output = null ) {
  36803. const previousFlow = this.flow;
  36804. const flow = {
  36805. code: ''
  36806. };
  36807. this.flow = flow;
  36808. flow.result = node.build( this, output );
  36809. this.flow = previousFlow;
  36810. return flow;
  36811. }
  36812. /**
  36813. * Executes a flow of code in a different stage.
  36814. *
  36815. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  36816. * return the value in fragment-stage even if it is being executed in an input fragment.
  36817. *
  36818. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36819. * @param {Node} node - The node to execute.
  36820. * @param {?string} output - Expected output type. For example 'vec3'.
  36821. * @param {?string} propertyName - The property name to assign the result.
  36822. * @return {?(Object|Node)} The code flow or node.build() result.
  36823. */
  36824. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  36825. const previousTab = this.tab;
  36826. const previousCache = this.cache;
  36827. const previousShaderStage = this.shaderStage;
  36828. const previousContext = this.context;
  36829. this.setShaderStage( shaderStage );
  36830. const context = { ...this.context };
  36831. delete context.nodeBlock;
  36832. this.cache = this.globalCache;
  36833. this.tab = '\t';
  36834. this.context = context;
  36835. let result = null;
  36836. if ( this.buildStage === 'generate' ) {
  36837. const flowData = this.flowChildNode( node, output );
  36838. if ( propertyName !== null ) {
  36839. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  36840. }
  36841. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  36842. result = flowData;
  36843. } else {
  36844. result = node.build( this );
  36845. }
  36846. this.setShaderStage( previousShaderStage );
  36847. this.cache = previousCache;
  36848. this.tab = previousTab;
  36849. this.context = previousContext;
  36850. return result;
  36851. }
  36852. /**
  36853. * Returns an array holding all node attributes of this node builder.
  36854. *
  36855. * @return {Array<NodeAttribute>} The node attributes of this builder.
  36856. */
  36857. getAttributesArray() {
  36858. return this.attributes.concat( this.bufferAttributes );
  36859. }
  36860. /**
  36861. * Returns the attribute definitions as a shader string for the given shader stage.
  36862. *
  36863. * @abstract
  36864. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36865. * @return {string} The attribute code section.
  36866. */
  36867. getAttributes( /*shaderStage*/ ) {
  36868. warn( 'Abstract function.' );
  36869. }
  36870. /**
  36871. * Returns the varying definitions as a shader string for the given shader stage.
  36872. *
  36873. * @abstract
  36874. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36875. * @return {string} The varying code section.
  36876. */
  36877. getVaryings( /*shaderStage*/ ) {
  36878. warn( 'Abstract function.' );
  36879. }
  36880. /**
  36881. * Returns a single variable definition as a shader string for the given variable type and name.
  36882. *
  36883. * @param {string} type - The variable's type.
  36884. * @param {string} name - The variable's name.
  36885. * @param {?number} [count=null] - The array length.
  36886. * @return {string} The shader string.
  36887. */
  36888. getVar( type, name, count = null ) {
  36889. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  36890. }
  36891. /**
  36892. * Returns the variable definitions as a shader string for the given shader stage.
  36893. *
  36894. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36895. * @return {string} The variable code section.
  36896. */
  36897. getVars( shaderStage ) {
  36898. let snippet = '';
  36899. const vars = this.vars[ shaderStage ];
  36900. if ( vars !== undefined ) {
  36901. for ( const variable of vars ) {
  36902. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  36903. }
  36904. }
  36905. return snippet;
  36906. }
  36907. /**
  36908. * Returns the uniform definitions as a shader string for the given shader stage.
  36909. *
  36910. * @abstract
  36911. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36912. * @return {string} The uniform code section.
  36913. */
  36914. getUniforms( /*shaderStage*/ ) {
  36915. warn( 'Abstract function.' );
  36916. }
  36917. /**
  36918. * Returns the native code definitions as a shader string for the given shader stage.
  36919. *
  36920. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36921. * @return {string} The native code section.
  36922. */
  36923. getCodes( shaderStage ) {
  36924. const codes = this.codes[ shaderStage ];
  36925. let code = '';
  36926. if ( codes !== undefined ) {
  36927. for ( const nodeCode of codes ) {
  36928. code += nodeCode.code + '\n';
  36929. }
  36930. }
  36931. return code;
  36932. }
  36933. /**
  36934. * Returns the hash of this node builder.
  36935. *
  36936. * @return {string} The hash.
  36937. */
  36938. getHash() {
  36939. return this.vertexShader + this.fragmentShader + this.computeShader;
  36940. }
  36941. /**
  36942. * Sets the current shader stage.
  36943. *
  36944. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  36945. */
  36946. setShaderStage( shaderStage ) {
  36947. this.shaderStage = shaderStage;
  36948. }
  36949. /**
  36950. * Returns the current shader stage.
  36951. *
  36952. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  36953. */
  36954. getShaderStage() {
  36955. return this.shaderStage;
  36956. }
  36957. /**
  36958. * Sets the current build stage.
  36959. *
  36960. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  36961. */
  36962. setBuildStage( buildStage ) {
  36963. this.buildStage = buildStage;
  36964. }
  36965. /**
  36966. * Returns the current build stage.
  36967. *
  36968. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  36969. */
  36970. getBuildStage() {
  36971. return this.buildStage;
  36972. }
  36973. /**
  36974. * Controls the code build of the shader stages.
  36975. *
  36976. * @abstract
  36977. */
  36978. buildCode() {
  36979. warn( 'Abstract function.' );
  36980. }
  36981. /**
  36982. * Returns the current sub-build layer.
  36983. *
  36984. * @return {SubBuildNode} The current sub-build layers.
  36985. */
  36986. get subBuild() {
  36987. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  36988. }
  36989. /**
  36990. * Adds a sub-build layer to the node builder.
  36991. *
  36992. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  36993. */
  36994. addSubBuild( subBuild ) {
  36995. this.subBuildLayers.push( subBuild );
  36996. }
  36997. /**
  36998. * Removes the last sub-build layer from the node builder.
  36999. *
  37000. * @return {SubBuildNode} The removed sub-build layer.
  37001. */
  37002. removeSubBuild() {
  37003. return this.subBuildLayers.pop();
  37004. }
  37005. /**
  37006. * Returns the closest sub-build layer for the given data.
  37007. *
  37008. * @param {Node|Set<string>|Array<string>} data - The data to get the closest sub-build layer from.
  37009. * @return {?string} The closest sub-build name or null if none found.
  37010. */
  37011. getClosestSubBuild( data ) {
  37012. let subBuilds;
  37013. if ( data && data.isNode ) {
  37014. if ( data.isShaderCallNodeInternal ) {
  37015. subBuilds = data.shaderNode.subBuilds;
  37016. } else if ( data.isStackNode ) {
  37017. subBuilds = [ data.subBuild ];
  37018. } else {
  37019. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  37020. }
  37021. } else if ( data instanceof Set ) {
  37022. subBuilds = [ ...data ];
  37023. } else {
  37024. subBuilds = data;
  37025. }
  37026. if ( ! subBuilds ) return null;
  37027. const subBuildLayers = this.subBuildLayers;
  37028. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  37029. const subBuild = subBuilds[ i ];
  37030. if ( subBuildLayers.includes( subBuild ) ) {
  37031. return subBuild;
  37032. }
  37033. }
  37034. return null;
  37035. }
  37036. /**
  37037. * Returns the output node of a sub-build layer.
  37038. *
  37039. * @param {Node} node - The node to get the output from.
  37040. * @return {string} The output node name.
  37041. */
  37042. getSubBuildOutput( node ) {
  37043. return this.getSubBuildProperty( 'outputNode', node );
  37044. }
  37045. /**
  37046. * Returns the sub-build property name for the given property and node.
  37047. *
  37048. * @param {string} [property=''] - The property name.
  37049. * @param {?Node} [node=null] - The node to get the sub-build from.
  37050. * @return {string} The sub-build property name.
  37051. */
  37052. getSubBuildProperty( property = '', node = null ) {
  37053. let subBuild;
  37054. if ( node !== null ) {
  37055. subBuild = this.getClosestSubBuild( node );
  37056. } else {
  37057. subBuild = this.subBuildFn;
  37058. }
  37059. let result;
  37060. if ( subBuild ) {
  37061. result = property ? ( subBuild + '_' + property ) : subBuild;
  37062. } else {
  37063. result = property;
  37064. }
  37065. return result;
  37066. }
  37067. /**
  37068. * Central build method which controls the build for the given object.
  37069. *
  37070. * @return {NodeBuilder} A reference to this node builder.
  37071. */
  37072. build() {
  37073. const { object, material, renderer } = this;
  37074. if ( material !== null ) {
  37075. let nodeMaterial = renderer.library.fromMaterial( material );
  37076. if ( nodeMaterial === null ) {
  37077. error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  37078. nodeMaterial = new NodeMaterial();
  37079. }
  37080. nodeMaterial.build( this );
  37081. } else {
  37082. this.addFlow( 'compute', object );
  37083. }
  37084. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  37085. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  37086. // generate() -> stage 3: generate shader
  37087. for ( const buildStage of defaultBuildStages ) {
  37088. this.setBuildStage( buildStage );
  37089. if ( this.context.vertex && this.context.vertex.isNode ) {
  37090. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  37091. }
  37092. for ( const shaderStage of shaderStages ) {
  37093. this.setShaderStage( shaderStage );
  37094. const flowNodes = this.flowNodes[ shaderStage ];
  37095. for ( const node of flowNodes ) {
  37096. if ( buildStage === 'generate' ) {
  37097. this.flowNode( node );
  37098. } else {
  37099. node.build( this );
  37100. }
  37101. }
  37102. }
  37103. }
  37104. this.setBuildStage( null );
  37105. this.setShaderStage( null );
  37106. // stage 4: build code for a specific output
  37107. this.buildCode();
  37108. this.buildUpdateNodes();
  37109. return this;
  37110. }
  37111. /**
  37112. * Returns shared data object for the given node.
  37113. *
  37114. * @param {Node} node - The node to get shared data from.
  37115. * @return {Object} The shared data.
  37116. */
  37117. getSharedDataFromNode( node ) {
  37118. let data = sharedNodeData.get( node );
  37119. if ( data === undefined ) {
  37120. data = {};
  37121. }
  37122. return data;
  37123. }
  37124. /**
  37125. * Returns a uniform representation which is later used for UBO generation and rendering.
  37126. *
  37127. * @param {NodeUniform} uniformNode - The uniform node.
  37128. * @param {string} type - The requested type.
  37129. * @return {Uniform} The uniform.
  37130. */
  37131. getNodeUniform( uniformNode, type ) {
  37132. const nodeData = this.getSharedDataFromNode( uniformNode );
  37133. let node = nodeData.cache;
  37134. if ( node === undefined ) {
  37135. if ( type === 'float' || type === 'int' || type === 'uint' ) node = new NumberNodeUniform( uniformNode );
  37136. else if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) node = new Vector2NodeUniform( uniformNode );
  37137. else if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) node = new Vector3NodeUniform( uniformNode );
  37138. else if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) node = new Vector4NodeUniform( uniformNode );
  37139. else if ( type === 'color' ) node = new ColorNodeUniform( uniformNode );
  37140. else if ( type === 'mat2' ) node = new Matrix2NodeUniform( uniformNode );
  37141. else if ( type === 'mat3' ) node = new Matrix3NodeUniform( uniformNode );
  37142. else if ( type === 'mat4' ) node = new Matrix4NodeUniform( uniformNode );
  37143. else {
  37144. throw new Error( `Uniform "${ type }" not implemented.` );
  37145. }
  37146. nodeData.cache = node;
  37147. }
  37148. return node;
  37149. }
  37150. /**
  37151. * Formats the given shader snippet from a given type into another one. E.g.
  37152. * this method might be used to convert a simple float string `"1.0"` into a
  37153. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  37154. *
  37155. * @param {string} snippet - The shader snippet.
  37156. * @param {string} fromType - The source type.
  37157. * @param {string} toType - The target type.
  37158. * @return {string} The updated shader string.
  37159. */
  37160. format( snippet, fromType, toType ) {
  37161. fromType = this.getVectorType( fromType );
  37162. toType = this.getVectorType( toType );
  37163. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  37164. return snippet;
  37165. }
  37166. const fromTypeLength = this.getTypeLength( fromType );
  37167. const toTypeLength = this.getTypeLength( toType );
  37168. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  37169. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  37170. }
  37171. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  37172. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  37173. }
  37174. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  37175. // @TODO: ignore for now
  37176. return snippet;
  37177. }
  37178. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  37179. // @TODO: ignore for now
  37180. return snippet;
  37181. }
  37182. if ( fromTypeLength === toTypeLength ) {
  37183. return `${ this.getType( toType ) }( ${ snippet } )`;
  37184. }
  37185. if ( fromTypeLength > toTypeLength ) {
  37186. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  37187. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  37188. }
  37189. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  37190. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  37191. }
  37192. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  37193. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  37194. }
  37195. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  37196. // convert a number value to vector type, e.g:
  37197. // vec3( 1u ) -> vec3( float( 1u ) )
  37198. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  37199. }
  37200. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  37201. }
  37202. /**
  37203. * Returns a signature with the engine's current revision.
  37204. *
  37205. * @return {string} The signature.
  37206. */
  37207. getSignature() {
  37208. return `// Three.js r${ REVISION } - Node System\n`;
  37209. }
  37210. }
  37211. /**
  37212. * Management class for updating nodes. The module tracks metrics like
  37213. * the elapsed time, delta time, the render and frame ID to correctly
  37214. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  37215. * and {@link Node#updateAfter} depending on the node's configuration.
  37216. */
  37217. class NodeFrame {
  37218. /**
  37219. * Constructs a new node fame.
  37220. */
  37221. constructor() {
  37222. /**
  37223. * The elapsed time in seconds.
  37224. *
  37225. * @type {number}
  37226. * @default 0
  37227. */
  37228. this.time = 0;
  37229. /**
  37230. * The delta time in seconds.
  37231. *
  37232. * @type {number}
  37233. * @default 0
  37234. */
  37235. this.deltaTime = 0;
  37236. /**
  37237. * The frame ID.
  37238. *
  37239. * @type {number}
  37240. * @default 0
  37241. */
  37242. this.frameId = 0;
  37243. /**
  37244. * The render ID.
  37245. *
  37246. * @type {number}
  37247. * @default 0
  37248. */
  37249. this.renderId = 0;
  37250. /**
  37251. * Used to control the {@link Node#update} call.
  37252. *
  37253. * @type {WeakMap<Node, Object>}
  37254. */
  37255. this.updateMap = new WeakMap();
  37256. /**
  37257. * Used to control the {@link Node#updateBefore} call.
  37258. *
  37259. * @type {WeakMap<Node, Object>}
  37260. */
  37261. this.updateBeforeMap = new WeakMap();
  37262. /**
  37263. * Used to control the {@link Node#updateAfter} call.
  37264. *
  37265. * @type {WeakMap<Node, Object>}
  37266. */
  37267. this.updateAfterMap = new WeakMap();
  37268. /**
  37269. * A reference to the current renderer.
  37270. *
  37271. * @type {?Renderer}
  37272. * @default null
  37273. */
  37274. this.renderer = null;
  37275. /**
  37276. * A reference to the current material.
  37277. *
  37278. * @type {?Material}
  37279. * @default null
  37280. */
  37281. this.material = null;
  37282. /**
  37283. * A reference to the current camera.
  37284. *
  37285. * @type {?Camera}
  37286. * @default null
  37287. */
  37288. this.camera = null;
  37289. /**
  37290. * A reference to the current 3D object.
  37291. *
  37292. * @type {?Object3D}
  37293. * @default null
  37294. */
  37295. this.object = null;
  37296. /**
  37297. * A reference to the current scene.
  37298. *
  37299. * @type {?Scene}
  37300. * @default null
  37301. */
  37302. this.scene = null;
  37303. }
  37304. /**
  37305. * Returns a dictionary for a given node and update map which
  37306. * is used to correctly call node update methods per frame or render.
  37307. *
  37308. * @private
  37309. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  37310. * @param {Node} nodeRef - The reference to the current node.
  37311. * @return {Object<string,WeakMap<Object, number>>} The dictionary.
  37312. */
  37313. _getMaps( referenceMap, nodeRef ) {
  37314. let maps = referenceMap.get( nodeRef );
  37315. if ( maps === undefined ) {
  37316. maps = {
  37317. renderId: 0,
  37318. frameId: 0,
  37319. };
  37320. referenceMap.set( nodeRef, maps );
  37321. }
  37322. return maps;
  37323. }
  37324. /**
  37325. * This method executes the {@link Node#updateBefore} for the given node.
  37326. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  37327. * is only executed once per frame, render or object depending on the update
  37328. * type.
  37329. *
  37330. * @param {Node} node - The node that should be updated.
  37331. */
  37332. updateBeforeNode( node ) {
  37333. const updateType = node.getUpdateBeforeType();
  37334. const reference = node.updateReference( this );
  37335. if ( updateType === NodeUpdateType.FRAME ) {
  37336. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  37337. if ( nodeUpdateBeforeMap.frameId !== this.frameId ) {
  37338. const previousFrameId = nodeUpdateBeforeMap.frameId;
  37339. nodeUpdateBeforeMap.frameId = this.frameId;
  37340. if ( node.updateBefore( this ) === false ) {
  37341. nodeUpdateBeforeMap.frameId = previousFrameId;
  37342. }
  37343. }
  37344. } else if ( updateType === NodeUpdateType.RENDER ) {
  37345. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  37346. if ( nodeUpdateBeforeMap.renderId !== this.renderId ) {
  37347. const previousRenderId = nodeUpdateBeforeMap.renderId;
  37348. nodeUpdateBeforeMap.renderId = this.renderId;
  37349. if ( node.updateBefore( this ) === false ) {
  37350. nodeUpdateBeforeMap.renderId = previousRenderId;
  37351. }
  37352. }
  37353. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37354. node.updateBefore( this );
  37355. }
  37356. }
  37357. /**
  37358. * This method executes the {@link Node#updateAfter} for the given node.
  37359. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  37360. * is only executed once per frame, render or object depending on the update
  37361. * type.
  37362. *
  37363. * @param {Node} node - The node that should be updated.
  37364. */
  37365. updateAfterNode( node ) {
  37366. const updateType = node.getUpdateAfterType();
  37367. const reference = node.updateReference( this );
  37368. if ( updateType === NodeUpdateType.FRAME ) {
  37369. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  37370. if ( nodeUpdateAfterMap.frameId !== this.frameId ) {
  37371. if ( node.updateAfter( this ) !== false ) {
  37372. nodeUpdateAfterMap.frameId = this.frameId;
  37373. }
  37374. }
  37375. } else if ( updateType === NodeUpdateType.RENDER ) {
  37376. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  37377. if ( nodeUpdateAfterMap.renderId !== this.renderId ) {
  37378. if ( node.updateAfter( this ) !== false ) {
  37379. nodeUpdateAfterMap.renderId = this.renderId;
  37380. }
  37381. }
  37382. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37383. node.updateAfter( this );
  37384. }
  37385. }
  37386. /**
  37387. * This method executes the {@link Node#update} for the given node.
  37388. * It makes sure {@link Node#updateType} is honored meaning the update
  37389. * is only executed once per frame, render or object depending on the update
  37390. * type.
  37391. *
  37392. * @param {Node} node - The node that should be updated.
  37393. */
  37394. updateNode( node ) {
  37395. const updateType = node.getUpdateType();
  37396. const reference = node.updateReference( this );
  37397. if ( updateType === NodeUpdateType.FRAME ) {
  37398. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  37399. if ( nodeUpdateMap.frameId !== this.frameId ) {
  37400. if ( node.update( this ) !== false ) {
  37401. nodeUpdateMap.frameId = this.frameId;
  37402. }
  37403. }
  37404. } else if ( updateType === NodeUpdateType.RENDER ) {
  37405. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  37406. if ( nodeUpdateMap.renderId !== this.renderId ) {
  37407. if ( node.update( this ) !== false ) {
  37408. nodeUpdateMap.renderId = this.renderId;
  37409. }
  37410. }
  37411. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37412. node.update( this );
  37413. }
  37414. }
  37415. /**
  37416. * Updates the internal state of the node frame. This method is
  37417. * called by the renderer in its internal animation loop.
  37418. */
  37419. update() {
  37420. this.frameId ++;
  37421. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  37422. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  37423. this.lastTime = performance.now();
  37424. this.time += this.deltaTime;
  37425. }
  37426. }
  37427. /**
  37428. * Describes the input of a {@link NodeFunction}.
  37429. */
  37430. class NodeFunctionInput {
  37431. /**
  37432. * Constructs a new node function input.
  37433. *
  37434. * @param {string} type - The input type.
  37435. * @param {string} name - The input name.
  37436. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  37437. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  37438. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  37439. */
  37440. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  37441. /**
  37442. * The input type.
  37443. *
  37444. * @type {string}
  37445. */
  37446. this.type = type;
  37447. /**
  37448. * The input name.
  37449. *
  37450. * @type {string}
  37451. */
  37452. this.name = name;
  37453. /**
  37454. * If the input is an Array, count will be the length.
  37455. *
  37456. * @type {?number}
  37457. * @default null
  37458. */
  37459. this.count = count;
  37460. /**
  37461. *The parameter qualifier (only relevant for GLSL).
  37462. *
  37463. * @type {('in'|'out'|'inout')}
  37464. * @default ''
  37465. */
  37466. this.qualifier = qualifier;
  37467. /**
  37468. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  37469. *
  37470. * @type {boolean}
  37471. * @default false
  37472. */
  37473. this.isConst = isConst;
  37474. }
  37475. }
  37476. NodeFunctionInput.isNodeFunctionInput = true;
  37477. /**
  37478. * Module for representing directional lights as nodes.
  37479. *
  37480. * @augments AnalyticLightNode
  37481. */
  37482. class DirectionalLightNode extends AnalyticLightNode {
  37483. static get type() {
  37484. return 'DirectionalLightNode';
  37485. }
  37486. /**
  37487. * Constructs a new directional light node.
  37488. *
  37489. * @param {?DirectionalLight} [light=null] - The directional light source.
  37490. */
  37491. constructor( light = null ) {
  37492. super( light );
  37493. }
  37494. setupDirect() {
  37495. const lightColor = this.colorNode;
  37496. const lightDirection = lightTargetDirection( this.light );
  37497. return { lightDirection, lightColor };
  37498. }
  37499. }
  37500. const _matrix41 = /*@__PURE__*/ new Matrix4();
  37501. const _matrix42 = /*@__PURE__*/ new Matrix4();
  37502. let _ltcLib = null;
  37503. /**
  37504. * Module for representing rect area lights as nodes.
  37505. *
  37506. * @augments AnalyticLightNode
  37507. */
  37508. class RectAreaLightNode extends AnalyticLightNode {
  37509. static get type() {
  37510. return 'RectAreaLightNode';
  37511. }
  37512. /**
  37513. * Constructs a new rect area light node.
  37514. *
  37515. * @param {?RectAreaLight} [light=null] - The rect area light source.
  37516. */
  37517. constructor( light = null ) {
  37518. super( light );
  37519. /**
  37520. * Uniform node representing the half height of the are light.
  37521. *
  37522. * @type {UniformNode<vec3>}
  37523. */
  37524. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  37525. /**
  37526. * Uniform node representing the half width of the are light.
  37527. *
  37528. * @type {UniformNode<vec3>}
  37529. */
  37530. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  37531. /**
  37532. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  37533. * relies on `viewMatrix` which might vary per render call.
  37534. *
  37535. * @type {string}
  37536. * @default 'render'
  37537. */
  37538. this.updateType = NodeUpdateType.RENDER;
  37539. }
  37540. /**
  37541. * Overwritten to updated rect area light specific uniforms.
  37542. *
  37543. * @param {NodeFrame} frame - A reference to the current node frame.
  37544. */
  37545. update( frame ) {
  37546. super.update( frame );
  37547. const { light } = this;
  37548. const viewMatrix = frame.camera.matrixWorldInverse;
  37549. _matrix42.identity();
  37550. _matrix41.copy( light.matrixWorld );
  37551. _matrix41.premultiply( viewMatrix );
  37552. _matrix42.extractRotation( _matrix41 );
  37553. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  37554. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  37555. this.halfWidth.value.applyMatrix4( _matrix42 );
  37556. this.halfHeight.value.applyMatrix4( _matrix42 );
  37557. }
  37558. setupDirectRectArea( builder ) {
  37559. let ltc_1, ltc_2;
  37560. if ( builder.isAvailable( 'float32Filterable' ) ) {
  37561. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  37562. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  37563. } else {
  37564. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  37565. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  37566. }
  37567. const { colorNode, light } = this;
  37568. const lightPosition = lightViewPosition( light );
  37569. return {
  37570. lightColor: colorNode,
  37571. lightPosition,
  37572. halfWidth: this.halfWidth,
  37573. halfHeight: this.halfHeight,
  37574. ltc_1,
  37575. ltc_2
  37576. };
  37577. }
  37578. /**
  37579. * Used to configure the internal BRDF approximation texture data.
  37580. *
  37581. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  37582. */
  37583. static setLTC( ltc ) {
  37584. _ltcLib = ltc;
  37585. }
  37586. }
  37587. /**
  37588. * Module for representing spot lights as nodes.
  37589. *
  37590. * @augments AnalyticLightNode
  37591. */
  37592. class SpotLightNode extends AnalyticLightNode {
  37593. static get type() {
  37594. return 'SpotLightNode';
  37595. }
  37596. /**
  37597. * Constructs a new spot light node.
  37598. *
  37599. * @param {?SpotLight} [light=null] - The spot light source.
  37600. */
  37601. constructor( light = null ) {
  37602. super( light );
  37603. /**
  37604. * Uniform node representing the cone cosine.
  37605. *
  37606. * @type {UniformNode<float>}
  37607. */
  37608. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  37609. /**
  37610. * Uniform node representing the penumbra cosine.
  37611. *
  37612. * @type {UniformNode<float>}
  37613. */
  37614. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  37615. /**
  37616. * Uniform node representing the cutoff distance.
  37617. *
  37618. * @type {UniformNode<float>}
  37619. */
  37620. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  37621. /**
  37622. * Uniform node representing the decay exponent.
  37623. *
  37624. * @type {UniformNode<float>}
  37625. */
  37626. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  37627. /**
  37628. * Uniform node representing the light color.
  37629. *
  37630. * @type {UniformNode<Color>}
  37631. */
  37632. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  37633. }
  37634. /**
  37635. * Overwritten to updated spot light specific uniforms.
  37636. *
  37637. * @param {NodeFrame} frame - A reference to the current node frame.
  37638. */
  37639. update( frame ) {
  37640. super.update( frame );
  37641. const { light } = this;
  37642. this.coneCosNode.value = Math.cos( light.angle );
  37643. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  37644. this.cutoffDistanceNode.value = light.distance;
  37645. this.decayExponentNode.value = light.decay;
  37646. }
  37647. /**
  37648. * Computes the spot attenuation for the given angle.
  37649. *
  37650. * @param {NodeBuilder} builder - The node builder.
  37651. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  37652. * @return {Node<float>} The spot attenuation.
  37653. */
  37654. getSpotAttenuation( builder, angleCosine ) {
  37655. const { coneCosNode, penumbraCosNode } = this;
  37656. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  37657. }
  37658. getLightCoord( builder ) {
  37659. const properties = builder.getNodeProperties( this );
  37660. let projectionUV = properties.projectionUV;
  37661. if ( projectionUV === undefined ) {
  37662. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  37663. properties.projectionUV = projectionUV;
  37664. }
  37665. return projectionUV;
  37666. }
  37667. setupDirect( builder ) {
  37668. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  37669. const lightVector = this.getLightVector( builder );
  37670. const lightDirection = lightVector.normalize();
  37671. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  37672. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  37673. const lightDistance = lightVector.length();
  37674. const lightAttenuation = getDistanceAttenuation( {
  37675. lightDistance,
  37676. cutoffDistance: cutoffDistanceNode,
  37677. decayExponent: decayExponentNode
  37678. } );
  37679. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  37680. let projected, lightCoord;
  37681. if ( light.colorNode ) {
  37682. lightCoord = this.getLightCoord( builder );
  37683. projected = light.colorNode( lightCoord );
  37684. } else if ( light.map ) {
  37685. lightCoord = this.getLightCoord( builder );
  37686. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  37687. }
  37688. if ( projected ) {
  37689. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  37690. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  37691. }
  37692. return { lightColor, lightDirection };
  37693. }
  37694. }
  37695. /**
  37696. * An IES version of the default spot light node.
  37697. *
  37698. * @augments SpotLightNode
  37699. */
  37700. class IESSpotLightNode extends SpotLightNode {
  37701. static get type() {
  37702. return 'IESSpotLightNode';
  37703. }
  37704. /**
  37705. * Overwrites the default implementation to compute an IES conform spot attenuation.
  37706. *
  37707. * @param {NodeBuilder} builder - The node builder.
  37708. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  37709. * @return {Node<float>} The spot attenuation.
  37710. */
  37711. getSpotAttenuation( builder, angleCosine ) {
  37712. const iesMap = this.light.iesMap;
  37713. let spotAttenuation = null;
  37714. if ( iesMap && iesMap.isTexture === true ) {
  37715. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  37716. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  37717. } else {
  37718. spotAttenuation = super.getSpotAttenuation( angleCosine );
  37719. }
  37720. return spotAttenuation;
  37721. }
  37722. }
  37723. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  37724. const d = p.abs().sub( b );
  37725. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  37726. } );
  37727. /**
  37728. * An implementation of a projector light node.
  37729. *
  37730. * @augments SpotLightNode
  37731. */
  37732. class ProjectorLightNode extends SpotLightNode {
  37733. static get type() {
  37734. return 'ProjectorLightNode';
  37735. }
  37736. update( frame ) {
  37737. super.update( frame );
  37738. const light = this.light;
  37739. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  37740. if ( light.aspect === null ) {
  37741. let aspect = 1;
  37742. if ( light.map !== null ) {
  37743. aspect = light.map.width / light.map.height;
  37744. }
  37745. light.shadow.aspect = aspect;
  37746. } else {
  37747. light.shadow.aspect = light.aspect;
  37748. }
  37749. }
  37750. /**
  37751. * Overwrites the default implementation to compute projection attenuation.
  37752. *
  37753. * @param {NodeBuilder} builder - The node builder.
  37754. * @return {Node<float>} The spot attenuation.
  37755. */
  37756. getSpotAttenuation( builder ) {
  37757. const attenuation = float( 0 );
  37758. const penumbraCos = this.penumbraCosNode;
  37759. // compute the fragment's position in the light's clip space
  37760. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  37761. // the sign of w determines whether the current fragment is in front or behind the light.
  37762. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  37763. If( spotLightCoord.w.greaterThan( 0 ), () => {
  37764. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  37765. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  37766. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  37767. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  37768. } );
  37769. return attenuation;
  37770. }
  37771. }
  37772. /**
  37773. * Module for representing ambient lights as nodes.
  37774. *
  37775. * @augments AnalyticLightNode
  37776. */
  37777. class AmbientLightNode extends AnalyticLightNode {
  37778. static get type() {
  37779. return 'AmbientLightNode';
  37780. }
  37781. /**
  37782. * Constructs a new ambient light node.
  37783. *
  37784. * @param {?AmbientLight} [light=null] - The ambient light source.
  37785. */
  37786. constructor( light = null ) {
  37787. super( light );
  37788. }
  37789. setup( { context } ) {
  37790. context.irradiance.addAssign( this.colorNode );
  37791. }
  37792. }
  37793. /**
  37794. * Module for representing hemisphere lights as nodes.
  37795. *
  37796. * @augments AnalyticLightNode
  37797. */
  37798. class HemisphereLightNode extends AnalyticLightNode {
  37799. static get type() {
  37800. return 'HemisphereLightNode';
  37801. }
  37802. /**
  37803. * Constructs a new hemisphere light node.
  37804. *
  37805. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  37806. */
  37807. constructor( light = null ) {
  37808. super( light );
  37809. /**
  37810. * Uniform node representing the light's position.
  37811. *
  37812. * @type {UniformNode<vec3>}
  37813. */
  37814. this.lightPositionNode = lightPosition( light );
  37815. /**
  37816. * A node representing the light's direction.
  37817. *
  37818. * @type {Node<vec3>}
  37819. */
  37820. this.lightDirectionNode = this.lightPositionNode.normalize();
  37821. /**
  37822. * Uniform node representing the light's ground color.
  37823. *
  37824. * @type {UniformNode<vec3>}
  37825. */
  37826. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  37827. }
  37828. /**
  37829. * Overwritten to updated hemisphere light specific uniforms.
  37830. *
  37831. * @param {NodeFrame} frame - A reference to the current node frame.
  37832. */
  37833. update( frame ) {
  37834. const { light } = this;
  37835. super.update( frame );
  37836. this.lightPositionNode.object3d = light;
  37837. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  37838. }
  37839. setup( builder ) {
  37840. const { colorNode, groundColorNode, lightDirectionNode } = this;
  37841. const dotNL = normalWorld.dot( lightDirectionNode );
  37842. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  37843. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  37844. builder.context.irradiance.addAssign( irradiance );
  37845. }
  37846. }
  37847. /**
  37848. * Module for representing light probes as nodes.
  37849. *
  37850. * @augments AnalyticLightNode
  37851. */
  37852. class LightProbeNode extends AnalyticLightNode {
  37853. static get type() {
  37854. return 'LightProbeNode';
  37855. }
  37856. /**
  37857. * Constructs a new light probe node.
  37858. *
  37859. * @param {?LightProbe} [light=null] - The light probe.
  37860. */
  37861. constructor( light = null ) {
  37862. super( light );
  37863. const array = [];
  37864. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  37865. /**
  37866. * Light probe represented as a uniform of spherical harmonics.
  37867. *
  37868. * @type {UniformArrayNode}
  37869. */
  37870. this.lightProbe = uniformArray( array );
  37871. }
  37872. /**
  37873. * Overwritten to updated light probe specific uniforms.
  37874. *
  37875. * @param {NodeFrame} frame - A reference to the current node frame.
  37876. */
  37877. update( frame ) {
  37878. const { light } = this;
  37879. super.update( frame );
  37880. //
  37881. for ( let i = 0; i < 9; i ++ ) {
  37882. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  37883. }
  37884. }
  37885. setup( builder ) {
  37886. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  37887. builder.context.irradiance.addAssign( irradiance );
  37888. }
  37889. }
  37890. /**
  37891. * Base class for node parsers. A derived parser must be implemented
  37892. * for each supported native shader language.
  37893. */
  37894. class NodeParser {
  37895. /**
  37896. * The method parses the given native code an returns a node function.
  37897. *
  37898. * @abstract
  37899. * @param {string} source - The native shader code.
  37900. * @return {NodeFunction} A node function.
  37901. */
  37902. parseFunction( /*source*/ ) {
  37903. warn( 'Abstract function.' );
  37904. }
  37905. }
  37906. /**
  37907. * Base class for node functions. A derived module must be implemented
  37908. * for each supported native shader language. Similar to other `Node*` modules,
  37909. * this class is only relevant during the building process and not used
  37910. * in user-level code.
  37911. */
  37912. class NodeFunction {
  37913. /**
  37914. * Constructs a new node function.
  37915. *
  37916. * @param {string} type - The node type. This type is the return type of the node function.
  37917. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  37918. * @param {string} [name=''] - The function's name.
  37919. * @param {string} [precision=''] - The precision qualifier.
  37920. */
  37921. constructor( type, inputs, name = '', precision = '' ) {
  37922. /**
  37923. * The node type. This type is the return type of the node function.
  37924. *
  37925. * @type {string}
  37926. */
  37927. this.type = type;
  37928. /**
  37929. * The function's inputs.
  37930. *
  37931. * @type {Array<NodeFunctionInput>}
  37932. */
  37933. this.inputs = inputs;
  37934. /**
  37935. * The name of the uniform.
  37936. *
  37937. * @type {string}
  37938. * @default ''
  37939. */
  37940. this.name = name;
  37941. /**
  37942. * The precision qualifier.
  37943. *
  37944. * @type {string}
  37945. * @default ''
  37946. */
  37947. this.precision = precision;
  37948. }
  37949. /**
  37950. * This method returns the native code of the node function.
  37951. *
  37952. * @abstract
  37953. * @param {string} name - The function's name.
  37954. * @return {string} A shader code.
  37955. */
  37956. getCode( /*name = this.name*/ ) {
  37957. warn( 'Abstract function.' );
  37958. }
  37959. }
  37960. NodeFunction.isNodeFunction = true;
  37961. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  37962. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  37963. const pragmaMain = '#pragma main';
  37964. const parse$1 = ( source ) => {
  37965. source = source.trim();
  37966. const pragmaMainIndex = source.indexOf( pragmaMain );
  37967. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  37968. const declaration = mainCode.match( declarationRegexp$1 );
  37969. if ( declaration !== null && declaration.length === 5 ) {
  37970. // tokenizer
  37971. const inputsCode = declaration[ 4 ];
  37972. const propsMatches = [];
  37973. let nameMatch = null;
  37974. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  37975. propsMatches.push( nameMatch );
  37976. }
  37977. // parser
  37978. const inputs = [];
  37979. let i = 0;
  37980. while ( i < propsMatches.length ) {
  37981. const isConst = propsMatches[ i ][ 0 ] === 'const';
  37982. if ( isConst === true ) {
  37983. i ++;
  37984. }
  37985. let qualifier = propsMatches[ i ][ 0 ];
  37986. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  37987. i ++;
  37988. } else {
  37989. qualifier = '';
  37990. }
  37991. const type = propsMatches[ i ++ ][ 0 ];
  37992. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  37993. if ( Number.isNaN( count ) === false ) i ++;
  37994. else count = null;
  37995. const name = propsMatches[ i ++ ][ 0 ];
  37996. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  37997. }
  37998. //
  37999. const blockCode = mainCode.substring( declaration[ 0 ].length );
  38000. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  38001. const type = declaration[ 2 ];
  38002. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  38003. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  38004. return {
  38005. type,
  38006. inputs,
  38007. name,
  38008. precision,
  38009. inputsCode,
  38010. blockCode,
  38011. headerCode
  38012. };
  38013. } else {
  38014. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  38015. }
  38016. };
  38017. /**
  38018. * This class represents a GLSL node function.
  38019. *
  38020. * @augments NodeFunction
  38021. */
  38022. class GLSLNodeFunction extends NodeFunction {
  38023. /**
  38024. * Constructs a new GLSL node function.
  38025. *
  38026. * @param {string} source - The GLSL source.
  38027. */
  38028. constructor( source ) {
  38029. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  38030. super( type, inputs, name, precision );
  38031. this.inputsCode = inputsCode;
  38032. this.blockCode = blockCode;
  38033. this.headerCode = headerCode;
  38034. }
  38035. /**
  38036. * This method returns the GLSL code of the node function.
  38037. *
  38038. * @param {string} [name=this.name] - The function's name.
  38039. * @return {string} The shader code.
  38040. */
  38041. getCode( name = this.name ) {
  38042. let code;
  38043. const blockCode = this.blockCode;
  38044. if ( blockCode !== '' ) {
  38045. const { type, inputsCode, headerCode, precision } = this;
  38046. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  38047. if ( precision !== '' ) {
  38048. declarationCode = `${ precision } ${ declarationCode }`;
  38049. }
  38050. code = headerCode + declarationCode + blockCode;
  38051. } else {
  38052. // interface function
  38053. code = '';
  38054. }
  38055. return code;
  38056. }
  38057. }
  38058. /**
  38059. * A GLSL node parser.
  38060. *
  38061. * @augments NodeParser
  38062. */
  38063. class GLSLNodeParser extends NodeParser {
  38064. /**
  38065. * The method parses the given GLSL code an returns a node function.
  38066. *
  38067. * @param {string} source - The GLSL code.
  38068. * @return {GLSLNodeFunction} A node function.
  38069. */
  38070. parseFunction( source ) {
  38071. return new GLSLNodeFunction( source );
  38072. }
  38073. }
  38074. const _outputNodeMap = new WeakMap();
  38075. const _chainKeys$2 = [];
  38076. const _cacheKeyValues = [];
  38077. /**
  38078. * This renderer module manages node-related objects and is the
  38079. * primary interface between the renderer and the node system.
  38080. *
  38081. * @private
  38082. * @augments DataMap
  38083. */
  38084. class Nodes extends DataMap {
  38085. /**
  38086. * Constructs a new nodes management component.
  38087. *
  38088. * @param {Renderer} renderer - The renderer.
  38089. * @param {Backend} backend - The renderer's backend.
  38090. */
  38091. constructor( renderer, backend ) {
  38092. super();
  38093. /**
  38094. * The renderer.
  38095. *
  38096. * @type {Renderer}
  38097. */
  38098. this.renderer = renderer;
  38099. /**
  38100. * The renderer's backend.
  38101. *
  38102. * @type {Backend}
  38103. */
  38104. this.backend = backend;
  38105. /**
  38106. * The node frame.
  38107. *
  38108. * @type {Renderer}
  38109. */
  38110. this.nodeFrame = new NodeFrame();
  38111. /**
  38112. * A cache for managing node builder states.
  38113. *
  38114. * @type {Map<number,NodeBuilderState>}
  38115. */
  38116. this.nodeBuilderCache = new Map();
  38117. /**
  38118. * A cache for managing data cache key data.
  38119. *
  38120. * @type {ChainMap}
  38121. */
  38122. this.callHashCache = new ChainMap();
  38123. /**
  38124. * A cache for managing node uniforms group data.
  38125. *
  38126. * @type {ChainMap}
  38127. */
  38128. this.groupsData = new ChainMap();
  38129. /**
  38130. * A cache for managing node objects of
  38131. * scene properties like fog or environments.
  38132. *
  38133. * @type {Object<string,WeakMap>}
  38134. */
  38135. this.cacheLib = {};
  38136. }
  38137. /**
  38138. * Returns `true` if the given node uniforms group must be updated or not.
  38139. *
  38140. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  38141. * @return {boolean} Whether the node uniforms group requires an update or not.
  38142. */
  38143. updateGroup( nodeUniformsGroup ) {
  38144. const groupNode = nodeUniformsGroup.groupNode;
  38145. const name = groupNode.name;
  38146. // objectGroup is always updated
  38147. if ( name === objectGroup.name ) return true;
  38148. // renderGroup is updated once per render/compute call
  38149. if ( name === renderGroup.name ) {
  38150. const uniformsGroupData = this.get( nodeUniformsGroup );
  38151. const renderId = this.nodeFrame.renderId;
  38152. if ( uniformsGroupData.renderId !== renderId ) {
  38153. uniformsGroupData.renderId = renderId;
  38154. return true;
  38155. }
  38156. return false;
  38157. }
  38158. // frameGroup is updated once per frame
  38159. if ( name === frameGroup.name ) {
  38160. const uniformsGroupData = this.get( nodeUniformsGroup );
  38161. const frameId = this.nodeFrame.frameId;
  38162. if ( uniformsGroupData.frameId !== frameId ) {
  38163. uniformsGroupData.frameId = frameId;
  38164. return true;
  38165. }
  38166. return false;
  38167. }
  38168. // other groups are updated just when groupNode.needsUpdate is true
  38169. _chainKeys$2[ 0 ] = groupNode;
  38170. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  38171. let groupData = this.groupsData.get( _chainKeys$2 );
  38172. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  38173. _chainKeys$2.length = 0;
  38174. if ( groupData.version !== groupNode.version ) {
  38175. groupData.version = groupNode.version;
  38176. return true;
  38177. }
  38178. return false;
  38179. }
  38180. /**
  38181. * Returns the cache key for the given render object.
  38182. *
  38183. * @param {RenderObject} renderObject - The render object.
  38184. * @return {number} The cache key.
  38185. */
  38186. getForRenderCacheKey( renderObject ) {
  38187. return renderObject.initialCacheKey;
  38188. }
  38189. /**
  38190. * Returns a node builder state for the given render object.
  38191. *
  38192. * @param {RenderObject} renderObject - The render object.
  38193. * @return {NodeBuilderState} The node builder state.
  38194. */
  38195. getForRender( renderObject ) {
  38196. const renderObjectData = this.get( renderObject );
  38197. let nodeBuilderState = renderObjectData.nodeBuilderState;
  38198. if ( nodeBuilderState === undefined ) {
  38199. const { nodeBuilderCache } = this;
  38200. const cacheKey = this.getForRenderCacheKey( renderObject );
  38201. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  38202. if ( nodeBuilderState === undefined ) {
  38203. const createNodeBuilder = ( material ) => {
  38204. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  38205. nodeBuilder.scene = renderObject.scene;
  38206. nodeBuilder.material = material;
  38207. nodeBuilder.camera = renderObject.camera;
  38208. nodeBuilder.context.material = material;
  38209. nodeBuilder.lightsNode = renderObject.lightsNode;
  38210. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  38211. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  38212. nodeBuilder.clippingContext = renderObject.clippingContext;
  38213. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  38214. nodeBuilder.enableMultiview();
  38215. }
  38216. return nodeBuilder;
  38217. };
  38218. let nodeBuilder = createNodeBuilder( renderObject.material );
  38219. try {
  38220. nodeBuilder.build();
  38221. } catch ( e ) {
  38222. nodeBuilder = createNodeBuilder( new NodeMaterial() );
  38223. nodeBuilder.build();
  38224. error( 'TSL: ' + e );
  38225. }
  38226. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  38227. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  38228. }
  38229. nodeBuilderState.usedTimes ++;
  38230. renderObjectData.nodeBuilderState = nodeBuilderState;
  38231. }
  38232. return nodeBuilderState;
  38233. }
  38234. /**
  38235. * Deletes the given object from the internal data map
  38236. *
  38237. * @param {any} object - The object to delete.
  38238. * @return {?Object} The deleted dictionary.
  38239. */
  38240. delete( object ) {
  38241. if ( object.isRenderObject ) {
  38242. const nodeBuilderState = this.get( object ).nodeBuilderState;
  38243. nodeBuilderState.usedTimes --;
  38244. if ( nodeBuilderState.usedTimes === 0 ) {
  38245. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  38246. }
  38247. }
  38248. return super.delete( object );
  38249. }
  38250. /**
  38251. * Returns a node builder state for the given compute node.
  38252. *
  38253. * @param {Node} computeNode - The compute node.
  38254. * @return {NodeBuilderState} The node builder state.
  38255. */
  38256. getForCompute( computeNode ) {
  38257. const computeData = this.get( computeNode );
  38258. let nodeBuilderState = computeData.nodeBuilderState;
  38259. if ( nodeBuilderState === undefined ) {
  38260. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  38261. nodeBuilder.build();
  38262. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  38263. computeData.nodeBuilderState = nodeBuilderState;
  38264. }
  38265. return nodeBuilderState;
  38266. }
  38267. /**
  38268. * Creates a node builder state for the given node builder.
  38269. *
  38270. * @private
  38271. * @param {NodeBuilder} nodeBuilder - The node builder.
  38272. * @return {NodeBuilderState} The node builder state.
  38273. */
  38274. _createNodeBuilderState( nodeBuilder ) {
  38275. return new NodeBuilderState(
  38276. nodeBuilder.vertexShader,
  38277. nodeBuilder.fragmentShader,
  38278. nodeBuilder.computeShader,
  38279. nodeBuilder.getAttributesArray(),
  38280. nodeBuilder.getBindings(),
  38281. nodeBuilder.updateNodes,
  38282. nodeBuilder.updateBeforeNodes,
  38283. nodeBuilder.updateAfterNodes,
  38284. nodeBuilder.observer,
  38285. nodeBuilder.transforms
  38286. );
  38287. }
  38288. /**
  38289. * Returns an environment node for the current configured
  38290. * scene environment.
  38291. *
  38292. * @param {Scene} scene - The scene.
  38293. * @return {Node} A node representing the current scene environment.
  38294. */
  38295. getEnvironmentNode( scene ) {
  38296. this.updateEnvironment( scene );
  38297. let environmentNode = null;
  38298. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  38299. environmentNode = scene.environmentNode;
  38300. } else {
  38301. const sceneData = this.get( scene );
  38302. if ( sceneData.environmentNode ) {
  38303. environmentNode = sceneData.environmentNode;
  38304. }
  38305. }
  38306. return environmentNode;
  38307. }
  38308. /**
  38309. * Returns a background node for the current configured
  38310. * scene background.
  38311. *
  38312. * @param {Scene} scene - The scene.
  38313. * @return {Node} A node representing the current scene background.
  38314. */
  38315. getBackgroundNode( scene ) {
  38316. this.updateBackground( scene );
  38317. let backgroundNode = null;
  38318. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  38319. backgroundNode = scene.backgroundNode;
  38320. } else {
  38321. const sceneData = this.get( scene );
  38322. if ( sceneData.backgroundNode ) {
  38323. backgroundNode = sceneData.backgroundNode;
  38324. }
  38325. }
  38326. return backgroundNode;
  38327. }
  38328. /**
  38329. * Returns a fog node for the current configured scene fog.
  38330. *
  38331. * @param {Scene} scene - The scene.
  38332. * @return {Node} A node representing the current scene fog.
  38333. */
  38334. getFogNode( scene ) {
  38335. this.updateFog( scene );
  38336. return scene.fogNode || this.get( scene ).fogNode || null;
  38337. }
  38338. /**
  38339. * Returns a cache key for the given scene and lights node.
  38340. * This key is used by `RenderObject` as a part of the dynamic
  38341. * cache key (a key that must be checked every time the render
  38342. * objects is drawn).
  38343. *
  38344. * @param {Scene} scene - The scene.
  38345. * @param {LightsNode} lightsNode - The lights node.
  38346. * @return {number} The cache key.
  38347. */
  38348. getCacheKey( scene, lightsNode ) {
  38349. _chainKeys$2[ 0 ] = scene;
  38350. _chainKeys$2[ 1 ] = lightsNode;
  38351. const callId = this.renderer.info.calls;
  38352. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  38353. if ( cacheKeyData.callId !== callId ) {
  38354. const environmentNode = this.getEnvironmentNode( scene );
  38355. const fogNode = this.getFogNode( scene );
  38356. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  38357. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  38358. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  38359. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  38360. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  38361. _cacheKeyValues.push( this.renderer.shadowMap.type );
  38362. cacheKeyData.callId = callId;
  38363. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  38364. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  38365. _cacheKeyValues.length = 0;
  38366. }
  38367. _chainKeys$2.length = 0;
  38368. return cacheKeyData.cacheKey;
  38369. }
  38370. /**
  38371. * A boolean that indicates whether tone mapping should be enabled
  38372. * or not.
  38373. *
  38374. * @type {boolean}
  38375. */
  38376. get isToneMappingState() {
  38377. return this.renderer.getRenderTarget() ? false : true;
  38378. }
  38379. /**
  38380. * If a scene background is configured, this method makes sure to
  38381. * represent the background with a corresponding node-based implementation.
  38382. *
  38383. * @param {Scene} scene - The scene.
  38384. */
  38385. updateBackground( scene ) {
  38386. const sceneData = this.get( scene );
  38387. const background = scene.background;
  38388. if ( background ) {
  38389. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  38390. if ( sceneData.background !== background || forceUpdate ) {
  38391. const backgroundNode = this.getCacheNode( 'background', background, () => {
  38392. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  38393. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  38394. return pmremTexture( background );
  38395. } else {
  38396. let envMap;
  38397. if ( background.isCubeTexture === true ) {
  38398. envMap = cubeTexture( background );
  38399. } else {
  38400. envMap = texture( background );
  38401. }
  38402. return cubeMapNode( envMap );
  38403. }
  38404. } else if ( background.isTexture === true ) {
  38405. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  38406. } else if ( background.isColor !== true ) {
  38407. error( 'WebGPUNodes: Unsupported background configuration.', background );
  38408. }
  38409. }, forceUpdate );
  38410. sceneData.backgroundNode = backgroundNode;
  38411. sceneData.background = background;
  38412. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  38413. }
  38414. } else if ( sceneData.backgroundNode ) {
  38415. delete sceneData.backgroundNode;
  38416. delete sceneData.background;
  38417. }
  38418. }
  38419. /**
  38420. * This method is part of the caching of nodes which are used to represents the
  38421. * scene's background, fog or environment.
  38422. *
  38423. * @param {string} type - The type of object to cache.
  38424. * @param {Object} object - The object.
  38425. * @param {Function} callback - A callback that produces a node representation for the given object.
  38426. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  38427. * @return {Node} The node representation.
  38428. */
  38429. getCacheNode( type, object, callback, forceUpdate = false ) {
  38430. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  38431. let node = nodeCache.get( object );
  38432. if ( node === undefined || forceUpdate ) {
  38433. node = callback();
  38434. nodeCache.set( object, node );
  38435. }
  38436. return node;
  38437. }
  38438. /**
  38439. * If a scene fog is configured, this method makes sure to
  38440. * represent the fog with a corresponding node-based implementation.
  38441. *
  38442. * @param {Scene} scene - The scene.
  38443. */
  38444. updateFog( scene ) {
  38445. const sceneData = this.get( scene );
  38446. const sceneFog = scene.fog;
  38447. if ( sceneFog ) {
  38448. if ( sceneData.fog !== sceneFog ) {
  38449. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  38450. if ( sceneFog.isFogExp2 ) {
  38451. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  38452. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  38453. return fog( color, densityFogFactor( density ) );
  38454. } else if ( sceneFog.isFog ) {
  38455. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  38456. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  38457. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  38458. return fog( color, rangeFogFactor( near, far ) );
  38459. } else {
  38460. error( 'Renderer: Unsupported fog configuration.', sceneFog );
  38461. }
  38462. } );
  38463. sceneData.fogNode = fogNode;
  38464. sceneData.fog = sceneFog;
  38465. }
  38466. } else {
  38467. delete sceneData.fogNode;
  38468. delete sceneData.fog;
  38469. }
  38470. }
  38471. /**
  38472. * If a scene environment is configured, this method makes sure to
  38473. * represent the environment with a corresponding node-based implementation.
  38474. *
  38475. * @param {Scene} scene - The scene.
  38476. */
  38477. updateEnvironment( scene ) {
  38478. const sceneData = this.get( scene );
  38479. const environment = scene.environment;
  38480. if ( environment ) {
  38481. if ( sceneData.environment !== environment ) {
  38482. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  38483. if ( environment.isCubeTexture === true ) {
  38484. return cubeTexture( environment );
  38485. } else if ( environment.isTexture === true ) {
  38486. return texture( environment );
  38487. } else {
  38488. error( 'Nodes: Unsupported environment configuration.', environment );
  38489. }
  38490. } );
  38491. sceneData.environmentNode = environmentNode;
  38492. sceneData.environment = environment;
  38493. }
  38494. } else if ( sceneData.environmentNode ) {
  38495. delete sceneData.environmentNode;
  38496. delete sceneData.environment;
  38497. }
  38498. }
  38499. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  38500. const nodeFrame = this.nodeFrame;
  38501. nodeFrame.renderer = renderer;
  38502. nodeFrame.scene = scene;
  38503. nodeFrame.object = object;
  38504. nodeFrame.camera = camera;
  38505. nodeFrame.material = material;
  38506. return nodeFrame;
  38507. }
  38508. getNodeFrameForRender( renderObject ) {
  38509. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  38510. }
  38511. /**
  38512. * Returns the current output cache key.
  38513. *
  38514. * @return {string} The output cache key.
  38515. */
  38516. getOutputCacheKey() {
  38517. const renderer = this.renderer;
  38518. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  38519. }
  38520. /**
  38521. * Checks if the output configuration (tone mapping and color space) for
  38522. * the given target has changed.
  38523. *
  38524. * @param {Texture} outputTarget - The output target.
  38525. * @return {boolean} Whether the output configuration has changed or not.
  38526. */
  38527. hasOutputChange( outputTarget ) {
  38528. const cacheKey = _outputNodeMap.get( outputTarget );
  38529. return cacheKey !== this.getOutputCacheKey();
  38530. }
  38531. /**
  38532. * Returns a node that represents the output configuration (tone mapping and
  38533. * color space) for the current target.
  38534. *
  38535. * @param {Texture} outputTarget - The output target.
  38536. * @return {Node} The output node.
  38537. */
  38538. getOutputNode( outputTarget ) {
  38539. const renderer = this.renderer;
  38540. const cacheKey = this.getOutputCacheKey();
  38541. const output = outputTarget.isArrayTexture ?
  38542. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  38543. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  38544. _outputNodeMap.set( outputTarget, cacheKey );
  38545. return output;
  38546. }
  38547. /**
  38548. * Triggers the call of `updateBefore()` methods
  38549. * for all nodes of the given render object.
  38550. *
  38551. * @param {RenderObject} renderObject - The render object.
  38552. */
  38553. updateBefore( renderObject ) {
  38554. const nodeBuilder = renderObject.getNodeBuilderState();
  38555. for ( const node of nodeBuilder.updateBeforeNodes ) {
  38556. // update frame state for each node
  38557. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  38558. }
  38559. }
  38560. /**
  38561. * Triggers the call of `updateAfter()` methods
  38562. * for all nodes of the given render object.
  38563. *
  38564. * @param {RenderObject} renderObject - The render object.
  38565. */
  38566. updateAfter( renderObject ) {
  38567. const nodeBuilder = renderObject.getNodeBuilderState();
  38568. for ( const node of nodeBuilder.updateAfterNodes ) {
  38569. // update frame state for each node
  38570. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  38571. }
  38572. }
  38573. /**
  38574. * Triggers the call of `update()` methods
  38575. * for all nodes of the given compute node.
  38576. *
  38577. * @param {Node} computeNode - The compute node.
  38578. */
  38579. updateForCompute( computeNode ) {
  38580. const nodeFrame = this.getNodeFrame();
  38581. const nodeBuilder = this.getForCompute( computeNode );
  38582. for ( const node of nodeBuilder.updateNodes ) {
  38583. nodeFrame.updateNode( node );
  38584. }
  38585. }
  38586. /**
  38587. * Triggers the call of `update()` methods
  38588. * for all nodes of the given compute node.
  38589. *
  38590. * @param {RenderObject} renderObject - The render object.
  38591. */
  38592. updateForRender( renderObject ) {
  38593. const nodeFrame = this.getNodeFrameForRender( renderObject );
  38594. const nodeBuilder = renderObject.getNodeBuilderState();
  38595. for ( const node of nodeBuilder.updateNodes ) {
  38596. nodeFrame.updateNode( node );
  38597. }
  38598. }
  38599. /**
  38600. * Returns `true` if the given render object requires a refresh.
  38601. *
  38602. * @param {RenderObject} renderObject - The render object.
  38603. * @return {boolean} Whether the given render object requires a refresh or not.
  38604. */
  38605. needsRefresh( renderObject ) {
  38606. const nodeFrame = this.getNodeFrameForRender( renderObject );
  38607. const monitor = renderObject.getMonitor();
  38608. return monitor.needsRefresh( renderObject, nodeFrame );
  38609. }
  38610. /**
  38611. * Frees the internal resources.
  38612. */
  38613. dispose() {
  38614. super.dispose();
  38615. this.nodeFrame = new NodeFrame();
  38616. this.nodeBuilderCache = new Map();
  38617. this.cacheLib = {};
  38618. }
  38619. }
  38620. const _plane = /*@__PURE__*/ new Plane();
  38621. /**
  38622. * Represents the state that is used to perform clipping via clipping planes.
  38623. * There is a default clipping context for each render context. When the
  38624. * scene holds instances of `ClippingGroup`, there will be a context for each
  38625. * group.
  38626. *
  38627. * @private
  38628. */
  38629. class ClippingContext {
  38630. /**
  38631. * Constructs a new clipping context.
  38632. *
  38633. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  38634. */
  38635. constructor( parentContext = null ) {
  38636. /**
  38637. * The clipping context's version.
  38638. *
  38639. * @type {number}
  38640. * @readonly
  38641. */
  38642. this.version = 0;
  38643. /**
  38644. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  38645. *
  38646. * @type {?boolean}
  38647. * @default null
  38648. */
  38649. this.clipIntersection = null;
  38650. /**
  38651. * The clipping context's cache key.
  38652. *
  38653. * @type {string}
  38654. */
  38655. this.cacheKey = '';
  38656. /**
  38657. * Whether the shadow pass is active or not.
  38658. *
  38659. * @type {boolean}
  38660. * @default false
  38661. */
  38662. this.shadowPass = false;
  38663. /**
  38664. * The view normal matrix.
  38665. *
  38666. * @type {Matrix3}
  38667. */
  38668. this.viewNormalMatrix = new Matrix3();
  38669. /**
  38670. * Internal cache for maintaining clipping contexts.
  38671. *
  38672. * @type {WeakMap<ClippingGroup,ClippingContext>}
  38673. */
  38674. this.clippingGroupContexts = new WeakMap();
  38675. /**
  38676. * The intersection planes.
  38677. *
  38678. * @type {Array<Vector4>}
  38679. */
  38680. this.intersectionPlanes = [];
  38681. /**
  38682. * The intersection planes.
  38683. *
  38684. * @type {Array<Vector4>}
  38685. */
  38686. this.unionPlanes = [];
  38687. /**
  38688. * The version of the clipping context's parent context.
  38689. *
  38690. * @type {?number}
  38691. * @readonly
  38692. */
  38693. this.parentVersion = null;
  38694. if ( parentContext !== null ) {
  38695. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  38696. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  38697. this.shadowPass = parentContext.shadowPass;
  38698. this.viewMatrix = parentContext.viewMatrix;
  38699. }
  38700. }
  38701. /**
  38702. * Projects the given source clipping planes and writes the result into the
  38703. * destination array.
  38704. *
  38705. * @param {Array<Plane>} source - The source clipping planes.
  38706. * @param {Array<Vector4>} destination - The destination.
  38707. * @param {number} offset - The offset.
  38708. */
  38709. projectPlanes( source, destination, offset ) {
  38710. const l = source.length;
  38711. for ( let i = 0; i < l; i ++ ) {
  38712. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  38713. const v = destination[ offset + i ];
  38714. const normal = _plane.normal;
  38715. v.x = - normal.x;
  38716. v.y = - normal.y;
  38717. v.z = - normal.z;
  38718. v.w = _plane.constant;
  38719. }
  38720. }
  38721. /**
  38722. * Updates the root clipping context of a scene.
  38723. *
  38724. * @param {Scene} scene - The scene.
  38725. * @param {Camera} camera - The camera that is used to render the scene.
  38726. */
  38727. updateGlobal( scene, camera ) {
  38728. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  38729. this.viewMatrix = camera.matrixWorldInverse;
  38730. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  38731. }
  38732. /**
  38733. * Updates the clipping context.
  38734. *
  38735. * @param {ClippingContext} parentContext - The parent context.
  38736. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  38737. */
  38738. update( parentContext, clippingGroup ) {
  38739. let update = false;
  38740. if ( parentContext.version !== this.parentVersion ) {
  38741. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  38742. this.unionPlanes = Array.from( parentContext.unionPlanes );
  38743. this.parentVersion = parentContext.version;
  38744. }
  38745. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  38746. this.clipIntersection = clippingGroup.clipIntersection;
  38747. if ( this.clipIntersection ) {
  38748. this.unionPlanes.length = parentContext.unionPlanes.length;
  38749. } else {
  38750. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  38751. }
  38752. }
  38753. const srcClippingPlanes = clippingGroup.clippingPlanes;
  38754. const l = srcClippingPlanes.length;
  38755. let dstClippingPlanes;
  38756. let offset;
  38757. if ( this.clipIntersection ) {
  38758. dstClippingPlanes = this.intersectionPlanes;
  38759. offset = parentContext.intersectionPlanes.length;
  38760. } else {
  38761. dstClippingPlanes = this.unionPlanes;
  38762. offset = parentContext.unionPlanes.length;
  38763. }
  38764. if ( dstClippingPlanes.length !== offset + l ) {
  38765. dstClippingPlanes.length = offset + l;
  38766. for ( let i = 0; i < l; i ++ ) {
  38767. dstClippingPlanes[ offset + i ] = new Vector4();
  38768. }
  38769. update = true;
  38770. }
  38771. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  38772. if ( update ) {
  38773. this.version ++;
  38774. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  38775. }
  38776. }
  38777. /**
  38778. * Returns a clipping context for the given clipping group.
  38779. *
  38780. * @param {ClippingGroup} clippingGroup - The clipping group.
  38781. * @return {ClippingContext} The clipping context.
  38782. */
  38783. getGroupContext( clippingGroup ) {
  38784. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  38785. let context = this.clippingGroupContexts.get( clippingGroup );
  38786. if ( context === undefined ) {
  38787. context = new ClippingContext( this );
  38788. this.clippingGroupContexts.set( clippingGroup, context );
  38789. }
  38790. context.update( this, clippingGroup );
  38791. return context;
  38792. }
  38793. /**
  38794. * The count of union clipping planes.
  38795. *
  38796. * @type {number}
  38797. * @readonly
  38798. */
  38799. get unionClippingCount() {
  38800. return this.unionPlanes.length;
  38801. }
  38802. }
  38803. /**
  38804. * This module is used to represent render bundles inside the renderer
  38805. * for further processing.
  38806. *
  38807. * @private
  38808. */
  38809. class RenderBundle {
  38810. /**
  38811. * Constructs a new bundle group.
  38812. *
  38813. * @param {BundleGroup} bundleGroup - The bundle group.
  38814. * @param {Camera} camera - The camera the bundle group is rendered with.
  38815. */
  38816. constructor( bundleGroup, camera ) {
  38817. this.bundleGroup = bundleGroup;
  38818. this.camera = camera;
  38819. }
  38820. }
  38821. const _chainKeys$1 = [];
  38822. /**
  38823. * This renderer module manages render bundles.
  38824. *
  38825. * @private
  38826. */
  38827. class RenderBundles {
  38828. /**
  38829. * Constructs a new render bundle management component.
  38830. */
  38831. constructor() {
  38832. /**
  38833. * A chain map for maintaining the render bundles.
  38834. *
  38835. * @type {ChainMap}
  38836. */
  38837. this.bundles = new ChainMap();
  38838. }
  38839. /**
  38840. * Returns a render bundle for the given bundle group and camera.
  38841. *
  38842. * @param {BundleGroup} bundleGroup - The bundle group.
  38843. * @param {Camera} camera - The camera the bundle group is rendered with.
  38844. * @return {RenderBundle} The render bundle.
  38845. */
  38846. get( bundleGroup, camera ) {
  38847. const bundles = this.bundles;
  38848. _chainKeys$1[ 0 ] = bundleGroup;
  38849. _chainKeys$1[ 1 ] = camera;
  38850. let bundle = bundles.get( _chainKeys$1 );
  38851. if ( bundle === undefined ) {
  38852. bundle = new RenderBundle( bundleGroup, camera );
  38853. bundles.set( _chainKeys$1, bundle );
  38854. }
  38855. _chainKeys$1.length = 0;
  38856. return bundle;
  38857. }
  38858. /**
  38859. * Frees all internal resources.
  38860. */
  38861. dispose() {
  38862. this.bundles = new ChainMap();
  38863. }
  38864. }
  38865. /**
  38866. * The purpose of a node library is to assign node implementations
  38867. * to existing library features. In `WebGPURenderer` lights, materials
  38868. * which are not based on `NodeMaterial` as well as tone mapping techniques
  38869. * are implemented with node-based modules.
  38870. *
  38871. * @private
  38872. */
  38873. class NodeLibrary {
  38874. /**
  38875. * Constructs a new node library.
  38876. */
  38877. constructor() {
  38878. /**
  38879. * A weak map that maps lights to light nodes.
  38880. *
  38881. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  38882. */
  38883. this.lightNodes = new WeakMap();
  38884. /**
  38885. * A map that maps materials to node materials.
  38886. *
  38887. * @type {Map<string,NodeMaterial.constructor>}
  38888. */
  38889. this.materialNodes = new Map();
  38890. /**
  38891. * A map that maps tone mapping techniques (constants)
  38892. * to tone mapping node functions.
  38893. *
  38894. * @type {Map<number,Function>}
  38895. */
  38896. this.toneMappingNodes = new Map();
  38897. }
  38898. /**
  38899. * Returns a matching node material instance for the given material object.
  38900. *
  38901. * This method also assigns/copies the properties of the given material object
  38902. * to the node material. This is done to make sure the current material
  38903. * configuration carries over to the node version.
  38904. *
  38905. * @param {Material} material - A material.
  38906. * @return {NodeMaterial} The corresponding node material.
  38907. */
  38908. fromMaterial( material ) {
  38909. if ( material.isNodeMaterial ) return material;
  38910. let nodeMaterial = null;
  38911. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  38912. if ( nodeMaterialClass !== null ) {
  38913. nodeMaterial = new nodeMaterialClass();
  38914. for ( const key in material ) {
  38915. nodeMaterial[ key ] = material[ key ];
  38916. }
  38917. }
  38918. return nodeMaterial;
  38919. }
  38920. /**
  38921. * Adds a tone mapping node function for a tone mapping technique (constant).
  38922. *
  38923. * @param {Function} toneMappingNode - The tone mapping node function.
  38924. * @param {number} toneMapping - The tone mapping.
  38925. */
  38926. addToneMapping( toneMappingNode, toneMapping ) {
  38927. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  38928. }
  38929. /**
  38930. * Returns a tone mapping node function for a tone mapping technique (constant).
  38931. *
  38932. * @param {number} toneMapping - The tone mapping.
  38933. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  38934. */
  38935. getToneMappingFunction( toneMapping ) {
  38936. return this.toneMappingNodes.get( toneMapping ) || null;
  38937. }
  38938. /**
  38939. * Returns a node material class definition for a material type.
  38940. *
  38941. * @param {string} materialType - The material type.
  38942. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  38943. */
  38944. getMaterialNodeClass( materialType ) {
  38945. return this.materialNodes.get( materialType ) || null;
  38946. }
  38947. /**
  38948. * Adds a node material class definition for a given material type.
  38949. *
  38950. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  38951. * @param {string} materialClassType - The material type.
  38952. */
  38953. addMaterial( materialNodeClass, materialClassType ) {
  38954. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  38955. }
  38956. /**
  38957. * Returns a light node class definition for a light class definition.
  38958. *
  38959. * @param {Light.constructor} light - The light class definition.
  38960. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  38961. */
  38962. getLightNodeClass( light ) {
  38963. return this.lightNodes.get( light ) || null;
  38964. }
  38965. /**
  38966. * Adds a light node class definition for a given light class definition.
  38967. *
  38968. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  38969. * @param {Light.constructor} lightClass - The light class definition.
  38970. */
  38971. addLight( lightNodeClass, lightClass ) {
  38972. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  38973. }
  38974. /**
  38975. * Adds a node class definition for the given type to the provided type library.
  38976. *
  38977. * @param {Node.constructor} nodeClass - The node class definition.
  38978. * @param {number|string} type - The object type.
  38979. * @param {Map<number|string,Node.constructor>} library - The type library.
  38980. */
  38981. addType( nodeClass, type, library ) {
  38982. if ( library.has( type ) ) {
  38983. warn( `Redefinition of node ${ type }` );
  38984. return;
  38985. }
  38986. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  38987. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  38988. library.set( type, nodeClass );
  38989. }
  38990. /**
  38991. * Adds a node class definition for the given class definition to the provided type library.
  38992. *
  38993. * @param {Node.constructor} nodeClass - The node class definition.
  38994. * @param {Node.constructor} baseClass - The class definition.
  38995. * @param {WeakMap<Node.constructor, Node.constructor>} library - The type library.
  38996. */
  38997. addClass( nodeClass, baseClass, library ) {
  38998. if ( library.has( baseClass ) ) {
  38999. warn( `Redefinition of node ${ baseClass.name }` );
  39000. return;
  39001. }
  39002. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  39003. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  39004. library.set( baseClass, nodeClass );
  39005. }
  39006. }
  39007. const _defaultLights = /*@__PURE__*/ new LightsNode();
  39008. const _chainKeys = [];
  39009. /**
  39010. * This renderer module manages the lights nodes which are unique
  39011. * per scene and camera combination.
  39012. *
  39013. * The lights node itself is later configured in the render list
  39014. * with the actual lights from the scene.
  39015. *
  39016. * @private
  39017. * @augments ChainMap
  39018. */
  39019. class Lighting extends ChainMap {
  39020. /**
  39021. * Constructs a lighting management component.
  39022. */
  39023. constructor() {
  39024. super();
  39025. }
  39026. /**
  39027. * Creates a new lights node for the given array of lights.
  39028. *
  39029. * @param {Array<Light>} lights - The render object.
  39030. * @return {LightsNode} The lights node.
  39031. */
  39032. createNode( lights = [] ) {
  39033. return new LightsNode().setLights( lights );
  39034. }
  39035. /**
  39036. * Returns a lights node for the given scene and camera.
  39037. *
  39038. * @param {Scene} scene - The scene.
  39039. * @param {Camera} camera - The camera.
  39040. * @return {LightsNode} The lights node.
  39041. */
  39042. getNode( scene, camera ) {
  39043. // ignore post-processing
  39044. if ( scene.isQuadMesh ) return _defaultLights;
  39045. _chainKeys[ 0 ] = scene;
  39046. _chainKeys[ 1 ] = camera;
  39047. let node = this.get( _chainKeys );
  39048. if ( node === undefined ) {
  39049. node = this.createNode();
  39050. this.set( _chainKeys, node );
  39051. }
  39052. _chainKeys.length = 0;
  39053. return node;
  39054. }
  39055. }
  39056. /**
  39057. * A special type of render target that is used when rendering
  39058. * with the WebXR Device API.
  39059. *
  39060. * @private
  39061. * @augments RenderTarget
  39062. */
  39063. class XRRenderTarget extends RenderTarget {
  39064. /**
  39065. * Constructs a new XR render target.
  39066. *
  39067. * @param {number} [width=1] - The width of the render target.
  39068. * @param {number} [height=1] - The height of the render target.
  39069. * @param {Object} [options={}] - The configuration options.
  39070. */
  39071. constructor( width = 1, height = 1, options = {} ) {
  39072. super( width, height, options );
  39073. /**
  39074. * This flag can be used for type testing.
  39075. *
  39076. * @type {boolean}
  39077. * @readonly
  39078. * @default true
  39079. */
  39080. this.isXRRenderTarget = true;
  39081. /**
  39082. * Whether the attachments of the render target
  39083. * are defined by external textures. This flag is
  39084. * set to `true` when using the WebXR Layers API.
  39085. *
  39086. * @private
  39087. * @type {boolean}
  39088. * @default false
  39089. */
  39090. this._hasExternalTextures = false;
  39091. /**
  39092. * Whether a depth buffer should automatically be allocated
  39093. * for this XR render target or not.
  39094. *
  39095. * Allocating a depth buffer is the default behavior of XR render
  39096. * targets. However, when using the WebXR Layers API, this flag
  39097. * must be set to `false` when the `ignoreDepthValues` property of
  39098. * the projection layers evaluates to `false`.
  39099. *
  39100. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  39101. *
  39102. * @private
  39103. * @type {boolean}
  39104. * @default true
  39105. */
  39106. this._autoAllocateDepthBuffer = true;
  39107. /**
  39108. * Whether this render target is associated with a XRWebGLLayer.
  39109. *
  39110. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  39111. * this means that you don't have access to its bound color,
  39112. * stencil and depth buffers. We need to handle this framebuffer
  39113. * differently since its textures are always bound.
  39114. *
  39115. * @private
  39116. * @type {boolean}
  39117. * @default false
  39118. * */
  39119. this._isOpaqueFramebuffer = false;
  39120. }
  39121. copy( source ) {
  39122. super.copy( source );
  39123. this._hasExternalTextures = source._hasExternalTextures;
  39124. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  39125. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  39126. return this;
  39127. }
  39128. }
  39129. const _cameraLPos = /*@__PURE__*/ new Vector3();
  39130. const _cameraRPos = /*@__PURE__*/ new Vector3();
  39131. /**
  39132. * The XR manager is built on top of the WebXR Device API to
  39133. * manage XR sessions with `WebGPURenderer`.
  39134. *
  39135. * XR is currently only supported with a WebGL 2 backend.
  39136. *
  39137. * @augments EventDispatcher
  39138. */
  39139. class XRManager extends EventDispatcher {
  39140. /**
  39141. * Constructs a new XR manager.
  39142. *
  39143. * @param {Renderer} renderer - The renderer.
  39144. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  39145. */
  39146. constructor( renderer, multiview = false ) {
  39147. super();
  39148. /**
  39149. * This flag globally enables XR rendering.
  39150. *
  39151. * @type {boolean}
  39152. * @default false
  39153. */
  39154. this.enabled = false;
  39155. /**
  39156. * Whether the XR device is currently presenting or not.
  39157. *
  39158. * @type {boolean}
  39159. * @default false
  39160. * @readonly
  39161. */
  39162. this.isPresenting = false;
  39163. /**
  39164. * Whether the XR camera should automatically be updated or not.
  39165. *
  39166. * @type {boolean}
  39167. * @default true
  39168. */
  39169. this.cameraAutoUpdate = true;
  39170. /**
  39171. * The renderer.
  39172. *
  39173. * @private
  39174. * @type {Renderer}
  39175. */
  39176. this._renderer = renderer;
  39177. // camera
  39178. /**
  39179. * Represents the camera for the left eye.
  39180. *
  39181. * @private
  39182. * @type {PerspectiveCamera}
  39183. */
  39184. this._cameraL = new PerspectiveCamera();
  39185. this._cameraL.viewport = new Vector4();
  39186. /**
  39187. * Represents the camera for the right eye.
  39188. *
  39189. * @private
  39190. * @type {PerspectiveCamera}
  39191. */
  39192. this._cameraR = new PerspectiveCamera();
  39193. this._cameraR.viewport = new Vector4();
  39194. /**
  39195. * A list of cameras used for rendering the XR views.
  39196. *
  39197. * @private
  39198. * @type {Array<Camera>}
  39199. */
  39200. this._cameras = [ this._cameraL, this._cameraR ];
  39201. /**
  39202. * The main XR camera.
  39203. *
  39204. * @private
  39205. * @type {ArrayCamera}
  39206. */
  39207. this._cameraXR = new ArrayCamera();
  39208. /**
  39209. * The current near value of the XR camera.
  39210. *
  39211. * @private
  39212. * @type {?number}
  39213. * @default null
  39214. */
  39215. this._currentDepthNear = null;
  39216. /**
  39217. * The current far value of the XR camera.
  39218. *
  39219. * @private
  39220. * @type {?number}
  39221. * @default null
  39222. */
  39223. this._currentDepthFar = null;
  39224. /**
  39225. * A list of WebXR controllers requested by the application.
  39226. *
  39227. * @private
  39228. * @type {Array<WebXRController>}
  39229. */
  39230. this._controllers = [];
  39231. /**
  39232. * A list of XR input source. Each input source belongs to
  39233. * an instance of WebXRController.
  39234. *
  39235. * @private
  39236. * @type {Array<XRInputSource?>}
  39237. */
  39238. this._controllerInputSources = [];
  39239. /**
  39240. * The XR render target that represents the rendering destination
  39241. * during an active XR session.
  39242. *
  39243. * @private
  39244. * @type {?RenderTarget}
  39245. * @default null
  39246. */
  39247. this._xrRenderTarget = null;
  39248. /**
  39249. * An array holding all the non-projection layers
  39250. *
  39251. * @private
  39252. * @type {Array<Object>}
  39253. * @default []
  39254. */
  39255. this._layers = [];
  39256. /**
  39257. * Whether the XR session uses layers.
  39258. *
  39259. * @private
  39260. * @type {boolean}
  39261. * @default false
  39262. */
  39263. this._sessionUsesLayers = false;
  39264. /**
  39265. * Whether the device supports binding gl objects.
  39266. *
  39267. * @private
  39268. * @type {boolean}
  39269. * @readonly
  39270. */
  39271. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  39272. this._frameBufferTargets = null;
  39273. /**
  39274. * Helper function to create native WebXR Layer.
  39275. *
  39276. * @private
  39277. * @type {Function}
  39278. */
  39279. this._createXRLayer = createXRLayer.bind( this );
  39280. /**
  39281. * The current WebGL context.
  39282. *
  39283. * @private
  39284. * @type {?WebGL2RenderingContext}
  39285. * @default null
  39286. */
  39287. this._gl = null;
  39288. /**
  39289. * The current animation context.
  39290. *
  39291. * @private
  39292. * @type {?Window}
  39293. * @default null
  39294. */
  39295. this._currentAnimationContext = null;
  39296. /**
  39297. * The current animation loop.
  39298. *
  39299. * @private
  39300. * @type {?Function}
  39301. * @default null
  39302. */
  39303. this._currentAnimationLoop = null;
  39304. /**
  39305. * The current pixel ratio.
  39306. *
  39307. * @private
  39308. * @type {?number}
  39309. * @default null
  39310. */
  39311. this._currentPixelRatio = null;
  39312. /**
  39313. * The current size of the renderer's canvas
  39314. * in logical pixel unit.
  39315. *
  39316. * @private
  39317. * @type {Vector2}
  39318. */
  39319. this._currentSize = new Vector2();
  39320. /**
  39321. * The default event listener for handling events inside a XR session.
  39322. *
  39323. * @private
  39324. * @type {Function}
  39325. */
  39326. this._onSessionEvent = onSessionEvent.bind( this );
  39327. /**
  39328. * The event listener for handling the end of a XR session.
  39329. *
  39330. * @private
  39331. * @type {Function}
  39332. */
  39333. this._onSessionEnd = onSessionEnd.bind( this );
  39334. /**
  39335. * The event listener for handling the `inputsourceschange` event.
  39336. *
  39337. * @private
  39338. * @type {Function}
  39339. */
  39340. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  39341. /**
  39342. * The animation loop which is used as a replacement for the default
  39343. * animation loop of the application. It is only used when a XR session
  39344. * is active.
  39345. *
  39346. * @private
  39347. * @type {Function}
  39348. */
  39349. this._onAnimationFrame = onAnimationFrame.bind( this );
  39350. /**
  39351. * The current XR reference space.
  39352. *
  39353. * @private
  39354. * @type {?XRReferenceSpace}
  39355. * @default null
  39356. */
  39357. this._referenceSpace = null;
  39358. /**
  39359. * The current XR reference space type.
  39360. *
  39361. * @private
  39362. * @type {XRReferenceSpaceType}
  39363. * @default 'local-floor'
  39364. */
  39365. this._referenceSpaceType = 'local-floor';
  39366. /**
  39367. * A custom reference space defined by the application.
  39368. *
  39369. * @private
  39370. * @type {?XRReferenceSpace}
  39371. * @default null
  39372. */
  39373. this._customReferenceSpace = null;
  39374. /**
  39375. * The framebuffer scale factor.
  39376. *
  39377. * @private
  39378. * @type {number}
  39379. * @default 1
  39380. */
  39381. this._framebufferScaleFactor = 1;
  39382. /**
  39383. * The foveation factor.
  39384. *
  39385. * @private
  39386. * @type {number}
  39387. * @default 1
  39388. */
  39389. this._foveation = 1.0;
  39390. /**
  39391. * A reference to the current XR session.
  39392. *
  39393. * @private
  39394. * @type {?XRSession}
  39395. * @default null
  39396. */
  39397. this._session = null;
  39398. /**
  39399. * A reference to the current XR base layer.
  39400. *
  39401. * @private
  39402. * @type {?XRWebGLLayer}
  39403. * @default null
  39404. */
  39405. this._glBaseLayer = null;
  39406. /**
  39407. * A reference to the current XR binding.
  39408. *
  39409. * @private
  39410. * @type {?XRWebGLBinding}
  39411. * @default null
  39412. */
  39413. this._glBinding = null;
  39414. /**
  39415. * A reference to the current XR projection layer.
  39416. *
  39417. * @private
  39418. * @type {?XRProjectionLayer}
  39419. * @default null
  39420. */
  39421. this._glProjLayer = null;
  39422. /**
  39423. * A reference to the current XR frame.
  39424. *
  39425. * @private
  39426. * @type {?XRFrame}
  39427. * @default null
  39428. */
  39429. this._xrFrame = null;
  39430. /**
  39431. * Whether the browser supports the APIs necessary to use XRProjectionLayers.
  39432. *
  39433. * Note: this does not represent XRSession explicitly requesting
  39434. * `'layers'` as a feature - see `_sessionUsesLayers` and #30112
  39435. *
  39436. * @private
  39437. * @type {boolean}
  39438. * @readonly
  39439. */
  39440. this._supportsLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  39441. /**
  39442. * Whether the usage of multiview has been requested by the application or not.
  39443. *
  39444. * @private
  39445. * @type {boolean}
  39446. * @default false
  39447. * @readonly
  39448. */
  39449. this._useMultiviewIfPossible = multiview;
  39450. /**
  39451. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  39452. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  39453. *
  39454. * @private
  39455. * @type {boolean}
  39456. * @readonly
  39457. */
  39458. this._useMultiview = false;
  39459. }
  39460. /**
  39461. * Returns an instance of `THREE.Group` that represents the transformation
  39462. * of a XR controller in target ray space. The requested controller is defined
  39463. * by the given index.
  39464. *
  39465. * @param {number} index - The index of the XR controller.
  39466. * @return {Group} A group that represents the controller's transformation.
  39467. */
  39468. getController( index ) {
  39469. const controller = this._getController( index );
  39470. return controller.getTargetRaySpace();
  39471. }
  39472. /**
  39473. * Returns an instance of `THREE.Group` that represents the transformation
  39474. * of a XR controller in grip space. The requested controller is defined
  39475. * by the given index.
  39476. *
  39477. * @param {number} index - The index of the XR controller.
  39478. * @return {Group} A group that represents the controller's transformation.
  39479. */
  39480. getControllerGrip( index ) {
  39481. const controller = this._getController( index );
  39482. return controller.getGripSpace();
  39483. }
  39484. /**
  39485. * Returns an instance of `THREE.Group` that represents the transformation
  39486. * of a XR controller in hand space. The requested controller is defined
  39487. * by the given index.
  39488. *
  39489. * @param {number} index - The index of the XR controller.
  39490. * @return {Group} A group that represents the controller's transformation.
  39491. */
  39492. getHand( index ) {
  39493. const controller = this._getController( index );
  39494. return controller.getHandSpace();
  39495. }
  39496. /**
  39497. * Returns the foveation value.
  39498. *
  39499. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  39500. */
  39501. getFoveation() {
  39502. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  39503. return undefined;
  39504. }
  39505. return this._foveation;
  39506. }
  39507. /**
  39508. * Sets the foveation value.
  39509. *
  39510. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  39511. * and `1` means maximum foveation (the edges render at lower resolution).
  39512. */
  39513. setFoveation( foveation ) {
  39514. this._foveation = foveation;
  39515. if ( this._glProjLayer !== null ) {
  39516. this._glProjLayer.fixedFoveation = foveation;
  39517. }
  39518. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  39519. this._glBaseLayer.fixedFoveation = foveation;
  39520. }
  39521. }
  39522. /**
  39523. * Returns the framebuffer scale factor.
  39524. *
  39525. * @return {number} The framebuffer scale factor.
  39526. */
  39527. getFramebufferScaleFactor() {
  39528. return this._framebufferScaleFactor;
  39529. }
  39530. /**
  39531. * Sets the framebuffer scale factor.
  39532. *
  39533. * This method can not be used during a XR session.
  39534. *
  39535. * @param {number} factor - The framebuffer scale factor.
  39536. */
  39537. setFramebufferScaleFactor( factor ) {
  39538. this._framebufferScaleFactor = factor;
  39539. if ( this.isPresenting === true ) {
  39540. warn( 'XRManager: Cannot change framebuffer scale while presenting.' );
  39541. }
  39542. }
  39543. /**
  39544. * Returns the reference space type.
  39545. *
  39546. * @return {XRReferenceSpaceType} The reference space type.
  39547. */
  39548. getReferenceSpaceType() {
  39549. return this._referenceSpaceType;
  39550. }
  39551. /**
  39552. * Sets the reference space type.
  39553. *
  39554. * This method can not be used during a XR session.
  39555. *
  39556. * @param {XRReferenceSpaceType} type - The reference space type.
  39557. */
  39558. setReferenceSpaceType( type ) {
  39559. this._referenceSpaceType = type;
  39560. if ( this.isPresenting === true ) {
  39561. warn( 'XRManager: Cannot change reference space type while presenting.' );
  39562. }
  39563. }
  39564. /**
  39565. * Returns the XR reference space.
  39566. *
  39567. * @return {XRReferenceSpace} The XR reference space.
  39568. */
  39569. getReferenceSpace() {
  39570. return this._customReferenceSpace || this._referenceSpace;
  39571. }
  39572. /**
  39573. * Sets a custom XR reference space.
  39574. *
  39575. * @param {XRReferenceSpace} space - The XR reference space.
  39576. */
  39577. setReferenceSpace( space ) {
  39578. this._customReferenceSpace = space;
  39579. }
  39580. /**
  39581. * Returns the XR camera.
  39582. *
  39583. * @return {ArrayCamera} The XR camera.
  39584. */
  39585. getCamera() {
  39586. return this._cameraXR;
  39587. }
  39588. /**
  39589. * Returns the environment blend mode from the current XR session.
  39590. *
  39591. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  39592. */
  39593. getEnvironmentBlendMode() {
  39594. if ( this._session !== null ) {
  39595. return this._session.environmentBlendMode;
  39596. }
  39597. }
  39598. /**
  39599. * Returns the current XR binding.
  39600. *
  39601. * Creates a new binding if needed and the browser is
  39602. * capable of doing so.
  39603. *
  39604. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  39605. */
  39606. getBinding() {
  39607. if ( this._glBinding === null && this._supportsGlBinding ) {
  39608. this._glBinding = new XRWebGLBinding( this._session, this._gl );
  39609. }
  39610. return this._glBinding;
  39611. }
  39612. /**
  39613. * Returns the current XR frame.
  39614. *
  39615. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  39616. */
  39617. getFrame() {
  39618. return this._xrFrame;
  39619. }
  39620. /**
  39621. * Returns `true` if the engine renders to a multiview target.
  39622. *
  39623. * @return {boolean} Whether the engine renders to a multiview render target or not.
  39624. */
  39625. useMultiview() {
  39626. return this._useMultiview;
  39627. }
  39628. /**
  39629. * This method can be used in XR applications to create a quadratic layer that presents a separate
  39630. * rendered scene.
  39631. *
  39632. * @param {number} width - The width of the layer plane in world units.
  39633. * @param {number} height - The height of the layer plane in world units.
  39634. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  39635. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  39636. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  39637. * @param {number} pixelheight - The height of the layer's render target in pixels.
  39638. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  39639. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  39640. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  39641. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  39642. */
  39643. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  39644. const geometry = new PlaneGeometry( width, height );
  39645. const renderTarget = new XRRenderTarget(
  39646. pixelwidth,
  39647. pixelheight,
  39648. {
  39649. format: RGBAFormat,
  39650. type: UnsignedByteType,
  39651. depthTexture: new DepthTexture(
  39652. pixelwidth,
  39653. pixelheight,
  39654. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  39655. undefined,
  39656. undefined,
  39657. undefined,
  39658. undefined,
  39659. undefined,
  39660. undefined,
  39661. attributes.stencil ? DepthStencilFormat : DepthFormat
  39662. ),
  39663. stencilBuffer: attributes.stencil,
  39664. resolveDepthBuffer: false,
  39665. resolveStencilBuffer: false
  39666. } );
  39667. renderTarget._autoAllocateDepthBuffer = true;
  39668. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  39669. material.map = renderTarget.texture;
  39670. material.map.offset.y = 1;
  39671. material.map.repeat.y = -1;
  39672. const plane = new Mesh( geometry, material );
  39673. plane.position.copy( translation );
  39674. plane.quaternion.copy( quaternion );
  39675. const layer = {
  39676. type: 'quad',
  39677. width: width,
  39678. height: height,
  39679. translation: translation,
  39680. quaternion: quaternion,
  39681. pixelwidth: pixelwidth,
  39682. pixelheight: pixelheight,
  39683. plane: plane,
  39684. material: material,
  39685. rendercall: rendercall,
  39686. renderTarget: renderTarget };
  39687. this._layers.push( layer );
  39688. if ( this._session !== null ) {
  39689. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  39690. layer.plane.material.blending = CustomBlending;
  39691. layer.plane.material.blendEquation = AddEquation;
  39692. layer.plane.material.blendSrc = ZeroFactor;
  39693. layer.plane.material.blendDst = ZeroFactor;
  39694. layer.xrlayer = this._createXRLayer( layer );
  39695. const xrlayers = this._session.renderState.layers;
  39696. xrlayers.unshift( layer.xrlayer );
  39697. this._session.updateRenderState( { layers: xrlayers } );
  39698. } else {
  39699. renderTarget.isXRRenderTarget = false;
  39700. }
  39701. return plane;
  39702. }
  39703. /**
  39704. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  39705. * rendered scene.
  39706. *
  39707. * @param {number} radius - The radius of the cylinder in world units.
  39708. * @param {number} centralAngle - The central angle of the cylinder in radians.
  39709. * @param {number} aspectratio - The aspect ratio.
  39710. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  39711. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  39712. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  39713. * @param {number} pixelheight - The height of the layer's render target in pixels.
  39714. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  39715. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  39716. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  39717. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  39718. */
  39719. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  39720. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  39721. const renderTarget = new XRRenderTarget(
  39722. pixelwidth,
  39723. pixelheight,
  39724. {
  39725. format: RGBAFormat,
  39726. type: UnsignedByteType,
  39727. depthTexture: new DepthTexture(
  39728. pixelwidth,
  39729. pixelheight,
  39730. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  39731. undefined,
  39732. undefined,
  39733. undefined,
  39734. undefined,
  39735. undefined,
  39736. undefined,
  39737. attributes.stencil ? DepthStencilFormat : DepthFormat
  39738. ),
  39739. stencilBuffer: attributes.stencil,
  39740. resolveDepthBuffer: false,
  39741. resolveStencilBuffer: false
  39742. } );
  39743. renderTarget._autoAllocateDepthBuffer = true;
  39744. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  39745. material.map = renderTarget.texture;
  39746. material.map.offset.y = 1;
  39747. material.map.repeat.y = -1;
  39748. const plane = new Mesh( geometry, material );
  39749. plane.position.copy( translation );
  39750. plane.quaternion.copy( quaternion );
  39751. const layer = {
  39752. type: 'cylinder',
  39753. radius: radius,
  39754. centralAngle: centralAngle,
  39755. aspectratio: aspectratio,
  39756. translation: translation,
  39757. quaternion: quaternion,
  39758. pixelwidth: pixelwidth,
  39759. pixelheight: pixelheight,
  39760. plane: plane,
  39761. material: material,
  39762. rendercall: rendercall,
  39763. renderTarget: renderTarget };
  39764. this._layers.push( layer );
  39765. if ( this._session !== null ) {
  39766. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  39767. layer.plane.material.blending = CustomBlending;
  39768. layer.plane.material.blendEquation = AddEquation;
  39769. layer.plane.material.blendSrc = ZeroFactor;
  39770. layer.plane.material.blendDst = ZeroFactor;
  39771. layer.xrlayer = this._createXRLayer( layer );
  39772. const xrlayers = this._session.renderState.layers;
  39773. xrlayers.unshift( layer.xrlayer );
  39774. this._session.updateRenderState( { layers: xrlayers } );
  39775. } else {
  39776. renderTarget.isXRRenderTarget = false;
  39777. }
  39778. return plane;
  39779. }
  39780. /**
  39781. * Renders the XR layers that have been previously added to the scene.
  39782. *
  39783. * This method is usually called in your animation loop before rendering
  39784. * the actual scene via `renderer.render( scene, camera );`.
  39785. */
  39786. renderLayers( ) {
  39787. const translationObject = new Vector3();
  39788. const quaternionObject = new Quaternion();
  39789. const renderer = this._renderer;
  39790. const wasPresenting = this.isPresenting;
  39791. const rendererOutputTarget = renderer.getOutputRenderTarget();
  39792. const rendererFramebufferTarget = renderer._frameBufferTarget;
  39793. this.isPresenting = false;
  39794. const rendererSize = new Vector2();
  39795. renderer.getSize( rendererSize );
  39796. const rendererQuad = renderer._quad;
  39797. for ( const layer of this._layers ) {
  39798. layer.renderTarget.isXRRenderTarget = this._session !== null;
  39799. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  39800. if ( layer.renderTarget.isXRRenderTarget && this._sessionUsesLayers ) {
  39801. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  39802. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  39803. renderer.backend.setXRRenderTargetTextures(
  39804. layer.renderTarget,
  39805. glSubImage.colorTexture,
  39806. undefined );
  39807. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  39808. renderer.setOutputRenderTarget( layer.renderTarget );
  39809. renderer.setRenderTarget( null );
  39810. renderer._frameBufferTarget = null;
  39811. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  39812. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  39813. if ( ! frameBufferTarget ) {
  39814. renderer._quad = new QuadMesh( new NodeMaterial() );
  39815. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  39816. } else {
  39817. renderer._frameBufferTarget = frameBufferTarget;
  39818. renderer._quad = quad;
  39819. }
  39820. layer.rendercall();
  39821. renderer._frameBufferTarget = null;
  39822. } else {
  39823. renderer.setRenderTarget( layer.renderTarget );
  39824. layer.rendercall();
  39825. }
  39826. }
  39827. renderer.setRenderTarget( null );
  39828. renderer.setOutputRenderTarget( rendererOutputTarget );
  39829. renderer._frameBufferTarget = rendererFramebufferTarget;
  39830. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  39831. renderer._quad = rendererQuad;
  39832. this.isPresenting = wasPresenting;
  39833. }
  39834. /**
  39835. * Returns the current XR session.
  39836. *
  39837. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  39838. */
  39839. getSession() {
  39840. return this._session;
  39841. }
  39842. /**
  39843. * After a XR session has been requested usually with one of the `*Button` modules, it
  39844. * is injected into the renderer with this method. This method triggers the start of
  39845. * the actual XR rendering.
  39846. *
  39847. * @async
  39848. * @param {XRSession} session - The XR session to set.
  39849. * @return {Promise} A Promise that resolves when the session has been set.
  39850. */
  39851. async setSession( session ) {
  39852. const renderer = this._renderer;
  39853. const backend = renderer.backend;
  39854. this._gl = renderer.getContext();
  39855. const gl = this._gl;
  39856. const attributes = gl.getContextAttributes();
  39857. this._session = session;
  39858. if ( session !== null ) {
  39859. 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.' );
  39860. session.addEventListener( 'select', this._onSessionEvent );
  39861. session.addEventListener( 'selectstart', this._onSessionEvent );
  39862. session.addEventListener( 'selectend', this._onSessionEvent );
  39863. session.addEventListener( 'squeeze', this._onSessionEvent );
  39864. session.addEventListener( 'squeezestart', this._onSessionEvent );
  39865. session.addEventListener( 'squeezeend', this._onSessionEvent );
  39866. session.addEventListener( 'end', this._onSessionEnd );
  39867. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  39868. await backend.makeXRCompatible();
  39869. this._currentPixelRatio = renderer.getPixelRatio();
  39870. renderer.getSize( this._currentSize );
  39871. this._currentAnimationContext = renderer._animation.getContext();
  39872. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  39873. renderer._animation.stop();
  39874. //
  39875. if ( this._supportsLayers === true ) {
  39876. // default path using XRProjectionLayer
  39877. let depthFormat = null;
  39878. let depthType = null;
  39879. let glDepthFormat = null;
  39880. if ( renderer.depth ) {
  39881. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  39882. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  39883. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  39884. }
  39885. const projectionlayerInit = {
  39886. colorFormat: gl.RGBA8,
  39887. depthFormat: glDepthFormat,
  39888. scaleFactor: this._framebufferScaleFactor,
  39889. clearOnAccess: false
  39890. };
  39891. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  39892. projectionlayerInit.textureType = 'texture-array';
  39893. this._useMultiview = true;
  39894. }
  39895. this._glBinding = this.getBinding();
  39896. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  39897. const layersArray = [ glProjLayer ];
  39898. this._glProjLayer = glProjLayer;
  39899. renderer.setPixelRatio( 1 );
  39900. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  39901. const depth = this._useMultiview ? 2 : 1;
  39902. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  39903. this._xrRenderTarget = new XRRenderTarget(
  39904. glProjLayer.textureWidth,
  39905. glProjLayer.textureHeight,
  39906. {
  39907. format: RGBAFormat,
  39908. type: UnsignedByteType,
  39909. colorSpace: renderer.outputColorSpace,
  39910. depthTexture: depthTexture,
  39911. stencilBuffer: renderer.stencil,
  39912. samples: attributes.antialias ? 4 : 0,
  39913. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  39914. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  39915. depth: this._useMultiview ? 2 : 1,
  39916. multiview: this._useMultiview
  39917. } );
  39918. this._xrRenderTarget._hasExternalTextures = true;
  39919. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  39920. this._sessionUsesLayers = session.enabledFeatures.includes( 'layers' );
  39921. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  39922. if ( this._sessionUsesLayers ) {
  39923. // switch layers to native
  39924. for ( const layer of this._layers ) {
  39925. // change material so it "punches" out a hole to show the XR Layer.
  39926. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  39927. layer.plane.material.blending = CustomBlending;
  39928. layer.plane.material.blendEquation = AddEquation;
  39929. layer.plane.material.blendSrc = ZeroFactor;
  39930. layer.plane.material.blendDst = ZeroFactor;
  39931. layer.xrlayer = this._createXRLayer( layer );
  39932. layersArray.unshift( layer.xrlayer );
  39933. }
  39934. }
  39935. session.updateRenderState( { layers: layersArray } );
  39936. } else {
  39937. // fallback to XRWebGLLayer
  39938. const layerInit = {
  39939. antialias: renderer.currentSamples > 0,
  39940. alpha: true,
  39941. depth: renderer.depth,
  39942. stencil: renderer.stencil,
  39943. framebufferScaleFactor: this.getFramebufferScaleFactor()
  39944. };
  39945. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  39946. this._glBaseLayer = glBaseLayer;
  39947. session.updateRenderState( { baseLayer: glBaseLayer } );
  39948. renderer.setPixelRatio( 1 );
  39949. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  39950. this._xrRenderTarget = new XRRenderTarget(
  39951. glBaseLayer.framebufferWidth,
  39952. glBaseLayer.framebufferHeight,
  39953. {
  39954. format: RGBAFormat,
  39955. type: UnsignedByteType,
  39956. colorSpace: renderer.outputColorSpace,
  39957. stencilBuffer: renderer.stencil,
  39958. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  39959. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  39960. }
  39961. );
  39962. this._xrRenderTarget._isOpaqueFramebuffer = true;
  39963. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  39964. }
  39965. //
  39966. this.setFoveation( this.getFoveation() );
  39967. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  39968. renderer._animation.setContext( session );
  39969. renderer._animation.start();
  39970. this.isPresenting = true;
  39971. this.dispatchEvent( { type: 'sessionstart' } );
  39972. }
  39973. }
  39974. /**
  39975. * This method is called by the renderer per frame and updates the XR camera
  39976. * and it sub cameras based on the given camera. The given camera is the "user"
  39977. * camera created on application level and used for non-XR rendering.
  39978. *
  39979. * @param {PerspectiveCamera} camera - The camera.
  39980. */
  39981. updateCamera( camera ) {
  39982. const session = this._session;
  39983. if ( session === null ) return;
  39984. const depthNear = camera.near;
  39985. const depthFar = camera.far;
  39986. const cameraXR = this._cameraXR;
  39987. const cameraL = this._cameraL;
  39988. const cameraR = this._cameraR;
  39989. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  39990. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  39991. cameraXR.isMultiViewCamera = this._useMultiview;
  39992. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  39993. // Note that the new renderState won't apply until the next frame. See #18320
  39994. session.updateRenderState( {
  39995. depthNear: cameraXR.near,
  39996. depthFar: cameraXR.far
  39997. } );
  39998. this._currentDepthNear = cameraXR.near;
  39999. this._currentDepthFar = cameraXR.far;
  40000. }
  40001. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  40002. cameraXR.layers.mask = camera.layers.mask | 0b110;
  40003. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  40004. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  40005. const parent = camera.parent;
  40006. const cameras = cameraXR.cameras;
  40007. updateCamera( cameraXR, parent );
  40008. for ( let i = 0; i < cameras.length; i ++ ) {
  40009. updateCamera( cameras[ i ], parent );
  40010. }
  40011. // update projection matrix for proper view frustum culling
  40012. if ( cameras.length === 2 ) {
  40013. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  40014. } else {
  40015. // assume single camera setup (AR)
  40016. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  40017. }
  40018. // update user camera and its children
  40019. updateUserCamera( camera, cameraXR, parent );
  40020. }
  40021. /**
  40022. * Returns a WebXR controller for the given controller index.
  40023. *
  40024. * @private
  40025. * @param {number} index - The controller index.
  40026. * @return {WebXRController} The XR controller.
  40027. */
  40028. _getController( index ) {
  40029. let controller = this._controllers[ index ];
  40030. if ( controller === undefined ) {
  40031. controller = new WebXRController();
  40032. this._controllers[ index ] = controller;
  40033. }
  40034. return controller;
  40035. }
  40036. }
  40037. /**
  40038. * Assumes 2 cameras that are parallel and share an X-axis, and that
  40039. * the cameras' projection and world matrices have already been set.
  40040. * And that near and far planes are identical for both cameras.
  40041. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  40042. *
  40043. * @param {ArrayCamera} camera - The camera to update.
  40044. * @param {PerspectiveCamera} cameraL - The left camera.
  40045. * @param {PerspectiveCamera} cameraR - The right camera.
  40046. */
  40047. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  40048. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  40049. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  40050. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  40051. const projL = cameraL.projectionMatrix.elements;
  40052. const projR = cameraR.projectionMatrix.elements;
  40053. // VR systems will have identical far and near planes, and
  40054. // most likely identical top and bottom frustum extents.
  40055. // Use the left camera for these values.
  40056. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  40057. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  40058. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  40059. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  40060. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  40061. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  40062. const left = near * leftFov;
  40063. const right = near * rightFov;
  40064. // Calculate the new camera's position offset from the
  40065. // left camera. xOffset should be roughly half `ipd`.
  40066. const zOffset = ipd / ( - leftFov + rightFov );
  40067. const xOffset = zOffset * - leftFov;
  40068. // TODO: Better way to apply this offset?
  40069. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  40070. camera.translateX( xOffset );
  40071. camera.translateZ( zOffset );
  40072. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  40073. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  40074. // Check if the projection uses an infinite far plane.
  40075. if ( projL[ 10 ] === -1 ) {
  40076. // Use the projection matrix from the left eye.
  40077. // The camera offset is sufficient to include the view volumes
  40078. // of both eyes (assuming symmetric projections).
  40079. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  40080. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  40081. } else {
  40082. // Find the union of the frustum values of the cameras and scale
  40083. // the values so that the near plane's position does not change in world space,
  40084. // although must now be relative to the new union camera.
  40085. const near2 = near + zOffset;
  40086. const far2 = far + zOffset;
  40087. const left2 = left - xOffset;
  40088. const right2 = right + ( ipd - xOffset );
  40089. const top2 = topFov * far / far2 * near2;
  40090. const bottom2 = bottomFov * far / far2 * near2;
  40091. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  40092. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  40093. }
  40094. }
  40095. /**
  40096. * Updates the world matrices for the given camera based on the parent 3D object.
  40097. *
  40098. * @inner
  40099. * @param {Camera} camera - The camera to update.
  40100. * @param {Object3D} parent - The parent 3D object.
  40101. */
  40102. function updateCamera( camera, parent ) {
  40103. if ( parent === null ) {
  40104. camera.matrixWorld.copy( camera.matrix );
  40105. } else {
  40106. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  40107. }
  40108. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  40109. }
  40110. /**
  40111. * Updates the given camera with the transformation of the XR camera and parent object.
  40112. *
  40113. * @inner
  40114. * @param {Camera} camera - The camera to update.
  40115. * @param {ArrayCamera} cameraXR - The XR camera.
  40116. * @param {Object3D} parent - The parent 3D object.
  40117. */
  40118. function updateUserCamera( camera, cameraXR, parent ) {
  40119. if ( parent === null ) {
  40120. camera.matrix.copy( cameraXR.matrixWorld );
  40121. } else {
  40122. camera.matrix.copy( parent.matrixWorld );
  40123. camera.matrix.invert();
  40124. camera.matrix.multiply( cameraXR.matrixWorld );
  40125. }
  40126. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  40127. camera.updateMatrixWorld( true );
  40128. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  40129. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  40130. if ( camera.isPerspectiveCamera ) {
  40131. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  40132. camera.zoom = 1;
  40133. }
  40134. }
  40135. function onSessionEvent( event ) {
  40136. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  40137. if ( controllerIndex === -1 ) {
  40138. return;
  40139. }
  40140. const controller = this._controllers[ controllerIndex ];
  40141. if ( controller !== undefined ) {
  40142. const referenceSpace = this.getReferenceSpace();
  40143. controller.update( event.inputSource, event.frame, referenceSpace );
  40144. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  40145. }
  40146. }
  40147. function onSessionEnd() {
  40148. const session = this._session;
  40149. const renderer = this._renderer;
  40150. session.removeEventListener( 'select', this._onSessionEvent );
  40151. session.removeEventListener( 'selectstart', this._onSessionEvent );
  40152. session.removeEventListener( 'selectend', this._onSessionEvent );
  40153. session.removeEventListener( 'squeeze', this._onSessionEvent );
  40154. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  40155. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  40156. session.removeEventListener( 'end', this._onSessionEnd );
  40157. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  40158. for ( let i = 0; i < this._controllers.length; i ++ ) {
  40159. const inputSource = this._controllerInputSources[ i ];
  40160. if ( inputSource === null ) continue;
  40161. this._controllerInputSources[ i ] = null;
  40162. this._controllers[ i ].disconnect( inputSource );
  40163. }
  40164. this._currentDepthNear = null;
  40165. this._currentDepthFar = null;
  40166. // restore framebuffer/rendering state
  40167. renderer._resetXRState();
  40168. this._session = null;
  40169. this._xrRenderTarget = null;
  40170. this._glBinding = null;
  40171. this._glBaseLayer = null;
  40172. this._glProjLayer = null;
  40173. // switch layers back to emulated
  40174. if ( this._sessionUsesLayers === true ) {
  40175. for ( const layer of this._layers ) {
  40176. // Recreate layer render target to reset state
  40177. layer.renderTarget = new XRRenderTarget(
  40178. layer.pixelwidth,
  40179. layer.pixelheight,
  40180. {
  40181. format: RGBAFormat,
  40182. type: UnsignedByteType,
  40183. depthTexture: new DepthTexture(
  40184. layer.pixelwidth,
  40185. layer.pixelheight,
  40186. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  40187. undefined,
  40188. undefined,
  40189. undefined,
  40190. undefined,
  40191. undefined,
  40192. undefined,
  40193. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  40194. ),
  40195. stencilBuffer: layer.stencilBuffer,
  40196. resolveDepthBuffer: false,
  40197. resolveStencilBuffer: false
  40198. } );
  40199. layer.renderTarget.isXRRenderTarget = false;
  40200. layer.plane.material = layer.material;
  40201. layer.material.map = layer.renderTarget.texture;
  40202. layer.material.map.offset.y = 1;
  40203. layer.material.map.repeat.y = -1;
  40204. delete layer.xrlayer;
  40205. }
  40206. }
  40207. //
  40208. this.isPresenting = false;
  40209. this._useMultiview = false;
  40210. renderer._animation.stop();
  40211. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  40212. renderer._animation.setContext( this._currentAnimationContext );
  40213. renderer._animation.start();
  40214. renderer.setPixelRatio( this._currentPixelRatio );
  40215. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  40216. this.dispatchEvent( { type: 'sessionend' } );
  40217. }
  40218. function onInputSourcesChange( event ) {
  40219. const controllers = this._controllers;
  40220. const controllerInputSources = this._controllerInputSources;
  40221. // Notify disconnected
  40222. for ( let i = 0; i < event.removed.length; i ++ ) {
  40223. const inputSource = event.removed[ i ];
  40224. const index = controllerInputSources.indexOf( inputSource );
  40225. if ( index >= 0 ) {
  40226. controllerInputSources[ index ] = null;
  40227. controllers[ index ].disconnect( inputSource );
  40228. }
  40229. }
  40230. // Notify connected
  40231. for ( let i = 0; i < event.added.length; i ++ ) {
  40232. const inputSource = event.added[ i ];
  40233. let controllerIndex = controllerInputSources.indexOf( inputSource );
  40234. if ( controllerIndex === -1 ) {
  40235. // Assign input source a controller that currently has no input source
  40236. for ( let i = 0; i < controllers.length; i ++ ) {
  40237. if ( i >= controllerInputSources.length ) {
  40238. controllerInputSources.push( inputSource );
  40239. controllerIndex = i;
  40240. break;
  40241. } else if ( controllerInputSources[ i ] === null ) {
  40242. controllerInputSources[ i ] = inputSource;
  40243. controllerIndex = i;
  40244. break;
  40245. }
  40246. }
  40247. // If all controllers do currently receive input we ignore new ones
  40248. if ( controllerIndex === -1 ) break;
  40249. }
  40250. const controller = controllers[ controllerIndex ];
  40251. if ( controller ) {
  40252. controller.connect( inputSource );
  40253. }
  40254. }
  40255. }
  40256. // Creation method for native WebXR layers
  40257. function createXRLayer( layer ) {
  40258. if ( layer.type === 'quad' ) {
  40259. return this._glBinding.createQuadLayer( {
  40260. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  40261. width: layer.width / 2,
  40262. height: layer.height / 2,
  40263. space: this._referenceSpace,
  40264. viewPixelWidth: layer.pixelwidth,
  40265. viewPixelHeight: layer.pixelheight,
  40266. clearOnAccess: false
  40267. } );
  40268. } else {
  40269. return this._glBinding.createCylinderLayer( {
  40270. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  40271. radius: layer.radius,
  40272. centralAngle: layer.centralAngle,
  40273. aspectRatio: layer.aspectRatio,
  40274. space: this._referenceSpace,
  40275. viewPixelWidth: layer.pixelwidth,
  40276. viewPixelHeight: layer.pixelheight,
  40277. clearOnAccess: false
  40278. } );
  40279. }
  40280. }
  40281. // Animation Loop
  40282. function onAnimationFrame( time, frame ) {
  40283. if ( frame === undefined ) return;
  40284. const cameraXR = this._cameraXR;
  40285. const renderer = this._renderer;
  40286. const backend = renderer.backend;
  40287. const glBaseLayer = this._glBaseLayer;
  40288. const referenceSpace = this.getReferenceSpace();
  40289. const pose = frame.getViewerPose( referenceSpace );
  40290. this._xrFrame = frame;
  40291. if ( pose !== null ) {
  40292. const views = pose.views;
  40293. if ( this._glBaseLayer !== null ) {
  40294. backend.setXRTarget( glBaseLayer.framebuffer );
  40295. }
  40296. let cameraXRNeedsUpdate = false;
  40297. // check if it's necessary to rebuild cameraXR's camera list
  40298. if ( views.length !== cameraXR.cameras.length ) {
  40299. cameraXR.cameras.length = 0;
  40300. cameraXRNeedsUpdate = true;
  40301. }
  40302. for ( let i = 0; i < views.length; i ++ ) {
  40303. const view = views[ i ];
  40304. let viewport;
  40305. if ( this._supportsLayers === true ) {
  40306. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  40307. viewport = glSubImage.viewport;
  40308. // For side-by-side projection, we only produce a single texture for both eyes.
  40309. if ( i === 0 ) {
  40310. backend.setXRRenderTargetTextures(
  40311. this._xrRenderTarget,
  40312. glSubImage.colorTexture,
  40313. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  40314. );
  40315. }
  40316. } else {
  40317. viewport = glBaseLayer.getViewport( view );
  40318. }
  40319. let camera = this._cameras[ i ];
  40320. if ( camera === undefined ) {
  40321. camera = new PerspectiveCamera();
  40322. camera.layers.enable( i );
  40323. camera.viewport = new Vector4();
  40324. this._cameras[ i ] = camera;
  40325. }
  40326. camera.matrix.fromArray( view.transform.matrix );
  40327. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  40328. camera.projectionMatrix.fromArray( view.projectionMatrix );
  40329. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  40330. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  40331. if ( i === 0 ) {
  40332. cameraXR.matrix.copy( camera.matrix );
  40333. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  40334. }
  40335. if ( cameraXRNeedsUpdate === true ) {
  40336. cameraXR.cameras.push( camera );
  40337. }
  40338. }
  40339. renderer.setOutputRenderTarget( this._xrRenderTarget );
  40340. }
  40341. //
  40342. for ( let i = 0; i < this._controllers.length; i ++ ) {
  40343. const inputSource = this._controllerInputSources[ i ];
  40344. const controller = this._controllers[ i ];
  40345. if ( inputSource !== null && controller !== undefined ) {
  40346. controller.update( inputSource, frame, referenceSpace );
  40347. }
  40348. }
  40349. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  40350. if ( frame.detectedPlanes ) {
  40351. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  40352. }
  40353. this._xrFrame = null;
  40354. }
  40355. /**
  40356. * CanvasTarget is a class that represents the final output destination of the renderer.
  40357. *
  40358. * @augments EventDispatcher
  40359. */
  40360. class CanvasTarget extends EventDispatcher {
  40361. /**
  40362. * Constructs a new CanvasTarget.
  40363. *
  40364. * @param {HTMLCanvasElement|OffscreenCanvas} domElement - The canvas element to render to.
  40365. */
  40366. constructor( domElement ) {
  40367. super();
  40368. /**
  40369. * A reference to the canvas element the renderer is drawing to.
  40370. * This value of this property will automatically be created by
  40371. * the renderer.
  40372. *
  40373. * @type {HTMLCanvasElement|OffscreenCanvas}
  40374. */
  40375. this.domElement = domElement;
  40376. /**
  40377. * The renderer's pixel ratio.
  40378. *
  40379. * @private
  40380. * @type {number}
  40381. * @default 1
  40382. */
  40383. this._pixelRatio = 1;
  40384. /**
  40385. * The width of the renderer's default framebuffer in logical pixel unit.
  40386. *
  40387. * @private
  40388. * @type {number}
  40389. */
  40390. this._width = this.domElement.width;
  40391. /**
  40392. * The height of the renderer's default framebuffer in logical pixel unit.
  40393. *
  40394. * @private
  40395. * @type {number}
  40396. */
  40397. this._height = this.domElement.height;
  40398. /**
  40399. * The viewport of the renderer in logical pixel unit.
  40400. *
  40401. * @private
  40402. * @type {Vector4}
  40403. */
  40404. this._viewport = new Vector4( 0, 0, this._width, this._height );
  40405. /**
  40406. * The scissor rectangle of the renderer in logical pixel unit.
  40407. *
  40408. * @private
  40409. * @type {Vector4}
  40410. */
  40411. this._scissor = new Vector4( 0, 0, this._width, this._height );
  40412. /**
  40413. * Whether the scissor test should be enabled or not.
  40414. *
  40415. * @private
  40416. * @type {boolean}
  40417. */
  40418. this._scissorTest = false;
  40419. /**
  40420. * The color texture of the default framebuffer.
  40421. *
  40422. * @type {FramebufferTexture}
  40423. */
  40424. this.colorTexture = new FramebufferTexture();
  40425. /**
  40426. * The depth texture of the default framebuffer.
  40427. *
  40428. * @type {DepthTexture}
  40429. */
  40430. this.depthTexture = new DepthTexture();
  40431. }
  40432. /**
  40433. * Returns the pixel ratio.
  40434. *
  40435. * @return {number} The pixel ratio.
  40436. */
  40437. getPixelRatio() {
  40438. return this._pixelRatio;
  40439. }
  40440. /**
  40441. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  40442. *
  40443. * @param {Vector2} target - The method writes the result in this target object.
  40444. * @return {Vector2} The drawing buffer size.
  40445. */
  40446. getDrawingBufferSize( target ) {
  40447. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  40448. }
  40449. /**
  40450. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  40451. *
  40452. * @param {Vector2} target - The method writes the result in this target object.
  40453. * @return {Vector2} The renderer's size in logical pixels.
  40454. */
  40455. getSize( target ) {
  40456. return target.set( this._width, this._height );
  40457. }
  40458. /**
  40459. * Sets the given pixel ratio and resizes the canvas if necessary.
  40460. *
  40461. * @param {number} [value=1] - The pixel ratio.
  40462. */
  40463. setPixelRatio( value = 1 ) {
  40464. if ( this._pixelRatio === value ) return;
  40465. this._pixelRatio = value;
  40466. this.setSize( this._width, this._height, false );
  40467. }
  40468. /**
  40469. * This method allows to define the drawing buffer size by specifying
  40470. * width, height and pixel ratio all at once. The size of the drawing
  40471. * buffer is computed with this formula:
  40472. * ```js
  40473. * size.x = width * pixelRatio;
  40474. * size.y = height * pixelRatio;
  40475. * ```
  40476. *
  40477. * @param {number} width - The width in logical pixels.
  40478. * @param {number} height - The height in logical pixels.
  40479. * @param {number} pixelRatio - The pixel ratio.
  40480. */
  40481. setDrawingBufferSize( width, height, pixelRatio ) {
  40482. // Renderer can't be resized while presenting in XR.
  40483. if ( this.xr && this.xr.isPresenting ) return;
  40484. this._width = width;
  40485. this._height = height;
  40486. this._pixelRatio = pixelRatio;
  40487. this.domElement.width = Math.floor( width * pixelRatio );
  40488. this.domElement.height = Math.floor( height * pixelRatio );
  40489. this.setViewport( 0, 0, width, height );
  40490. this._dispatchResize();
  40491. }
  40492. /**
  40493. * Sets the size of the renderer.
  40494. *
  40495. * @param {number} width - The width in logical pixels.
  40496. * @param {number} height - The height in logical pixels.
  40497. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  40498. */
  40499. setSize( width, height, updateStyle = true ) {
  40500. // Renderer can't be resized while presenting in XR.
  40501. if ( this.xr && this.xr.isPresenting ) return;
  40502. this._width = width;
  40503. this._height = height;
  40504. this.domElement.width = Math.floor( width * this._pixelRatio );
  40505. this.domElement.height = Math.floor( height * this._pixelRatio );
  40506. if ( updateStyle === true ) {
  40507. this.domElement.style.width = width + 'px';
  40508. this.domElement.style.height = height + 'px';
  40509. }
  40510. this.setViewport( 0, 0, width, height );
  40511. this._dispatchResize();
  40512. }
  40513. /**
  40514. * Returns the scissor rectangle.
  40515. *
  40516. * @param {Vector4} target - The method writes the result in this target object.
  40517. * @return {Vector4} The scissor rectangle.
  40518. */
  40519. getScissor( target ) {
  40520. const scissor = this._scissor;
  40521. target.x = scissor.x;
  40522. target.y = scissor.y;
  40523. target.width = scissor.width;
  40524. target.height = scissor.height;
  40525. return target;
  40526. }
  40527. /**
  40528. * Defines the scissor rectangle.
  40529. *
  40530. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  40531. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  40532. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  40533. * @param {number} width - The width of the scissor box in logical pixel unit.
  40534. * @param {number} height - The height of the scissor box in logical pixel unit.
  40535. */
  40536. setScissor( x, y, width, height ) {
  40537. const scissor = this._scissor;
  40538. if ( x.isVector4 ) {
  40539. scissor.copy( x );
  40540. } else {
  40541. scissor.set( x, y, width, height );
  40542. }
  40543. }
  40544. /**
  40545. * Returns the scissor test value.
  40546. *
  40547. * @return {boolean} Whether the scissor test should be enabled or not.
  40548. */
  40549. getScissorTest() {
  40550. return this._scissorTest;
  40551. }
  40552. /**
  40553. * Defines the scissor test.
  40554. *
  40555. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  40556. */
  40557. setScissorTest( boolean ) {
  40558. this._scissorTest = boolean;
  40559. }
  40560. /**
  40561. * Returns the viewport definition.
  40562. *
  40563. * @param {Vector4} target - The method writes the result in this target object.
  40564. * @return {Vector4} The viewport definition.
  40565. */
  40566. getViewport( target ) {
  40567. return target.copy( this._viewport );
  40568. }
  40569. /**
  40570. * Defines the viewport.
  40571. *
  40572. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40573. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40574. * @param {number} width - The width of the viewport in logical pixel unit.
  40575. * @param {number} height - The height of the viewport in logical pixel unit.
  40576. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  40577. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  40578. */
  40579. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  40580. const viewport = this._viewport;
  40581. if ( x.isVector4 ) {
  40582. viewport.copy( x );
  40583. } else {
  40584. viewport.set( x, y, width, height );
  40585. }
  40586. viewport.minDepth = minDepth;
  40587. viewport.maxDepth = maxDepth;
  40588. }
  40589. /**
  40590. * Dispatches the resize event.
  40591. *
  40592. * @private
  40593. */
  40594. _dispatchResize() {
  40595. this.dispatchEvent( { type: 'resize' } );
  40596. }
  40597. /**
  40598. * Frees the GPU-related resources allocated by this instance. Call this
  40599. * method whenever this instance is no longer used in your app.
  40600. *
  40601. * @fires RenderTarget#dispose
  40602. */
  40603. dispose() {
  40604. this.dispatchEvent( { type: 'dispose' } );
  40605. }
  40606. }
  40607. const _scene = /*@__PURE__*/ new Scene();
  40608. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  40609. const _screen = /*@__PURE__*/ new Vector4();
  40610. const _frustum = /*@__PURE__*/ new Frustum();
  40611. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  40612. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  40613. const _vector4 = /*@__PURE__*/ new Vector4();
  40614. /**
  40615. * Base class for renderers.
  40616. */
  40617. class Renderer {
  40618. /**
  40619. * Renderer options.
  40620. *
  40621. * @typedef {Object} Renderer~Options
  40622. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  40623. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  40624. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  40625. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  40626. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  40627. * @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
  40628. * to overwrite the default.
  40629. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  40630. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  40631. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  40632. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  40633. */
  40634. /**
  40635. * Constructs a new renderer.
  40636. *
  40637. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  40638. * @param {Renderer~Options} [parameters] - The configuration parameter.
  40639. */
  40640. constructor( backend, parameters = {} ) {
  40641. /**
  40642. * This flag can be used for type testing.
  40643. *
  40644. * @type {boolean}
  40645. * @readonly
  40646. * @default true
  40647. */
  40648. this.isRenderer = true;
  40649. //
  40650. const {
  40651. logarithmicDepthBuffer = false,
  40652. alpha = true,
  40653. depth = true,
  40654. stencil = false,
  40655. antialias = false,
  40656. samples = 0,
  40657. getFallback = null,
  40658. colorBufferType = HalfFloatType,
  40659. multiview = false
  40660. } = parameters;
  40661. /**
  40662. * A reference to the current backend.
  40663. *
  40664. * @type {Backend}
  40665. */
  40666. this.backend = backend;
  40667. /**
  40668. * Whether the renderer should automatically clear the current rendering target
  40669. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  40670. * or the current bound render target (custom framebuffer).
  40671. *
  40672. * @type {boolean}
  40673. * @default true
  40674. */
  40675. this.autoClear = true;
  40676. /**
  40677. * When `autoClear` is set to `true`, this property defines whether the renderer
  40678. * should clear the color buffer.
  40679. *
  40680. * @type {boolean}
  40681. * @default true
  40682. */
  40683. this.autoClearColor = true;
  40684. /**
  40685. * When `autoClear` is set to `true`, this property defines whether the renderer
  40686. * should clear the depth buffer.
  40687. *
  40688. * @type {boolean}
  40689. * @default true
  40690. */
  40691. this.autoClearDepth = true;
  40692. /**
  40693. * When `autoClear` is set to `true`, this property defines whether the renderer
  40694. * should clear the stencil buffer.
  40695. *
  40696. * @type {boolean}
  40697. * @default true
  40698. */
  40699. this.autoClearStencil = true;
  40700. /**
  40701. * Whether the default framebuffer should be transparent or opaque.
  40702. *
  40703. * @type {boolean}
  40704. * @default true
  40705. */
  40706. this.alpha = alpha;
  40707. /**
  40708. * Whether logarithmic depth buffer is enabled or not.
  40709. *
  40710. * @type {boolean}
  40711. * @default false
  40712. */
  40713. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  40714. /**
  40715. * Defines the output color space of the renderer.
  40716. *
  40717. * @type {string}
  40718. * @default SRGBColorSpace
  40719. */
  40720. this.outputColorSpace = SRGBColorSpace;
  40721. /**
  40722. * Defines the tone mapping of the renderer.
  40723. *
  40724. * @type {number}
  40725. * @default NoToneMapping
  40726. */
  40727. this.toneMapping = NoToneMapping;
  40728. /**
  40729. * Defines the tone mapping exposure.
  40730. *
  40731. * @type {number}
  40732. * @default 1
  40733. */
  40734. this.toneMappingExposure = 1.0;
  40735. /**
  40736. * Whether the renderer should sort its render lists or not.
  40737. *
  40738. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  40739. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  40740. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  40741. * e.g. manually determining each object's rendering order.
  40742. *
  40743. * @type {boolean}
  40744. * @default true
  40745. */
  40746. this.sortObjects = true;
  40747. /**
  40748. * Whether the default framebuffer should have a depth buffer or not.
  40749. *
  40750. * @type {boolean}
  40751. * @default true
  40752. */
  40753. this.depth = depth;
  40754. /**
  40755. * Whether the default framebuffer should have a stencil buffer or not.
  40756. *
  40757. * @type {boolean}
  40758. * @default false
  40759. */
  40760. this.stencil = stencil;
  40761. /**
  40762. * Holds a series of statistical information about the GPU memory
  40763. * and the rendering process. Useful for debugging and monitoring.
  40764. *
  40765. * @type {Info}
  40766. */
  40767. this.info = new Info();
  40768. /**
  40769. * A global context node that stores override nodes for specific transformations or calculations.
  40770. * These nodes can be used to replace default behavior in the rendering pipeline.
  40771. *
  40772. * @type {ContextNode}
  40773. * @property {Object} value - The context value object.
  40774. */
  40775. this.contextNode = context();
  40776. /**
  40777. * The node library defines how certain library objects like materials, lights
  40778. * or tone mapping functions are mapped to node types. This is required since
  40779. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  40780. * be part of the scene graph, they are internally represented as nodes for
  40781. * further processing.
  40782. *
  40783. * @type {NodeLibrary}
  40784. */
  40785. this.library = new NodeLibrary();
  40786. /**
  40787. * A map-like data structure for managing lights.
  40788. *
  40789. * @type {Lighting}
  40790. */
  40791. this.lighting = new Lighting();
  40792. // internals
  40793. /**
  40794. * The number of MSAA samples.
  40795. *
  40796. * @private
  40797. * @type {number}
  40798. * @default 0
  40799. */
  40800. this._samples = samples || ( antialias === true ) ? 4 : 0;
  40801. /**
  40802. * OnCanvasTargetResize callback function.
  40803. *
  40804. * @private
  40805. * @type {Function}
  40806. */
  40807. this._onCanvasTargetResize = this._onCanvasTargetResize.bind( this );
  40808. /**
  40809. * The canvas target for rendering.
  40810. *
  40811. * @private
  40812. * @type {CanvasTarget}
  40813. */
  40814. this._canvasTarget = new CanvasTarget( backend.getDomElement() );
  40815. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  40816. this._canvasTarget.isDefaultCanvasTarget = true;
  40817. /**
  40818. * The inspector provides information about the internal renderer state.
  40819. *
  40820. * @private
  40821. * @type {InspectorBase}
  40822. */
  40823. this._inspector = new InspectorBase();
  40824. this._inspector.setRenderer( this );
  40825. /**
  40826. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  40827. *
  40828. * @private
  40829. * @type {?Function}
  40830. */
  40831. this._getFallback = getFallback;
  40832. /**
  40833. * A reference to a renderer module for managing shader attributes.
  40834. *
  40835. * @private
  40836. * @type {?Attributes}
  40837. * @default null
  40838. */
  40839. this._attributes = null;
  40840. /**
  40841. * A reference to a renderer module for managing geometries.
  40842. *
  40843. * @private
  40844. * @type {?Geometries}
  40845. * @default null
  40846. */
  40847. this._geometries = null;
  40848. /**
  40849. * A reference to a renderer module for managing node related logic.
  40850. *
  40851. * @private
  40852. * @type {?Nodes}
  40853. * @default null
  40854. */
  40855. this._nodes = null;
  40856. /**
  40857. * A reference to a renderer module for managing the internal animation loop.
  40858. *
  40859. * @private
  40860. * @type {?Animation}
  40861. * @default null
  40862. */
  40863. this._animation = null;
  40864. /**
  40865. * A reference to a renderer module for managing shader program bindings.
  40866. *
  40867. * @private
  40868. * @type {?Bindings}
  40869. * @default null
  40870. */
  40871. this._bindings = null;
  40872. /**
  40873. * A reference to a renderer module for managing render objects.
  40874. *
  40875. * @private
  40876. * @type {?RenderObjects}
  40877. * @default null
  40878. */
  40879. this._objects = null;
  40880. /**
  40881. * A reference to a renderer module for managing render and compute pipelines.
  40882. *
  40883. * @private
  40884. * @type {?Pipelines}
  40885. * @default null
  40886. */
  40887. this._pipelines = null;
  40888. /**
  40889. * A reference to a renderer module for managing render bundles.
  40890. *
  40891. * @private
  40892. * @type {?RenderBundles}
  40893. * @default null
  40894. */
  40895. this._bundles = null;
  40896. /**
  40897. * A reference to a renderer module for managing render lists.
  40898. *
  40899. * @private
  40900. * @type {?RenderLists}
  40901. * @default null
  40902. */
  40903. this._renderLists = null;
  40904. /**
  40905. * A reference to a renderer module for managing render contexts.
  40906. *
  40907. * @private
  40908. * @type {?RenderContexts}
  40909. * @default null
  40910. */
  40911. this._renderContexts = null;
  40912. /**
  40913. * A reference to a renderer module for managing textures.
  40914. *
  40915. * @private
  40916. * @type {?Textures}
  40917. * @default null
  40918. */
  40919. this._textures = null;
  40920. /**
  40921. * A reference to a renderer module for backgrounds.
  40922. *
  40923. * @private
  40924. * @type {?Background}
  40925. * @default null
  40926. */
  40927. this._background = null;
  40928. /**
  40929. * This fullscreen quad is used for internal render passes
  40930. * like the tone mapping and color space output pass.
  40931. *
  40932. * @private
  40933. * @type {QuadMesh}
  40934. */
  40935. this._quad = new QuadMesh( new NodeMaterial() );
  40936. this._quad.name = 'Output Color Transform';
  40937. this._quad.material.name = 'outputColorTransform';
  40938. /**
  40939. * A reference to the current render context.
  40940. *
  40941. * @private
  40942. * @type {?RenderContext}
  40943. * @default null
  40944. */
  40945. this._currentRenderContext = null;
  40946. /**
  40947. * A custom sort function for the opaque render list.
  40948. *
  40949. * @private
  40950. * @type {?Function}
  40951. * @default null
  40952. */
  40953. this._opaqueSort = null;
  40954. /**
  40955. * A custom sort function for the transparent render list.
  40956. *
  40957. * @private
  40958. * @type {?Function}
  40959. * @default null
  40960. */
  40961. this._transparentSort = null;
  40962. /**
  40963. * The framebuffer target.
  40964. *
  40965. * @private
  40966. * @type {?RenderTarget}
  40967. * @default null
  40968. */
  40969. this._frameBufferTarget = null;
  40970. const alphaClear = this.alpha === true ? 0 : 1;
  40971. /**
  40972. * The clear color value.
  40973. *
  40974. * @private
  40975. * @type {Color4}
  40976. */
  40977. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  40978. /**
  40979. * The clear depth value.
  40980. *
  40981. * @private
  40982. * @type {number}
  40983. * @default 1
  40984. */
  40985. this._clearDepth = 1;
  40986. /**
  40987. * The clear stencil value.
  40988. *
  40989. * @private
  40990. * @type {number}
  40991. * @default 0
  40992. */
  40993. this._clearStencil = 0;
  40994. /**
  40995. * The current render target.
  40996. *
  40997. * @private
  40998. * @type {?RenderTarget}
  40999. * @default null
  41000. */
  41001. this._renderTarget = null;
  41002. /**
  41003. * The active cube face.
  41004. *
  41005. * @private
  41006. * @type {number}
  41007. * @default 0
  41008. */
  41009. this._activeCubeFace = 0;
  41010. /**
  41011. * The active mipmap level.
  41012. *
  41013. * @private
  41014. * @type {number}
  41015. * @default 0
  41016. */
  41017. this._activeMipmapLevel = 0;
  41018. /**
  41019. * The current output render target.
  41020. *
  41021. * @private
  41022. * @type {?RenderTarget}
  41023. * @default null
  41024. */
  41025. this._outputRenderTarget = null;
  41026. /**
  41027. * The MRT setting.
  41028. *
  41029. * @private
  41030. * @type {?MRTNode}
  41031. * @default null
  41032. */
  41033. this._mrt = null;
  41034. /**
  41035. * This function defines how a render object is going
  41036. * to be rendered.
  41037. *
  41038. * @private
  41039. * @type {?Function}
  41040. * @default null
  41041. */
  41042. this._renderObjectFunction = null;
  41043. /**
  41044. * Used to keep track of the current render object function.
  41045. *
  41046. * @private
  41047. * @type {?Function}
  41048. * @default null
  41049. */
  41050. this._currentRenderObjectFunction = null;
  41051. /**
  41052. * Used to keep track of the current render bundle.
  41053. *
  41054. * @private
  41055. * @type {?RenderBundle}
  41056. * @default null
  41057. */
  41058. this._currentRenderBundle = null;
  41059. /**
  41060. * Next to `_renderObjectFunction()`, this function provides another hook
  41061. * for influencing the render process of a render object. It is meant for internal
  41062. * use and only relevant for `compileAsync()` right now. Instead of using
  41063. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  41064. * a different function might be used which performs no draw but just the node
  41065. * and pipeline updates.
  41066. *
  41067. * @private
  41068. * @type {?Function}
  41069. * @default null
  41070. */
  41071. this._handleObjectFunction = this._renderObjectDirect;
  41072. /**
  41073. * Indicates whether the device has been lost or not. In WebGL terms, the device
  41074. * lost is considered as a context lost. When this is set to `true`, rendering
  41075. * isn't possible anymore.
  41076. *
  41077. * @private
  41078. * @type {boolean}
  41079. * @default false
  41080. */
  41081. this._isDeviceLost = false;
  41082. /**
  41083. * A callback function that defines what should happen when a device/context lost occurs.
  41084. *
  41085. * @type {Function}
  41086. */
  41087. this.onDeviceLost = this._onDeviceLost;
  41088. /**
  41089. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  41090. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  41091. * This will reduce rendering quality though.
  41092. *
  41093. * @private
  41094. * @type {number}
  41095. * @default HalfFloatType
  41096. */
  41097. this._colorBufferType = colorBufferType;
  41098. /**
  41099. * A cache for shadow nodes per material
  41100. *
  41101. * @private
  41102. * @type {WeakMap<Material, Object>}
  41103. */
  41104. this._cacheShadowNodes = new WeakMap();
  41105. /**
  41106. * Whether the renderer has been initialized or not.
  41107. *
  41108. * @private
  41109. * @type {boolean}
  41110. * @default false
  41111. */
  41112. this._initialized = false;
  41113. /**
  41114. * A reference to the promise which initializes the renderer.
  41115. *
  41116. * @private
  41117. * @type {?Promise<this>}
  41118. * @default null
  41119. */
  41120. this._initPromise = null;
  41121. /**
  41122. * An array of compilation promises which are used in `compileAsync()`.
  41123. *
  41124. * @private
  41125. * @type {?Array<Promise>}
  41126. * @default null
  41127. */
  41128. this._compilationPromises = null;
  41129. /**
  41130. * Whether the renderer should render transparent render objects or not.
  41131. *
  41132. * @type {boolean}
  41133. * @default true
  41134. */
  41135. this.transparent = true;
  41136. /**
  41137. * Whether the renderer should render opaque render objects or not.
  41138. *
  41139. * @type {boolean}
  41140. * @default true
  41141. */
  41142. this.opaque = true;
  41143. /**
  41144. * Shadow map configuration
  41145. * @typedef {Object} ShadowMapConfig
  41146. * @property {boolean} enabled - Whether to globally enable shadows or not.
  41147. * @property {number} type - The shadow map type.
  41148. */
  41149. /**
  41150. * The renderer's shadow configuration.
  41151. *
  41152. * @type {ShadowMapConfig}
  41153. */
  41154. this.shadowMap = {
  41155. enabled: false,
  41156. type: PCFShadowMap
  41157. };
  41158. /**
  41159. * XR configuration.
  41160. * @typedef {Object} XRConfig
  41161. * @property {boolean} enabled - Whether to globally enable XR or not.
  41162. */
  41163. /**
  41164. * The renderer's XR manager.
  41165. *
  41166. * @type {XRManager}
  41167. */
  41168. this.xr = new XRManager( this, multiview );
  41169. /**
  41170. * Debug configuration.
  41171. * @typedef {Object} DebugConfig
  41172. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  41173. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  41174. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  41175. */
  41176. /**
  41177. * The renderer's debug configuration.
  41178. *
  41179. * @type {DebugConfig}
  41180. */
  41181. this.debug = {
  41182. checkShaderErrors: true,
  41183. onShaderError: null,
  41184. getShaderAsync: async ( scene, camera, object ) => {
  41185. await this.compileAsync( scene, camera );
  41186. const renderList = this._renderLists.get( scene, camera );
  41187. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget, this._mrt );
  41188. const material = scene.overrideMaterial || object.material;
  41189. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  41190. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  41191. return { fragmentShader, vertexShader };
  41192. }
  41193. };
  41194. }
  41195. /**
  41196. * Initializes the renderer so it is ready for usage.
  41197. *
  41198. * @async
  41199. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  41200. */
  41201. async init() {
  41202. if ( this._initPromise !== null ) {
  41203. return this._initPromise;
  41204. }
  41205. this._initPromise = new Promise( async ( resolve, reject ) => {
  41206. let backend = this.backend;
  41207. try {
  41208. await backend.init( this );
  41209. } catch ( error ) {
  41210. if ( this._getFallback !== null ) {
  41211. // try the fallback
  41212. try {
  41213. this.backend = backend = this._getFallback( error );
  41214. await backend.init( this );
  41215. } catch ( error ) {
  41216. reject( error );
  41217. return;
  41218. }
  41219. } else {
  41220. reject( error );
  41221. return;
  41222. }
  41223. }
  41224. this._nodes = new Nodes( this, backend );
  41225. this._animation = new Animation( this, this._nodes, this.info );
  41226. this._attributes = new Attributes( backend );
  41227. this._background = new Background( this, this._nodes );
  41228. this._geometries = new Geometries( this._attributes, this.info );
  41229. this._textures = new Textures( this, backend, this.info );
  41230. this._pipelines = new Pipelines( backend, this._nodes );
  41231. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  41232. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  41233. this._renderLists = new RenderLists( this.lighting );
  41234. this._bundles = new RenderBundles();
  41235. this._renderContexts = new RenderContexts();
  41236. //
  41237. this._animation.start();
  41238. this._initialized = true;
  41239. //
  41240. this._inspector.init();
  41241. //
  41242. resolve( this );
  41243. } );
  41244. return this._initPromise;
  41245. }
  41246. /**
  41247. * A reference to the canvas element the renderer is drawing to.
  41248. * This value of this property will automatically be created by
  41249. * the renderer.
  41250. *
  41251. * @type {HTMLCanvasElement|OffscreenCanvas}
  41252. */
  41253. get domElement() {
  41254. return this._canvasTarget.domElement;
  41255. }
  41256. /**
  41257. * The coordinate system of the renderer. The value of this property
  41258. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  41259. * `THREE.WebGPUCoordinateSystem`.
  41260. *
  41261. * @readonly
  41262. * @type {number}
  41263. */
  41264. get coordinateSystem() {
  41265. return this.backend.coordinateSystem;
  41266. }
  41267. /**
  41268. * Compiles all materials in the given scene. This can be useful to avoid a
  41269. * phenomenon which is called "shader compilation stutter", which occurs when
  41270. * rendering an object with a new shader for the first time.
  41271. *
  41272. * If you want to add a 3D object to an existing scene, use the third optional
  41273. * parameter for applying the target scene. Note that the (target) scene's lighting
  41274. * and environment must be configured before calling this method.
  41275. *
  41276. * @async
  41277. * @param {Object3D} scene - The scene or 3D object to precompile.
  41278. * @param {Camera} camera - The camera that is used to render the scene.
  41279. * @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.
  41280. * @return {Promise} A Promise that resolves when the compile has been finished.
  41281. */
  41282. async compileAsync( scene, camera, targetScene = null ) {
  41283. if ( this._isDeviceLost === true ) return;
  41284. if ( this._initialized === false ) await this.init();
  41285. // preserve render tree
  41286. const nodeFrame = this._nodes.nodeFrame;
  41287. const previousRenderId = nodeFrame.renderId;
  41288. const previousRenderContext = this._currentRenderContext;
  41289. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  41290. const previousCompilationPromises = this._compilationPromises;
  41291. //
  41292. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  41293. if ( targetScene === null ) targetScene = scene;
  41294. const renderTarget = this._renderTarget;
  41295. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget, this._mrt );
  41296. const activeMipmapLevel = this._activeMipmapLevel;
  41297. const compilationPromises = [];
  41298. this._currentRenderContext = renderContext;
  41299. this._currentRenderObjectFunction = this.renderObject;
  41300. this._handleObjectFunction = this._createObjectPipeline;
  41301. this._compilationPromises = compilationPromises;
  41302. nodeFrame.renderId ++;
  41303. //
  41304. nodeFrame.update();
  41305. //
  41306. renderContext.depth = this.depth;
  41307. renderContext.stencil = this.stencil;
  41308. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  41309. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  41310. //
  41311. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  41312. //
  41313. const renderList = this._renderLists.get( scene, camera );
  41314. renderList.begin();
  41315. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  41316. // include lights from target scene
  41317. if ( targetScene !== scene ) {
  41318. targetScene.traverseVisible( function ( object ) {
  41319. if ( object.isLight && object.layers.test( camera.layers ) ) {
  41320. renderList.pushLight( object );
  41321. }
  41322. } );
  41323. }
  41324. renderList.finish();
  41325. //
  41326. if ( renderTarget !== null ) {
  41327. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  41328. const renderTargetData = this._textures.get( renderTarget );
  41329. renderContext.textures = renderTargetData.textures;
  41330. renderContext.depthTexture = renderTargetData.depthTexture;
  41331. } else {
  41332. renderContext.textures = null;
  41333. renderContext.depthTexture = null;
  41334. }
  41335. //
  41336. this._background.update( sceneRef, renderList, renderContext );
  41337. // process render lists
  41338. const opaqueObjects = renderList.opaque;
  41339. const transparentObjects = renderList.transparent;
  41340. const transparentDoublePassObjects = renderList.transparentDoublePass;
  41341. const lightsNode = renderList.lightsNode;
  41342. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  41343. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  41344. // restore render tree
  41345. nodeFrame.renderId = previousRenderId;
  41346. this._currentRenderContext = previousRenderContext;
  41347. this._currentRenderObjectFunction = previousRenderObjectFunction;
  41348. this._compilationPromises = previousCompilationPromises;
  41349. this._handleObjectFunction = this._renderObjectDirect;
  41350. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  41351. await Promise.all( compilationPromises );
  41352. }
  41353. /**
  41354. * Renders the scene in an async fashion.
  41355. *
  41356. * @async
  41357. * @deprecated
  41358. * @param {Object3D} scene - The scene or 3D object to render.
  41359. * @param {Camera} camera - The camera.
  41360. * @return {Promise} A Promise that resolves when the render has been finished.
  41361. */
  41362. async renderAsync( scene, camera ) {
  41363. warnOnce( 'Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41364. await this.init();
  41365. this.render( scene, camera );
  41366. }
  41367. /**
  41368. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  41369. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  41370. *
  41371. * @async
  41372. * @deprecated
  41373. * @return {Promise} A Promise that resolves when synchronization has been finished.
  41374. */
  41375. async waitForGPU() {
  41376. error( 'Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.' );
  41377. }
  41378. //
  41379. set inspector( value ) {
  41380. if ( this._inspector !== null ) {
  41381. this._inspector.setRenderer( null );
  41382. }
  41383. this._inspector = value;
  41384. this._inspector.setRenderer( this );
  41385. }
  41386. /**
  41387. * The inspector instance. The inspector can be any class that extends from `InspectorBase`.
  41388. *
  41389. * @type {InspectorBase}
  41390. */
  41391. get inspector() {
  41392. return this._inspector;
  41393. }
  41394. /**
  41395. * Enables or disables high precision for model-view and normal-view matrices.
  41396. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  41397. *
  41398. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  41399. *
  41400. * @param {boolean} value - Whether to enable or disable high precision.
  41401. * @type {boolean}
  41402. */
  41403. set highPrecision( value ) {
  41404. const contextNodeData = this.contextNode.value;
  41405. if ( value === true ) {
  41406. contextNodeData.modelViewMatrix = highpModelViewMatrix;
  41407. contextNodeData.modelNormalViewMatrix = highpModelNormalViewMatrix;
  41408. } else if ( this.highPrecision ) {
  41409. delete contextNodeData.modelViewMatrix;
  41410. delete contextNodeData.modelNormalViewMatrix;
  41411. }
  41412. }
  41413. /**
  41414. * Returns whether high precision is enabled or not.
  41415. *
  41416. * @return {boolean} Whether high precision is enabled or not.
  41417. * @type {boolean}
  41418. */
  41419. get highPrecision() {
  41420. const contextNodeData = this.contextNode.value;
  41421. return contextNodeData.modelViewMatrix === highpModelViewMatrix && contextNodeData.modelNormalViewMatrix === highpModelNormalViewMatrix;
  41422. }
  41423. /**
  41424. * Sets the given MRT configuration.
  41425. *
  41426. * @param {MRTNode} mrt - The MRT node to set.
  41427. * @return {Renderer} A reference to this renderer.
  41428. */
  41429. setMRT( mrt ) {
  41430. this._mrt = mrt;
  41431. return this;
  41432. }
  41433. /**
  41434. * Returns the MRT configuration.
  41435. *
  41436. * @return {MRTNode} The MRT configuration.
  41437. */
  41438. getMRT() {
  41439. return this._mrt;
  41440. }
  41441. /**
  41442. * Returns the color buffer type.
  41443. *
  41444. * @return {number} The color buffer type.
  41445. */
  41446. getColorBufferType() {
  41447. return this._colorBufferType;
  41448. }
  41449. /**
  41450. * Default implementation of the device lost callback.
  41451. *
  41452. * @private
  41453. * @param {Object} info - Information about the context lost.
  41454. */
  41455. _onDeviceLost( info ) {
  41456. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  41457. if ( info.reason ) {
  41458. errorMessage += `\nReason: ${info.reason}`;
  41459. }
  41460. error( errorMessage );
  41461. this._isDeviceLost = true;
  41462. }
  41463. /**
  41464. * Renders the given render bundle.
  41465. *
  41466. * @private
  41467. * @param {Object} bundle - Render bundle data.
  41468. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  41469. * @param {LightsNode} lightsNode - The lights node.
  41470. */
  41471. _renderBundle( bundle, sceneRef, lightsNode ) {
  41472. const { bundleGroup, camera, renderList } = bundle;
  41473. const renderContext = this._currentRenderContext;
  41474. //
  41475. const renderBundle = this._bundles.get( bundleGroup, camera );
  41476. const renderBundleData = this.backend.get( renderBundle );
  41477. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  41478. //
  41479. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  41480. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  41481. renderBundleData.renderContexts.add( renderContext );
  41482. if ( renderBundleNeedsUpdate ) {
  41483. this.backend.beginBundle( renderContext );
  41484. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  41485. renderBundleData.renderObjects = [];
  41486. }
  41487. this._currentRenderBundle = renderBundle;
  41488. const {
  41489. transparentDoublePass: transparentDoublePassObjects,
  41490. transparent: transparentObjects,
  41491. opaque: opaqueObjects
  41492. } = renderList;
  41493. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  41494. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  41495. this._currentRenderBundle = null;
  41496. //
  41497. this.backend.finishBundle( renderContext, renderBundle );
  41498. renderBundleData.version = bundleGroup.version;
  41499. } else {
  41500. const { renderObjects } = renderBundleData;
  41501. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  41502. const renderObject = renderObjects[ i ];
  41503. if ( this._nodes.needsRefresh( renderObject ) ) {
  41504. this._nodes.updateBefore( renderObject );
  41505. this._nodes.updateForRender( renderObject );
  41506. this._bindings.updateForRender( renderObject );
  41507. this._nodes.updateAfter( renderObject );
  41508. }
  41509. }
  41510. }
  41511. this.backend.addBundle( renderContext, renderBundle );
  41512. }
  41513. /**
  41514. * Renders the scene or 3D object with the given camera. This method can only be called
  41515. * if the renderer has been initialized. When using `render()` inside an animation loop,
  41516. * it's guaranteed the renderer will be initialized. The animation loop must be defined
  41517. * with {@link Renderer#setAnimationLoop} though.
  41518. *
  41519. * For all other use cases (like when using on-demand rendering), you must call
  41520. * {@link Renderer#init} before rendering.
  41521. *
  41522. * The target of the method is the default framebuffer (meaning the canvas)
  41523. * or alternatively a render target when specified via `setRenderTarget()`.
  41524. *
  41525. * @param {Object3D} scene - The scene or 3D object to render.
  41526. * @param {Camera} camera - The camera to render the scene with.
  41527. */
  41528. render( scene, camera ) {
  41529. if ( this._initialized === false ) {
  41530. throw new Error( 'Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.' );
  41531. }
  41532. this._renderScene( scene, camera );
  41533. }
  41534. /**
  41535. * Returns whether the renderer has been initialized or not.
  41536. *
  41537. * @readonly
  41538. * @return {boolean} Whether the renderer has been initialized or not.
  41539. */
  41540. get initialized() {
  41541. return this._initialized;
  41542. }
  41543. /**
  41544. * Returns an internal render target which is used when computing the output tone mapping
  41545. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  41546. * pass and not inline to achieve more correct results.
  41547. *
  41548. * @private
  41549. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  41550. */
  41551. _getFrameBufferTarget() {
  41552. const { currentToneMapping, currentColorSpace } = this;
  41553. const useToneMapping = currentToneMapping !== NoToneMapping;
  41554. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  41555. if ( useToneMapping === false && useColorSpace === false ) return null;
  41556. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  41557. const { depth, stencil } = this;
  41558. let frameBufferTarget = this._frameBufferTarget;
  41559. if ( frameBufferTarget === null ) {
  41560. frameBufferTarget = new RenderTarget( width, height, {
  41561. depthBuffer: depth,
  41562. stencilBuffer: stencil,
  41563. type: this._colorBufferType,
  41564. format: RGBAFormat,
  41565. colorSpace: ColorManagement.workingColorSpace,
  41566. generateMipmaps: false,
  41567. minFilter: LinearFilter,
  41568. magFilter: LinearFilter,
  41569. samples: this.samples
  41570. } );
  41571. frameBufferTarget.isPostProcessingRenderTarget = true;
  41572. this._frameBufferTarget = frameBufferTarget;
  41573. }
  41574. const outputRenderTarget = this.getOutputRenderTarget();
  41575. frameBufferTarget.depthBuffer = depth;
  41576. frameBufferTarget.stencilBuffer = stencil;
  41577. if ( outputRenderTarget !== null ) {
  41578. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  41579. } else {
  41580. frameBufferTarget.setSize( width, height, 1 );
  41581. }
  41582. const canvasTarget = this._canvasTarget;
  41583. frameBufferTarget.viewport.copy( canvasTarget._viewport );
  41584. frameBufferTarget.scissor.copy( canvasTarget._scissor );
  41585. frameBufferTarget.viewport.multiplyScalar( canvasTarget._pixelRatio );
  41586. frameBufferTarget.scissor.multiplyScalar( canvasTarget._pixelRatio );
  41587. frameBufferTarget.scissorTest = canvasTarget._scissorTest;
  41588. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  41589. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  41590. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  41591. return frameBufferTarget;
  41592. }
  41593. /**
  41594. * Renders the scene or 3D object with the given camera.
  41595. *
  41596. * @private
  41597. * @param {Object3D} scene - The scene or 3D object to render.
  41598. * @param {Camera} camera - The camera to render the scene with.
  41599. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  41600. * @return {RenderContext} The current render context.
  41601. */
  41602. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  41603. if ( this._isDeviceLost === true ) return;
  41604. //
  41605. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  41606. // preserve render tree
  41607. const nodeFrame = this._nodes.nodeFrame;
  41608. const previousRenderId = nodeFrame.renderId;
  41609. const previousRenderContext = this._currentRenderContext;
  41610. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  41611. //
  41612. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  41613. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  41614. const activeCubeFace = this._activeCubeFace;
  41615. const activeMipmapLevel = this._activeMipmapLevel;
  41616. //
  41617. let renderTarget;
  41618. if ( frameBufferTarget !== null ) {
  41619. renderTarget = frameBufferTarget;
  41620. this.setRenderTarget( renderTarget );
  41621. } else {
  41622. renderTarget = outputRenderTarget;
  41623. }
  41624. //
  41625. const renderContext = this._renderContexts.get( scene, camera, renderTarget, this._mrt );
  41626. this._currentRenderContext = renderContext;
  41627. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  41628. //
  41629. this.info.calls ++;
  41630. this.info.render.calls ++;
  41631. this.info.render.frameCalls ++;
  41632. nodeFrame.renderId = this.info.calls;
  41633. //
  41634. this.backend.updateTimeStampUID( renderContext );
  41635. this.inspector.beginRender( this.backend.getTimestampUID( renderContext ), scene, camera, renderTarget );
  41636. //
  41637. const coordinateSystem = this.coordinateSystem;
  41638. const xr = this.xr;
  41639. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  41640. camera.coordinateSystem = coordinateSystem;
  41641. camera.updateProjectionMatrix();
  41642. if ( camera.isArrayCamera ) {
  41643. for ( const subCamera of camera.cameras ) {
  41644. subCamera.coordinateSystem = coordinateSystem;
  41645. subCamera.updateProjectionMatrix();
  41646. }
  41647. }
  41648. }
  41649. //
  41650. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  41651. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  41652. if ( xr.enabled === true && xr.isPresenting === true ) {
  41653. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  41654. camera = xr.getCamera(); // use XR camera for rendering
  41655. }
  41656. //
  41657. const canvasTarget = this._canvasTarget;
  41658. let viewport = canvasTarget._viewport;
  41659. let scissor = canvasTarget._scissor;
  41660. let pixelRatio = canvasTarget._pixelRatio;
  41661. if ( renderTarget !== null ) {
  41662. viewport = renderTarget.viewport;
  41663. scissor = renderTarget.scissor;
  41664. pixelRatio = 1;
  41665. }
  41666. this.getDrawingBufferSize( _drawingBufferSize );
  41667. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  41668. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  41669. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  41670. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  41671. renderContext.viewportValue.width >>= activeMipmapLevel;
  41672. renderContext.viewportValue.height >>= activeMipmapLevel;
  41673. renderContext.viewportValue.minDepth = minDepth;
  41674. renderContext.viewportValue.maxDepth = maxDepth;
  41675. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  41676. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  41677. renderContext.scissor = canvasTarget._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  41678. renderContext.scissorValue.width >>= activeMipmapLevel;
  41679. renderContext.scissorValue.height >>= activeMipmapLevel;
  41680. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  41681. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  41682. //
  41683. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  41684. //
  41685. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  41686. if ( ! camera.isArrayCamera ) {
  41687. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  41688. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  41689. }
  41690. const renderList = this._renderLists.get( scene, camera );
  41691. renderList.begin();
  41692. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  41693. renderList.finish();
  41694. if ( this.sortObjects === true ) {
  41695. renderList.sort( this._opaqueSort, this._transparentSort );
  41696. }
  41697. //
  41698. if ( renderTarget !== null ) {
  41699. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  41700. const renderTargetData = this._textures.get( renderTarget );
  41701. renderContext.textures = renderTargetData.textures;
  41702. renderContext.depthTexture = renderTargetData.depthTexture;
  41703. renderContext.width = renderTargetData.width;
  41704. renderContext.height = renderTargetData.height;
  41705. renderContext.renderTarget = renderTarget;
  41706. renderContext.depth = renderTarget.depthBuffer;
  41707. renderContext.stencil = renderTarget.stencilBuffer;
  41708. } else {
  41709. renderContext.textures = null;
  41710. renderContext.depthTexture = null;
  41711. renderContext.width = _drawingBufferSize.width;
  41712. renderContext.height = _drawingBufferSize.height;
  41713. renderContext.depth = this.depth;
  41714. renderContext.stencil = this.stencil;
  41715. }
  41716. renderContext.width >>= activeMipmapLevel;
  41717. renderContext.height >>= activeMipmapLevel;
  41718. renderContext.activeCubeFace = activeCubeFace;
  41719. renderContext.activeMipmapLevel = activeMipmapLevel;
  41720. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  41721. //
  41722. renderContext.scissorValue.max( _vector4.set( 0, 0, 0, 0 ) );
  41723. if ( renderContext.scissorValue.x + renderContext.scissorValue.width > renderContext.width ) {
  41724. renderContext.scissorValue.width = Math.max( renderContext.width - renderContext.scissorValue.x, 0 );
  41725. }
  41726. if ( renderContext.scissorValue.y + renderContext.scissorValue.height > renderContext.height ) {
  41727. renderContext.scissorValue.height = Math.max( renderContext.height - renderContext.scissorValue.y, 0 );
  41728. }
  41729. //
  41730. this._background.update( sceneRef, renderList, renderContext );
  41731. //
  41732. renderContext.camera = camera;
  41733. this.backend.beginRender( renderContext );
  41734. // process render lists
  41735. const {
  41736. bundles,
  41737. lightsNode,
  41738. transparentDoublePass: transparentDoublePassObjects,
  41739. transparent: transparentObjects,
  41740. opaque: opaqueObjects
  41741. } = renderList;
  41742. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  41743. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  41744. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  41745. // finish render pass
  41746. this.backend.finishRender( renderContext );
  41747. // restore render tree
  41748. nodeFrame.renderId = previousRenderId;
  41749. this._currentRenderContext = previousRenderContext;
  41750. this._currentRenderObjectFunction = previousRenderObjectFunction;
  41751. //
  41752. if ( frameBufferTarget !== null ) {
  41753. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  41754. this._renderOutput( renderTarget );
  41755. }
  41756. //
  41757. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  41758. //
  41759. this.inspector.finishRender( this.backend.getTimestampUID( renderContext ) );
  41760. //
  41761. return renderContext;
  41762. }
  41763. _setXRLayerSize( width, height ) {
  41764. // TODO: Find a better solution to resize the canvas when in XR.
  41765. this._canvasTarget._width = width;
  41766. this._canvasTarget._height = height;
  41767. this.setViewport( 0, 0, width, height );
  41768. }
  41769. /**
  41770. * The output pass performs tone mapping and color space conversion.
  41771. *
  41772. * @private
  41773. * @param {RenderTarget} renderTarget - The current render target.
  41774. */
  41775. _renderOutput( renderTarget ) {
  41776. const quad = this._quad;
  41777. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  41778. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  41779. quad.material.needsUpdate = true;
  41780. }
  41781. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  41782. const currentAutoClear = this.autoClear;
  41783. const currentXR = this.xr.enabled;
  41784. this.autoClear = false;
  41785. this.xr.enabled = false;
  41786. this._renderScene( quad, quad.camera, false );
  41787. this.autoClear = currentAutoClear;
  41788. this.xr.enabled = currentXR;
  41789. }
  41790. /**
  41791. * Returns the maximum available anisotropy for texture filtering.
  41792. *
  41793. * @return {number} The maximum available anisotropy.
  41794. */
  41795. getMaxAnisotropy() {
  41796. return this.backend.getMaxAnisotropy();
  41797. }
  41798. /**
  41799. * Returns the active cube face.
  41800. *
  41801. * @return {number} The active cube face.
  41802. */
  41803. getActiveCubeFace() {
  41804. return this._activeCubeFace;
  41805. }
  41806. /**
  41807. * Returns the active mipmap level.
  41808. *
  41809. * @return {number} The active mipmap level.
  41810. */
  41811. getActiveMipmapLevel() {
  41812. return this._activeMipmapLevel;
  41813. }
  41814. /**
  41815. * Applications are advised to always define the animation loop
  41816. * with this method and not manually with `requestAnimationFrame()`
  41817. * for best compatibility.
  41818. *
  41819. * @async
  41820. * @param {?onAnimationCallback} callback - The application's animation loop.
  41821. * @return {Promise} A Promise that resolves when the set has been executed.
  41822. */
  41823. async setAnimationLoop( callback ) {
  41824. if ( this._initialized === false ) await this.init();
  41825. this._animation.setAnimationLoop( callback );
  41826. }
  41827. /**
  41828. * Returns the current animation loop callback.
  41829. *
  41830. * @return {?Function} The current animation loop callback.
  41831. */
  41832. getAnimationLoop() {
  41833. return this._animation.getAnimationLoop();
  41834. }
  41835. /**
  41836. * Can be used to transfer buffer data from a storage buffer attribute
  41837. * from the GPU to the CPU in context of compute shaders.
  41838. *
  41839. * @async
  41840. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  41841. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  41842. */
  41843. async getArrayBufferAsync( attribute ) {
  41844. return await this.backend.getArrayBufferAsync( attribute );
  41845. }
  41846. /**
  41847. * Returns the rendering context.
  41848. *
  41849. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  41850. */
  41851. getContext() {
  41852. return this.backend.getContext();
  41853. }
  41854. /**
  41855. * Returns the pixel ratio.
  41856. *
  41857. * @return {number} The pixel ratio.
  41858. */
  41859. getPixelRatio() {
  41860. return this._canvasTarget.getPixelRatio();
  41861. }
  41862. /**
  41863. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  41864. *
  41865. * @param {Vector2} target - The method writes the result in this target object.
  41866. * @return {Vector2} The drawing buffer size.
  41867. */
  41868. getDrawingBufferSize( target ) {
  41869. return this._canvasTarget.getDrawingBufferSize( target );
  41870. }
  41871. /**
  41872. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  41873. *
  41874. * @param {Vector2} target - The method writes the result in this target object.
  41875. * @return {Vector2} The renderer's size in logical pixels.
  41876. */
  41877. getSize( target ) {
  41878. return this._canvasTarget.getSize( target );
  41879. }
  41880. /**
  41881. * Sets the given pixel ratio and resizes the canvas if necessary.
  41882. *
  41883. * @param {number} [value=1] - The pixel ratio.
  41884. */
  41885. setPixelRatio( value = 1 ) {
  41886. this._canvasTarget.setPixelRatio( value );
  41887. }
  41888. /**
  41889. * This method allows to define the drawing buffer size by specifying
  41890. * width, height and pixel ratio all at once. The size of the drawing
  41891. * buffer is computed with this formula:
  41892. * ```js
  41893. * size.x = width * pixelRatio;
  41894. * size.y = height * pixelRatio;
  41895. * ```
  41896. *
  41897. * @param {number} width - The width in logical pixels.
  41898. * @param {number} height - The height in logical pixels.
  41899. * @param {number} pixelRatio - The pixel ratio.
  41900. */
  41901. setDrawingBufferSize( width, height, pixelRatio ) {
  41902. // Renderer can't be resized while presenting in XR.
  41903. if ( this.xr && this.xr.isPresenting ) return;
  41904. this._canvasTarget.setDrawingBufferSize( width, height, pixelRatio );
  41905. }
  41906. /**
  41907. * Sets the size of the renderer.
  41908. *
  41909. * @param {number} width - The width in logical pixels.
  41910. * @param {number} height - The height in logical pixels.
  41911. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  41912. */
  41913. setSize( width, height, updateStyle = true ) {
  41914. // Renderer can't be resized while presenting in XR.
  41915. if ( this.xr && this.xr.isPresenting ) return;
  41916. this._canvasTarget.setSize( width, height, updateStyle );
  41917. }
  41918. /**
  41919. * Defines a manual sort function for the opaque render list.
  41920. * Pass `null` to use the default sort.
  41921. *
  41922. * @param {Function} method - The sort function.
  41923. */
  41924. setOpaqueSort( method ) {
  41925. this._opaqueSort = method;
  41926. }
  41927. /**
  41928. * Defines a manual sort function for the transparent render list.
  41929. * Pass `null` to use the default sort.
  41930. *
  41931. * @param {Function} method - The sort function.
  41932. */
  41933. setTransparentSort( method ) {
  41934. this._transparentSort = method;
  41935. }
  41936. /**
  41937. * Returns the scissor rectangle.
  41938. *
  41939. * @param {Vector4} target - The method writes the result in this target object.
  41940. * @return {Vector4} The scissor rectangle.
  41941. */
  41942. getScissor( target ) {
  41943. return this._canvasTarget.getScissor( target );
  41944. }
  41945. /**
  41946. * Defines the scissor rectangle.
  41947. *
  41948. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  41949. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  41950. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  41951. * @param {number} width - The width of the scissor box in logical pixel unit.
  41952. * @param {number} height - The height of the scissor box in logical pixel unit.
  41953. */
  41954. setScissor( x, y, width, height ) {
  41955. this._canvasTarget.setScissor( x, y, width, height );
  41956. }
  41957. /**
  41958. * Returns the scissor test value.
  41959. *
  41960. * @return {boolean} Whether the scissor test should be enabled or not.
  41961. */
  41962. getScissorTest() {
  41963. return this._canvasTarget.getScissorTest();
  41964. }
  41965. /**
  41966. * Defines the scissor test.
  41967. *
  41968. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  41969. */
  41970. setScissorTest( boolean ) {
  41971. this._canvasTarget.setScissorTest( boolean );
  41972. // TODO: Move it to CanvasTarget event listener.
  41973. this.backend.setScissorTest( boolean );
  41974. }
  41975. /**
  41976. * Returns the viewport definition.
  41977. *
  41978. * @param {Vector4} target - The method writes the result in this target object.
  41979. * @return {Vector4} The viewport definition.
  41980. */
  41981. getViewport( target ) {
  41982. return this._canvasTarget.getViewport( target );
  41983. }
  41984. /**
  41985. * Defines the viewport.
  41986. *
  41987. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  41988. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  41989. * @param {number} width - The width of the viewport in logical pixel unit.
  41990. * @param {number} height - The height of the viewport in logical pixel unit.
  41991. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  41992. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  41993. */
  41994. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  41995. this._canvasTarget.setViewport( x, y, width, height, minDepth, maxDepth );
  41996. }
  41997. /**
  41998. * Returns the clear color.
  41999. *
  42000. * @param {Color} target - The method writes the result in this target object.
  42001. * @return {Color} The clear color.
  42002. */
  42003. getClearColor( target ) {
  42004. return target.copy( this._clearColor );
  42005. }
  42006. /**
  42007. * Defines the clear color and optionally the clear alpha.
  42008. *
  42009. * @param {Color} color - The clear color.
  42010. * @param {number} [alpha=1] - The clear alpha.
  42011. */
  42012. setClearColor( color, alpha = 1 ) {
  42013. this._clearColor.set( color );
  42014. this._clearColor.a = alpha;
  42015. }
  42016. /**
  42017. * Returns the clear alpha.
  42018. *
  42019. * @return {number} The clear alpha.
  42020. */
  42021. getClearAlpha() {
  42022. return this._clearColor.a;
  42023. }
  42024. /**
  42025. * Defines the clear alpha.
  42026. *
  42027. * @param {number} alpha - The clear alpha.
  42028. */
  42029. setClearAlpha( alpha ) {
  42030. this._clearColor.a = alpha;
  42031. }
  42032. /**
  42033. * Returns the clear depth.
  42034. *
  42035. * @return {number} The clear depth.
  42036. */
  42037. getClearDepth() {
  42038. return this._clearDepth;
  42039. }
  42040. /**
  42041. * Defines the clear depth.
  42042. *
  42043. * @param {number} depth - The clear depth.
  42044. */
  42045. setClearDepth( depth ) {
  42046. this._clearDepth = depth;
  42047. }
  42048. /**
  42049. * Returns the clear stencil.
  42050. *
  42051. * @return {number} The clear stencil.
  42052. */
  42053. getClearStencil() {
  42054. return this._clearStencil;
  42055. }
  42056. /**
  42057. * Defines the clear stencil.
  42058. *
  42059. * @param {number} stencil - The clear stencil.
  42060. */
  42061. setClearStencil( stencil ) {
  42062. this._clearStencil = stencil;
  42063. }
  42064. /**
  42065. * This method performs an occlusion query for the given 3D object.
  42066. * It returns `true` if the given 3D object is fully occluded by other
  42067. * 3D objects in the scene.
  42068. *
  42069. * @param {Object3D} object - The 3D object to test.
  42070. * @return {boolean} Whether the 3D object is fully occluded or not.
  42071. */
  42072. isOccluded( object ) {
  42073. const renderContext = this._currentRenderContext;
  42074. return renderContext && this.backend.isOccluded( renderContext, object );
  42075. }
  42076. /**
  42077. * Performs a manual clear operation. This method ignores `autoClear` properties.
  42078. *
  42079. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  42080. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  42081. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  42082. */
  42083. clear( color = true, depth = true, stencil = true ) {
  42084. if ( this._initialized === false ) {
  42085. throw new Error( 'Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42086. }
  42087. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  42088. let renderContext = null;
  42089. if ( renderTarget !== null ) {
  42090. this._textures.updateRenderTarget( renderTarget );
  42091. const renderTargetData = this._textures.get( renderTarget );
  42092. renderContext = this._renderContexts.getForClear( renderTarget );
  42093. renderContext.textures = renderTargetData.textures;
  42094. renderContext.depthTexture = renderTargetData.depthTexture;
  42095. renderContext.width = renderTargetData.width;
  42096. renderContext.height = renderTargetData.height;
  42097. renderContext.renderTarget = renderTarget;
  42098. renderContext.depth = renderTarget.depthBuffer;
  42099. renderContext.stencil = renderTarget.stencilBuffer;
  42100. // #30329
  42101. renderContext.clearColorValue = this.backend.getClearColor();
  42102. renderContext.activeCubeFace = this.getActiveCubeFace();
  42103. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  42104. }
  42105. this.backend.clear( color, depth, stencil, renderContext );
  42106. if ( renderTarget !== null && this._renderTarget === null ) {
  42107. this._renderOutput( renderTarget );
  42108. }
  42109. }
  42110. /**
  42111. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  42112. */
  42113. clearColor() {
  42114. this.clear( true, false, false );
  42115. }
  42116. /**
  42117. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  42118. */
  42119. clearDepth() {
  42120. this.clear( false, true, false );
  42121. }
  42122. /**
  42123. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  42124. */
  42125. clearStencil() {
  42126. this.clear( false, false, true );
  42127. }
  42128. /**
  42129. * Async version of {@link Renderer#clear}.
  42130. *
  42131. * @async
  42132. * @deprecated
  42133. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  42134. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  42135. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  42136. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42137. */
  42138. async clearAsync( color = true, depth = true, stencil = true ) {
  42139. warnOnce( 'Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42140. await this.init();
  42141. this.clear( color, depth, stencil );
  42142. }
  42143. /**
  42144. * Async version of {@link Renderer#clearColor}.
  42145. *
  42146. * @async
  42147. * @deprecated
  42148. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42149. */
  42150. async clearColorAsync() {
  42151. warnOnce( 'Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42152. this.clear( true, false, false );
  42153. }
  42154. /**
  42155. * Async version of {@link Renderer#clearDepth}.
  42156. *
  42157. * @async
  42158. * @deprecated
  42159. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42160. */
  42161. async clearDepthAsync() {
  42162. warnOnce( 'Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42163. this.clear( false, true, false );
  42164. }
  42165. /**
  42166. * Async version of {@link Renderer#clearStencil}.
  42167. *
  42168. * @async
  42169. * @deprecated
  42170. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42171. */
  42172. async clearStencilAsync() {
  42173. warnOnce( 'Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42174. this.clear( false, false, true );
  42175. }
  42176. /**
  42177. * Returns `true` if a framebuffer target is needed to perform tone mapping or color space conversion.
  42178. * If this is the case, the renderer allocates an internal render target for that purpose.
  42179. *
  42180. */
  42181. get needsFrameBufferTarget() {
  42182. const useToneMapping = this.currentToneMapping !== NoToneMapping;
  42183. const useColorSpace = this.currentColorSpace !== ColorManagement.workingColorSpace;
  42184. return useToneMapping || useColorSpace;
  42185. }
  42186. /**
  42187. * The number of samples used for multi-sample anti-aliasing (MSAA).
  42188. *
  42189. * @type {number}
  42190. * @default 0
  42191. */
  42192. get samples() {
  42193. return this._samples;
  42194. }
  42195. /**
  42196. * The current number of samples used for multi-sample anti-aliasing (MSAA).
  42197. *
  42198. * When rendering to a custom render target, the number of samples of that render target is used.
  42199. * If the renderer needs an internal framebuffer target for tone mapping or color space conversion,
  42200. * the number of samples is set to 0.
  42201. *
  42202. * @type {number}
  42203. */
  42204. get currentSamples() {
  42205. let samples = this._samples;
  42206. if ( this._renderTarget !== null ) {
  42207. samples = this._renderTarget.samples;
  42208. } else if ( this.needsFrameBufferTarget ) {
  42209. samples = 0;
  42210. }
  42211. return samples;
  42212. }
  42213. /**
  42214. * The current tone mapping of the renderer. When not producing screen output,
  42215. * the tone mapping is always `NoToneMapping`.
  42216. *
  42217. * @type {number}
  42218. */
  42219. get currentToneMapping() {
  42220. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  42221. }
  42222. /**
  42223. * The current color space of the renderer. When not producing screen output,
  42224. * the color space is always the working color space.
  42225. *
  42226. * @type {string}
  42227. */
  42228. get currentColorSpace() {
  42229. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  42230. }
  42231. /**
  42232. * Returns `true` if the rendering settings are set to screen output.
  42233. *
  42234. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  42235. */
  42236. get isOutputTarget() {
  42237. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  42238. }
  42239. /**
  42240. * Frees all internal resources of the renderer. Call this method if the renderer
  42241. * is no longer in use by your app.
  42242. */
  42243. dispose() {
  42244. if ( this._initialized === true ) {
  42245. this.info.dispose();
  42246. this.backend.dispose();
  42247. this._animation.dispose();
  42248. this._objects.dispose();
  42249. this._geometries.dispose();
  42250. this._pipelines.dispose();
  42251. this._nodes.dispose();
  42252. this._bindings.dispose();
  42253. this._renderLists.dispose();
  42254. this._renderContexts.dispose();
  42255. this._textures.dispose();
  42256. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  42257. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  42258. if ( queryPool !== null ) queryPool.dispose();
  42259. } );
  42260. }
  42261. this.setRenderTarget( null );
  42262. this.setAnimationLoop( null );
  42263. }
  42264. /**
  42265. * Sets the given render target. Calling this method means the renderer does not
  42266. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  42267. * Use `null` as the first argument to reset the state.
  42268. *
  42269. * @param {?RenderTarget} renderTarget - The render target to set.
  42270. * @param {number} [activeCubeFace=0] - The active cube face.
  42271. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  42272. */
  42273. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  42274. this._renderTarget = renderTarget;
  42275. this._activeCubeFace = activeCubeFace;
  42276. this._activeMipmapLevel = activeMipmapLevel;
  42277. }
  42278. /**
  42279. * Returns the current render target.
  42280. *
  42281. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  42282. */
  42283. getRenderTarget() {
  42284. return this._renderTarget;
  42285. }
  42286. /**
  42287. * Sets the output render target for the renderer.
  42288. *
  42289. * @param {Object} renderTarget - The render target to set as the output target.
  42290. */
  42291. setOutputRenderTarget( renderTarget ) {
  42292. this._outputRenderTarget = renderTarget;
  42293. }
  42294. /**
  42295. * Returns the current output target.
  42296. *
  42297. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  42298. */
  42299. getOutputRenderTarget() {
  42300. return this._outputRenderTarget;
  42301. }
  42302. /**
  42303. * Sets the canvas target. The canvas target manages the HTML canvas
  42304. * or the offscreen canvas the renderer draws into.
  42305. *
  42306. * @param {CanvasTarget} canvasTarget - The canvas target.
  42307. */
  42308. setCanvasTarget( canvasTarget ) {
  42309. this._canvasTarget.removeEventListener( 'resize', this._onCanvasTargetResize );
  42310. this._canvasTarget = canvasTarget;
  42311. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  42312. }
  42313. /**
  42314. * Returns the current canvas target.
  42315. *
  42316. * @return {CanvasTarget} The current canvas target.
  42317. */
  42318. getCanvasTarget() {
  42319. return this._canvasTarget;
  42320. }
  42321. /**
  42322. * Resets the renderer to the initial state before WebXR started.
  42323. *
  42324. * @private
  42325. */
  42326. _resetXRState() {
  42327. this.backend.setXRTarget( null );
  42328. this.setOutputRenderTarget( null );
  42329. this.setRenderTarget( null );
  42330. this._frameBufferTarget.dispose();
  42331. this._frameBufferTarget = null;
  42332. }
  42333. /**
  42334. * Callback for {@link Renderer#setRenderObjectFunction}.
  42335. *
  42336. * @callback renderObjectFunction
  42337. * @param {Object3D} object - The 3D object.
  42338. * @param {Scene} scene - The scene the 3D object belongs to.
  42339. * @param {Camera} camera - The camera the object should be rendered with.
  42340. * @param {BufferGeometry} geometry - The object's geometry.
  42341. * @param {Material} material - The object's material.
  42342. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  42343. * @param {LightsNode} lightsNode - The current lights node.
  42344. * @param {ClippingContext} clippingContext - The clipping context.
  42345. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  42346. */
  42347. /**
  42348. * Sets the given render object function. Calling this method overwrites the default implementation
  42349. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  42350. * if you want to modify the way objects are rendered. For example you can define things like "every
  42351. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  42352. * The custom function must always call `renderObject()` in its implementation.
  42353. *
  42354. * Use `null` as the first argument to reset the state.
  42355. *
  42356. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  42357. */
  42358. setRenderObjectFunction( renderObjectFunction ) {
  42359. this._renderObjectFunction = renderObjectFunction;
  42360. }
  42361. /**
  42362. * Returns the current render object function.
  42363. *
  42364. * @return {?Function} The current render object function. Returns `null` if no function is set.
  42365. */
  42366. getRenderObjectFunction() {
  42367. return this._renderObjectFunction;
  42368. }
  42369. /**
  42370. * Execute a single or an array of compute nodes. This method can only be called
  42371. * if the renderer has been initialized.
  42372. *
  42373. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  42374. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  42375. * - A single number representing count, or
  42376. * - An array [x, y, z] representing dispatch size, or
  42377. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  42378. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  42379. */
  42380. compute( computeNodes, dispatchSize = null ) {
  42381. if ( this._isDeviceLost === true ) return;
  42382. if ( this._initialized === false ) {
  42383. warn( 'Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  42384. return this.computeAsync( computeNodes, dispatchSize );
  42385. }
  42386. //
  42387. const nodeFrame = this._nodes.nodeFrame;
  42388. const previousRenderId = nodeFrame.renderId;
  42389. //
  42390. this.info.calls ++;
  42391. this.info.compute.calls ++;
  42392. this.info.compute.frameCalls ++;
  42393. nodeFrame.renderId = this.info.calls;
  42394. //
  42395. this.backend.updateTimeStampUID( computeNodes );
  42396. this.inspector.beginCompute( this.backend.getTimestampUID( computeNodes ), computeNodes );
  42397. //
  42398. const backend = this.backend;
  42399. const pipelines = this._pipelines;
  42400. const bindings = this._bindings;
  42401. const nodes = this._nodes;
  42402. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  42403. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  42404. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  42405. }
  42406. backend.beginCompute( computeNodes );
  42407. for ( const computeNode of computeList ) {
  42408. // onInit
  42409. if ( pipelines.has( computeNode ) === false ) {
  42410. const dispose = () => {
  42411. computeNode.removeEventListener( 'dispose', dispose );
  42412. pipelines.delete( computeNode );
  42413. bindings.deleteForCompute( computeNode );
  42414. nodes.delete( computeNode );
  42415. };
  42416. computeNode.addEventListener( 'dispose', dispose );
  42417. //
  42418. const onInitFn = computeNode.onInitFunction;
  42419. if ( onInitFn !== null ) {
  42420. onInitFn.call( computeNode, { renderer: this } );
  42421. }
  42422. }
  42423. nodes.updateForCompute( computeNode );
  42424. bindings.updateForCompute( computeNode );
  42425. const computeBindings = bindings.getForCompute( computeNode );
  42426. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  42427. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSize );
  42428. }
  42429. backend.finishCompute( computeNodes );
  42430. //
  42431. nodeFrame.renderId = previousRenderId;
  42432. //
  42433. this.inspector.finishCompute( this.backend.getTimestampUID( computeNodes ) );
  42434. }
  42435. /**
  42436. * Execute a single or an array of compute nodes.
  42437. *
  42438. * @async
  42439. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  42440. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  42441. * - A single number representing count, or
  42442. * - An array [x, y, z] representing dispatch size, or
  42443. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  42444. * @return {Promise} A Promise that resolve when the compute has finished.
  42445. */
  42446. async computeAsync( computeNodes, dispatchSize = null ) {
  42447. if ( this._initialized === false ) await this.init();
  42448. this.compute( computeNodes, dispatchSize );
  42449. }
  42450. /**
  42451. * Checks if the given feature is supported by the selected backend.
  42452. *
  42453. * @async
  42454. * @deprecated
  42455. * @param {string} name - The feature's name.
  42456. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  42457. */
  42458. async hasFeatureAsync( name ) {
  42459. warnOnce( 'Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42460. await this.init();
  42461. return this.hasFeature( name );
  42462. }
  42463. async resolveTimestampsAsync( type = 'render' ) {
  42464. if ( this._initialized === false ) await this.init();
  42465. return this.backend.resolveTimestampsAsync( type );
  42466. }
  42467. /**
  42468. * Checks if the given feature is supported by the selected backend. If the
  42469. * renderer has not been initialized, this method always returns `false`.
  42470. *
  42471. * @param {string} name - The feature's name.
  42472. * @return {boolean} Whether the feature is supported or not.
  42473. */
  42474. hasFeature( name ) {
  42475. if ( this._initialized === false ) {
  42476. throw new Error( 'Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42477. }
  42478. return this.backend.hasFeature( name );
  42479. }
  42480. /**
  42481. * Returns `true` when the renderer has been initialized.
  42482. *
  42483. * @return {boolean} Whether the renderer has been initialized or not.
  42484. */
  42485. hasInitialized() {
  42486. return this._initialized;
  42487. }
  42488. /**
  42489. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  42490. * (which can cause noticeable lags due to decode and GPU upload overhead).
  42491. *
  42492. * @async
  42493. * @deprecated
  42494. * @param {Texture} texture - The texture.
  42495. * @return {Promise} A Promise that resolves when the texture has been initialized.
  42496. */
  42497. async initTextureAsync( texture ) {
  42498. warnOnce( 'Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42499. await this.init();
  42500. this.initTexture( texture );
  42501. }
  42502. /**
  42503. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  42504. * (which can cause noticeable lags due to decode and GPU upload overhead).
  42505. *
  42506. * This method can only be used if the renderer has been initialized.
  42507. *
  42508. * @param {Texture} texture - The texture.
  42509. */
  42510. initTexture( texture ) {
  42511. if ( this._initialized === false ) {
  42512. throw new Error( 'Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42513. }
  42514. this._textures.updateTexture( texture );
  42515. }
  42516. /**
  42517. * Copies the current bound framebuffer into the given texture.
  42518. *
  42519. * @param {FramebufferTexture} framebufferTexture - The texture.
  42520. * @param {?(Vector2|Vector4)} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  42521. */
  42522. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  42523. if ( rectangle !== null ) {
  42524. if ( rectangle.isVector2 ) {
  42525. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  42526. } else if ( rectangle.isVector4 ) {
  42527. rectangle = _vector4.copy( rectangle ).floor();
  42528. } else {
  42529. error( 'Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  42530. return;
  42531. }
  42532. } else {
  42533. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  42534. }
  42535. //
  42536. let renderContext = this._currentRenderContext;
  42537. let renderTarget;
  42538. if ( renderContext !== null ) {
  42539. renderTarget = renderContext.renderTarget;
  42540. } else {
  42541. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  42542. if ( renderTarget !== null ) {
  42543. this._textures.updateRenderTarget( renderTarget );
  42544. renderContext = this._textures.get( renderTarget );
  42545. }
  42546. }
  42547. //
  42548. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  42549. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  42550. this._inspector.copyFramebufferToTexture( framebufferTexture );
  42551. }
  42552. /**
  42553. * Copies data of the given source texture into a destination texture.
  42554. *
  42555. * @param {Texture} srcTexture - The source texture.
  42556. * @param {Texture} dstTexture - The destination texture.
  42557. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  42558. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  42559. * @param {number} [srcLevel=0] - The source mip level to copy from.
  42560. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  42561. */
  42562. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  42563. this._textures.updateTexture( srcTexture );
  42564. this._textures.updateTexture( dstTexture );
  42565. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  42566. this._inspector.copyTextureToTexture( srcTexture, dstTexture );
  42567. }
  42568. /**
  42569. * Reads pixel data from the given render target.
  42570. *
  42571. * @async
  42572. * @param {RenderTarget} renderTarget - The render target to read from.
  42573. * @param {number} x - The `x` coordinate of the copy region's origin.
  42574. * @param {number} y - The `y` coordinate of the copy region's origin.
  42575. * @param {number} width - The width of the copy region.
  42576. * @param {number} height - The height of the copy region.
  42577. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  42578. * @param {number} [faceIndex=0] - The active cube face index.
  42579. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  42580. */
  42581. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  42582. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  42583. }
  42584. /**
  42585. * Analyzes the given 3D object's hierarchy and builds render lists from the
  42586. * processed hierarchy.
  42587. *
  42588. * @private
  42589. * @param {Object3D} object - The 3D object to process (usually a scene).
  42590. * @param {Camera} camera - The camera the object is rendered with.
  42591. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  42592. * @param {RenderList} renderList - The current render list.
  42593. * @param {ClippingContext} clippingContext - The current clipping context.
  42594. */
  42595. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  42596. if ( object.visible === false ) return;
  42597. const visible = object.layers.test( camera.layers );
  42598. if ( visible ) {
  42599. if ( object.isGroup ) {
  42600. groupOrder = object.renderOrder;
  42601. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  42602. } else if ( object.isLOD ) {
  42603. if ( object.autoUpdate === true ) object.update( camera );
  42604. } else if ( object.isLight ) {
  42605. renderList.pushLight( object );
  42606. } else if ( object.isSprite ) {
  42607. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  42608. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  42609. if ( this.sortObjects === true ) {
  42610. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  42611. }
  42612. const { geometry, material } = object;
  42613. if ( material.visible ) {
  42614. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  42615. }
  42616. }
  42617. } else if ( object.isLineLoop ) {
  42618. error( 'Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  42619. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  42620. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  42621. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  42622. const { geometry, material } = object;
  42623. if ( this.sortObjects === true ) {
  42624. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  42625. _vector4
  42626. .copy( geometry.boundingSphere.center )
  42627. .applyMatrix4( object.matrixWorld )
  42628. .applyMatrix4( _projScreenMatrix );
  42629. }
  42630. if ( Array.isArray( material ) ) {
  42631. const groups = geometry.groups;
  42632. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  42633. const group = groups[ i ];
  42634. const groupMaterial = material[ group.materialIndex ];
  42635. if ( groupMaterial && groupMaterial.visible ) {
  42636. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  42637. }
  42638. }
  42639. } else if ( material.visible ) {
  42640. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  42641. }
  42642. }
  42643. }
  42644. }
  42645. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  42646. const baseRenderList = renderList;
  42647. // replace render list
  42648. renderList = this._renderLists.get( object, camera );
  42649. renderList.begin();
  42650. baseRenderList.pushBundle( {
  42651. bundleGroup: object,
  42652. camera,
  42653. renderList,
  42654. } );
  42655. renderList.finish();
  42656. }
  42657. const children = object.children;
  42658. for ( let i = 0, l = children.length; i < l; i ++ ) {
  42659. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  42660. }
  42661. }
  42662. /**
  42663. * Renders the given render bundles.
  42664. *
  42665. * @private
  42666. * @param {Array<Object>} bundles - Array with render bundle data.
  42667. * @param {Scene} sceneRef - The scene the render bundles belong to.
  42668. * @param {LightsNode} lightsNode - The current lights node.
  42669. */
  42670. _renderBundles( bundles, sceneRef, lightsNode ) {
  42671. for ( const bundle of bundles ) {
  42672. this._renderBundle( bundle, sceneRef, lightsNode );
  42673. }
  42674. }
  42675. /**
  42676. * Renders the transparent objects from the given render lists.
  42677. *
  42678. * @private
  42679. * @param {Array<Object>} renderList - The transparent render list.
  42680. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  42681. * @param {Camera} camera - The camera the render list should be rendered with.
  42682. * @param {Scene} scene - The scene the render list belongs to.
  42683. * @param {LightsNode} lightsNode - The current lights node.
  42684. */
  42685. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  42686. if ( doublePassList.length > 0 ) {
  42687. // render back side
  42688. for ( const { material } of doublePassList ) {
  42689. material.side = BackSide;
  42690. }
  42691. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  42692. // render front side
  42693. for ( const { material } of doublePassList ) {
  42694. material.side = FrontSide;
  42695. }
  42696. this._renderObjects( renderList, camera, scene, lightsNode );
  42697. // restore
  42698. for ( const { material } of doublePassList ) {
  42699. material.side = DoubleSide;
  42700. }
  42701. } else {
  42702. this._renderObjects( renderList, camera, scene, lightsNode );
  42703. }
  42704. }
  42705. /**
  42706. * Renders the objects from the given render list.
  42707. *
  42708. * @private
  42709. * @param {Array<Object>} renderList - The render list.
  42710. * @param {Camera} camera - The camera the render list should be rendered with.
  42711. * @param {Scene} scene - The scene the render list belongs to.
  42712. * @param {LightsNode} lightsNode - The current lights node.
  42713. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  42714. */
  42715. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  42716. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  42717. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  42718. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  42719. }
  42720. }
  42721. /**
  42722. * Retrieves shadow nodes for the given material. This is used to setup shadow passes.
  42723. * The result is cached per material and updated when the material's version changes.
  42724. *
  42725. * @private
  42726. * @param {Material} material
  42727. * @returns {Object} - The shadow nodes for the material.
  42728. */
  42729. _getShadowNodes( material ) {
  42730. const version = material.version;
  42731. let cache = this._cacheShadowNodes.get( material );
  42732. if ( cache === undefined || cache.version !== version ) {
  42733. const hasMap = material.map !== null;
  42734. const hasColorNode = material.colorNode && material.colorNode.isNode;
  42735. const hasCastShadowNode = material.castShadowNode && material.castShadowNode.isNode;
  42736. let positionNode = null;
  42737. let colorNode = null;
  42738. let depthNode = null;
  42739. if ( hasMap || hasColorNode || hasCastShadowNode ) {
  42740. let shadowRGB;
  42741. let shadowAlpha;
  42742. if ( hasCastShadowNode ) {
  42743. shadowRGB = material.castShadowNode.rgb;
  42744. shadowAlpha = material.castShadowNode.a;
  42745. } else {
  42746. shadowRGB = vec3( 0 );
  42747. shadowAlpha = float( 1 );
  42748. }
  42749. if ( hasMap ) {
  42750. shadowAlpha = shadowAlpha.mul( reference( 'map', 'texture', material ).a );
  42751. }
  42752. if ( hasColorNode ) {
  42753. shadowAlpha = shadowAlpha.mul( material.colorNode.a );
  42754. }
  42755. colorNode = vec4( shadowRGB, shadowAlpha );
  42756. }
  42757. if ( material.depthNode && material.depthNode.isNode ) {
  42758. depthNode = material.depthNode;
  42759. }
  42760. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  42761. positionNode = material.castShadowPositionNode;
  42762. } else if ( material.positionNode && material.positionNode.isNode ) {
  42763. positionNode = material.positionNode;
  42764. }
  42765. cache = {
  42766. version,
  42767. colorNode,
  42768. depthNode,
  42769. positionNode
  42770. };
  42771. this._cacheShadowNodes.set( material, cache );
  42772. }
  42773. return cache;
  42774. }
  42775. /**
  42776. * This method represents the default render object function that manages the render lifecycle
  42777. * of the object.
  42778. *
  42779. * @param {Object3D} object - The 3D object.
  42780. * @param {Scene} scene - The scene the 3D object belongs to.
  42781. * @param {Camera} camera - The camera the object should be rendered with.
  42782. * @param {BufferGeometry} geometry - The object's geometry.
  42783. * @param {Material} material - The object's material.
  42784. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  42785. * @param {LightsNode} lightsNode - The current lights node.
  42786. * @param {?ClippingContext} clippingContext - The clipping context.
  42787. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  42788. */
  42789. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  42790. let materialOverride = false;
  42791. let materialColorNode;
  42792. let materialDepthNode;
  42793. let materialPositionNode;
  42794. let materialSide;
  42795. //
  42796. object.onBeforeRender( this, scene, camera, geometry, material, group );
  42797. //
  42798. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  42799. const overrideMaterial = scene.overrideMaterial;
  42800. materialOverride = true;
  42801. // store original nodes
  42802. materialColorNode = scene.overrideMaterial.colorNode;
  42803. materialDepthNode = scene.overrideMaterial.depthNode;
  42804. materialPositionNode = scene.overrideMaterial.positionNode;
  42805. materialSide = scene.overrideMaterial.side;
  42806. if ( material.positionNode && material.positionNode.isNode ) {
  42807. overrideMaterial.positionNode = material.positionNode;
  42808. }
  42809. overrideMaterial.alphaTest = material.alphaTest;
  42810. overrideMaterial.alphaMap = material.alphaMap;
  42811. overrideMaterial.transparent = material.transparent || material.transmission > 0 ||
  42812. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  42813. ( material.backdropNode && material.backdropNode.isNode );
  42814. if ( overrideMaterial.isShadowPassMaterial ) {
  42815. const { colorNode, depthNode, positionNode } = this._getShadowNodes( material );
  42816. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  42817. if ( colorNode !== null ) overrideMaterial.colorNode = colorNode;
  42818. if ( depthNode !== null ) overrideMaterial.depthNode = depthNode;
  42819. if ( positionNode !== null ) overrideMaterial.positionNode = positionNode;
  42820. }
  42821. material = overrideMaterial;
  42822. }
  42823. //
  42824. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  42825. material.side = BackSide;
  42826. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  42827. material.side = FrontSide;
  42828. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  42829. material.side = DoubleSide;
  42830. } else {
  42831. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  42832. }
  42833. //
  42834. if ( materialOverride ) {
  42835. scene.overrideMaterial.colorNode = materialColorNode;
  42836. scene.overrideMaterial.depthNode = materialDepthNode;
  42837. scene.overrideMaterial.positionNode = materialPositionNode;
  42838. scene.overrideMaterial.side = materialSide;
  42839. }
  42840. //
  42841. object.onAfterRender( this, scene, camera, geometry, material, group );
  42842. }
  42843. /**
  42844. * This method represents the default `_handleObjectFunction` implementation which creates
  42845. * a render object from the given data and performs the draw command with the selected backend.
  42846. *
  42847. * @private
  42848. * @param {Object3D} object - The 3D object.
  42849. * @param {Material} material - The object's material.
  42850. * @param {Scene} scene - The scene the 3D object belongs to.
  42851. * @param {Camera} camera - The camera the object should be rendered with.
  42852. * @param {LightsNode} lightsNode - The current lights node.
  42853. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  42854. * @param {ClippingContext} clippingContext - The clipping context.
  42855. * @param {string} [passId] - An optional ID for identifying the pass.
  42856. */
  42857. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  42858. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  42859. renderObject.drawRange = object.geometry.drawRange;
  42860. renderObject.group = group;
  42861. //
  42862. const needsRefresh = this._nodes.needsRefresh( renderObject );
  42863. if ( needsRefresh ) {
  42864. this._nodes.updateBefore( renderObject );
  42865. this._geometries.updateForRender( renderObject );
  42866. this._nodes.updateForRender( renderObject );
  42867. this._bindings.updateForRender( renderObject );
  42868. }
  42869. this._pipelines.updateForRender( renderObject );
  42870. //
  42871. if ( this._currentRenderBundle !== null ) {
  42872. const renderBundleData = this.backend.get( this._currentRenderBundle );
  42873. renderBundleData.renderObjects.push( renderObject );
  42874. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  42875. }
  42876. this.backend.draw( renderObject, this.info );
  42877. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  42878. }
  42879. /**
  42880. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  42881. * Used in `compileAsync()`.
  42882. *
  42883. * @private
  42884. * @param {Object3D} object - The 3D object.
  42885. * @param {Material} material - The object's material.
  42886. * @param {Scene} scene - The scene the 3D object belongs to.
  42887. * @param {Camera} camera - The camera the object should be rendered with.
  42888. * @param {LightsNode} lightsNode - The current lights node.
  42889. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  42890. * @param {ClippingContext} clippingContext - The clipping context.
  42891. * @param {string} [passId] - An optional ID for identifying the pass.
  42892. */
  42893. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  42894. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  42895. renderObject.drawRange = object.geometry.drawRange;
  42896. renderObject.group = group;
  42897. //
  42898. this._nodes.updateBefore( renderObject );
  42899. this._geometries.updateForRender( renderObject );
  42900. this._nodes.updateForRender( renderObject );
  42901. this._bindings.updateForRender( renderObject );
  42902. this._pipelines.getForRender( renderObject, this._compilationPromises );
  42903. this._nodes.updateAfter( renderObject );
  42904. }
  42905. /**
  42906. * Callback when the canvas has been resized.
  42907. *
  42908. * @private
  42909. */
  42910. _onCanvasTargetResize() {
  42911. if ( this._initialized ) this.backend.updateSize();
  42912. }
  42913. /**
  42914. * Alias for `compileAsync()`.
  42915. *
  42916. * @method
  42917. * @param {Object3D} scene - The scene or 3D object to precompile.
  42918. * @param {Camera} camera - The camera that is used to render the scene.
  42919. * @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.
  42920. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  42921. */
  42922. get compile() {
  42923. return this.compileAsync;
  42924. }
  42925. }
  42926. /**
  42927. * A binding represents the connection between a resource (like a texture, sampler
  42928. * or uniform buffer) and the resource definition in a shader stage.
  42929. *
  42930. * This module is an abstract base class for all concrete bindings types.
  42931. *
  42932. * @abstract
  42933. * @private
  42934. */
  42935. class Binding {
  42936. /**
  42937. * Constructs a new binding.
  42938. *
  42939. * @param {string} [name=''] - The binding's name.
  42940. */
  42941. constructor( name = '' ) {
  42942. /**
  42943. * The binding's name.
  42944. *
  42945. * @type {string}
  42946. */
  42947. this.name = name;
  42948. /**
  42949. * A bitmask that defines in what shader stages the
  42950. * binding's resource is accessible.
  42951. *
  42952. * @type {number}
  42953. */
  42954. this.visibility = 0;
  42955. }
  42956. /**
  42957. * Makes sure binding's resource is visible for the given shader stage.
  42958. *
  42959. * @param {number} visibility - The shader stage.
  42960. */
  42961. setVisibility( visibility ) {
  42962. this.visibility |= visibility;
  42963. }
  42964. /**
  42965. * The shader stages in which the binding's resource is visible.
  42966. *
  42967. * @return {number} The visibility bitmask.
  42968. */
  42969. getVisibility() {
  42970. return this.visibility;
  42971. }
  42972. /**
  42973. * Clones the binding.
  42974. *
  42975. * @return {Binding} The cloned binding.
  42976. */
  42977. clone() {
  42978. return Object.assign( new this.constructor(), this );
  42979. }
  42980. }
  42981. /**
  42982. * This function is usually called with the length in bytes of an array buffer.
  42983. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  42984. *
  42985. * @function
  42986. * @param {number} floatLength - The buffer length.
  42987. * @return {number} The padded length.
  42988. */
  42989. function getFloatLength( floatLength ) {
  42990. // ensure chunk size alignment (STD140 layout)
  42991. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  42992. }
  42993. /**
  42994. * Represents a buffer binding type.
  42995. *
  42996. * @private
  42997. * @abstract
  42998. * @augments Binding
  42999. */
  43000. class Buffer extends Binding {
  43001. /**
  43002. * Constructs a new buffer.
  43003. *
  43004. * @param {string} name - The buffer's name.
  43005. * @param {TypedArray} [buffer=null] - The buffer.
  43006. */
  43007. constructor( name, buffer = null ) {
  43008. super( name );
  43009. /**
  43010. * This flag can be used for type testing.
  43011. *
  43012. * @type {boolean}
  43013. * @readonly
  43014. * @default true
  43015. */
  43016. this.isBuffer = true;
  43017. /**
  43018. * The bytes per element.
  43019. *
  43020. * @type {number}
  43021. */
  43022. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  43023. /**
  43024. * A reference to the internal buffer.
  43025. *
  43026. * @private
  43027. * @type {TypedArray}
  43028. */
  43029. this._buffer = buffer;
  43030. /**
  43031. * An array of update ranges.
  43032. *
  43033. * @private
  43034. * @type {Array<{start: number, count: number}>}
  43035. */
  43036. this._updateRanges = [];
  43037. }
  43038. /**
  43039. * The array of update ranges.
  43040. *
  43041. * @type {Array<{start: number, count: number}>}
  43042. */
  43043. get updateRanges() {
  43044. return this._updateRanges;
  43045. }
  43046. /**
  43047. * Adds an update range.
  43048. *
  43049. * @param {number} start - The start index.
  43050. * @param {number} count - The number of elements.
  43051. */
  43052. addUpdateRange( start, count ) {
  43053. this.updateRanges.push( { start, count } );
  43054. }
  43055. /**
  43056. * Clears all update ranges.
  43057. */
  43058. clearUpdateRanges() {
  43059. this.updateRanges.length = 0;
  43060. }
  43061. /**
  43062. * The buffer's byte length.
  43063. *
  43064. * @type {number}
  43065. * @readonly
  43066. */
  43067. get byteLength() {
  43068. return getFloatLength( this._buffer.byteLength );
  43069. }
  43070. /**
  43071. * A reference to the internal buffer.
  43072. *
  43073. * @type {Float32Array}
  43074. * @readonly
  43075. */
  43076. get buffer() {
  43077. return this._buffer;
  43078. }
  43079. /**
  43080. * Updates the binding.
  43081. *
  43082. * @return {boolean} Whether the buffer has been updated and must be
  43083. * uploaded to the GPU.
  43084. */
  43085. update() {
  43086. return true;
  43087. }
  43088. }
  43089. /**
  43090. * Represents a uniform buffer binding type.
  43091. *
  43092. * @private
  43093. * @augments Buffer
  43094. */
  43095. class UniformBuffer extends Buffer {
  43096. /**
  43097. * Constructs a new uniform buffer.
  43098. *
  43099. * @param {string} name - The buffer's name.
  43100. * @param {TypedArray} [buffer=null] - The buffer.
  43101. */
  43102. constructor( name, buffer = null ) {
  43103. super( name, buffer );
  43104. /**
  43105. * This flag can be used for type testing.
  43106. *
  43107. * @type {boolean}
  43108. * @readonly
  43109. * @default true
  43110. */
  43111. this.isUniformBuffer = true;
  43112. }
  43113. }
  43114. let _id$4 = 0;
  43115. /**
  43116. * A special form of uniform buffer binding type.
  43117. * It's buffer value is managed by a node object.
  43118. *
  43119. * @private
  43120. * @augments UniformBuffer
  43121. */
  43122. class NodeUniformBuffer extends UniformBuffer {
  43123. /**
  43124. * Constructs a new node-based uniform buffer.
  43125. *
  43126. * @param {BufferNode} nodeUniform - The uniform buffer node.
  43127. * @param {UniformGroupNode} groupNode - The uniform group node.
  43128. */
  43129. constructor( nodeUniform, groupNode ) {
  43130. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  43131. /**
  43132. * The uniform buffer node.
  43133. *
  43134. * @type {BufferNode}
  43135. */
  43136. this.nodeUniform = nodeUniform;
  43137. /**
  43138. * The uniform group node.
  43139. *
  43140. * @type {UniformGroupNode}
  43141. */
  43142. this.groupNode = groupNode;
  43143. /**
  43144. * This flag can be used for type testing.
  43145. *
  43146. * @type {boolean}
  43147. * @readonly
  43148. * @default true
  43149. */
  43150. this.isNodeUniformBuffer = true;
  43151. }
  43152. /**
  43153. * The array of update ranges.
  43154. *
  43155. * @param {Array<{start: number, count: number}>} value - The update ranges.
  43156. */
  43157. set updateRanges( value ) {
  43158. this.nodeUniform.updateRanges = value;
  43159. }
  43160. /**
  43161. * The array of update ranges.
  43162. *
  43163. * @type {Array<{start: number, count: number}>}
  43164. */
  43165. get updateRanges() {
  43166. return this.nodeUniform.updateRanges;
  43167. }
  43168. /**
  43169. * Adds a range of data in the data array to be updated on the GPU.
  43170. *
  43171. * @param {number} start - Position at which to start update.
  43172. * @param {number} count - The number of components to update.
  43173. */
  43174. addUpdateRange( start, count ) {
  43175. this.nodeUniform.addUpdateRange( start, count );
  43176. }
  43177. /**
  43178. * Clears all update ranges.
  43179. */
  43180. clearUpdateRanges() {
  43181. this.nodeUniform.clearUpdateRanges();
  43182. }
  43183. /**
  43184. * The uniform buffer.
  43185. *
  43186. * @type {Float32Array}
  43187. */
  43188. get buffer() {
  43189. return this.nodeUniform.value;
  43190. }
  43191. }
  43192. /**
  43193. * This class represents a uniform buffer binding but with
  43194. * an API that allows to maintain individual uniform objects.
  43195. *
  43196. * @private
  43197. * @augments UniformBuffer
  43198. */
  43199. class UniformsGroup extends UniformBuffer {
  43200. /**
  43201. * Constructs a new uniforms group.
  43202. *
  43203. * @param {string} name - The group's name.
  43204. */
  43205. constructor( name ) {
  43206. super( name );
  43207. /**
  43208. * This flag can be used for type testing.
  43209. *
  43210. * @type {boolean}
  43211. * @readonly
  43212. * @default true
  43213. */
  43214. this.isUniformsGroup = true;
  43215. /**
  43216. * An array with the raw uniform values.
  43217. *
  43218. * @private
  43219. * @type {?Array<number>}
  43220. * @default null
  43221. */
  43222. this._values = null;
  43223. /**
  43224. * An array of uniform objects.
  43225. *
  43226. * The order of uniforms in this array must match the order of uniforms in the shader.
  43227. *
  43228. * @type {Array<Uniform>}
  43229. */
  43230. this.uniforms = [];
  43231. }
  43232. /**
  43233. * Adds a uniform to this group.
  43234. *
  43235. * @param {Uniform} uniform - The uniform to add.
  43236. * @return {UniformsGroup} A reference to this group.
  43237. */
  43238. addUniform( uniform ) {
  43239. this.uniforms.push( uniform );
  43240. return this;
  43241. }
  43242. /**
  43243. * Removes a uniform from this group.
  43244. *
  43245. * @param {Uniform} uniform - The uniform to remove.
  43246. * @return {UniformsGroup} A reference to this group.
  43247. */
  43248. removeUniform( uniform ) {
  43249. const index = this.uniforms.indexOf( uniform );
  43250. if ( index !== -1 ) {
  43251. this.uniforms.splice( index, 1 );
  43252. }
  43253. return this;
  43254. }
  43255. /**
  43256. * An array with the raw uniform values.
  43257. *
  43258. * @type {Array<number>}
  43259. */
  43260. get values() {
  43261. if ( this._values === null ) {
  43262. this._values = Array.from( this.buffer );
  43263. }
  43264. return this._values;
  43265. }
  43266. /**
  43267. * A Float32 array buffer with the uniform values.
  43268. *
  43269. * @type {Float32Array}
  43270. */
  43271. get buffer() {
  43272. let buffer = this._buffer;
  43273. if ( buffer === null ) {
  43274. const byteLength = this.byteLength;
  43275. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  43276. this._buffer = buffer;
  43277. }
  43278. return buffer;
  43279. }
  43280. /**
  43281. * The byte length of the buffer with correct buffer alignment.
  43282. *
  43283. * @type {number}
  43284. */
  43285. get byteLength() {
  43286. const bytesPerElement = this.bytesPerElement;
  43287. let offset = 0; // global buffer offset in bytes
  43288. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  43289. const uniform = this.uniforms[ i ];
  43290. const boundary = uniform.boundary;
  43291. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  43292. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  43293. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  43294. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  43295. offset += chunkPadding;
  43296. // Check for chunk overflow
  43297. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  43298. // Add padding to the end of the chunk
  43299. offset += ( GPU_CHUNK_BYTES - chunkStart );
  43300. }
  43301. uniform.offset = offset / bytesPerElement;
  43302. offset += itemSize;
  43303. }
  43304. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  43305. }
  43306. /**
  43307. * Updates this group by updating each uniform object of
  43308. * the internal uniform list. The uniform objects check if their
  43309. * values has actually changed so this method only returns
  43310. * `true` if there is a real value change.
  43311. *
  43312. * @return {boolean} Whether the uniforms have been updated and
  43313. * must be uploaded to the GPU.
  43314. */
  43315. update() {
  43316. let updated = false;
  43317. for ( const uniform of this.uniforms ) {
  43318. if ( this.updateByType( uniform ) === true ) {
  43319. updated = true;
  43320. }
  43321. }
  43322. return updated;
  43323. }
  43324. /**
  43325. * Updates a given uniform by calling an update method matching
  43326. * the uniforms type.
  43327. *
  43328. * @param {Uniform} uniform - The uniform to update.
  43329. * @return {boolean} Whether the uniform has been updated or not.
  43330. */
  43331. updateByType( uniform ) {
  43332. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  43333. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  43334. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  43335. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  43336. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  43337. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  43338. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  43339. error( 'WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  43340. }
  43341. /**
  43342. * Updates a given Number uniform.
  43343. *
  43344. * @param {NumberUniform} uniform - The Number uniform.
  43345. * @return {boolean} Whether the uniform has been updated or not.
  43346. */
  43347. updateNumber( uniform ) {
  43348. let updated = false;
  43349. const a = this.values;
  43350. const v = uniform.getValue();
  43351. const offset = uniform.offset;
  43352. const type = uniform.getType();
  43353. if ( a[ offset ] !== v ) {
  43354. const b = this._getBufferForType( type );
  43355. b[ offset ] = a[ offset ] = v;
  43356. updated = true;
  43357. }
  43358. return updated;
  43359. }
  43360. /**
  43361. * Updates a given Vector2 uniform.
  43362. *
  43363. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  43364. * @return {boolean} Whether the uniform has been updated or not.
  43365. */
  43366. updateVector2( uniform ) {
  43367. let updated = false;
  43368. const a = this.values;
  43369. const v = uniform.getValue();
  43370. const offset = uniform.offset;
  43371. const type = uniform.getType();
  43372. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  43373. const b = this._getBufferForType( type );
  43374. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  43375. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  43376. updated = true;
  43377. }
  43378. return updated;
  43379. }
  43380. /**
  43381. * Updates a given Vector3 uniform.
  43382. *
  43383. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  43384. * @return {boolean} Whether the uniform has been updated or not.
  43385. */
  43386. updateVector3( uniform ) {
  43387. let updated = false;
  43388. const a = this.values;
  43389. const v = uniform.getValue();
  43390. const offset = uniform.offset;
  43391. const type = uniform.getType();
  43392. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  43393. const b = this._getBufferForType( type );
  43394. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  43395. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  43396. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  43397. updated = true;
  43398. }
  43399. return updated;
  43400. }
  43401. /**
  43402. * Updates a given Vector4 uniform.
  43403. *
  43404. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  43405. * @return {boolean} Whether the uniform has been updated or not.
  43406. */
  43407. updateVector4( uniform ) {
  43408. let updated = false;
  43409. const a = this.values;
  43410. const v = uniform.getValue();
  43411. const offset = uniform.offset;
  43412. const type = uniform.getType();
  43413. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  43414. const b = this._getBufferForType( type );
  43415. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  43416. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  43417. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  43418. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  43419. updated = true;
  43420. }
  43421. return updated;
  43422. }
  43423. /**
  43424. * Updates a given Color uniform.
  43425. *
  43426. * @param {ColorUniform} uniform - The Color uniform.
  43427. * @return {boolean} Whether the uniform has been updated or not.
  43428. */
  43429. updateColor( uniform ) {
  43430. let updated = false;
  43431. const a = this.values;
  43432. const c = uniform.getValue();
  43433. const offset = uniform.offset;
  43434. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  43435. const b = this.buffer;
  43436. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  43437. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  43438. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  43439. updated = true;
  43440. }
  43441. return updated;
  43442. }
  43443. /**
  43444. * Updates a given Matrix3 uniform.
  43445. *
  43446. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  43447. * @return {boolean} Whether the uniform has been updated or not.
  43448. */
  43449. updateMatrix3( uniform ) {
  43450. let updated = false;
  43451. const a = this.values;
  43452. const e = uniform.getValue().elements;
  43453. const offset = uniform.offset;
  43454. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  43455. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  43456. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  43457. const b = this.buffer;
  43458. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  43459. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  43460. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  43461. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  43462. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  43463. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  43464. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  43465. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  43466. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  43467. updated = true;
  43468. }
  43469. return updated;
  43470. }
  43471. /**
  43472. * Updates a given Matrix4 uniform.
  43473. *
  43474. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  43475. * @return {boolean} Whether the uniform has been updated or not.
  43476. */
  43477. updateMatrix4( uniform ) {
  43478. let updated = false;
  43479. const a = this.values;
  43480. const e = uniform.getValue().elements;
  43481. const offset = uniform.offset;
  43482. if ( arraysEqual( a, e, offset ) === false ) {
  43483. const b = this.buffer;
  43484. b.set( e, offset );
  43485. setArray( a, e, offset );
  43486. updated = true;
  43487. }
  43488. return updated;
  43489. }
  43490. /**
  43491. * Returns a typed array that matches the given data type.
  43492. *
  43493. * @private
  43494. * @param {string} type - The data type.
  43495. * @return {TypedArray} The typed array.
  43496. */
  43497. _getBufferForType( type ) {
  43498. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  43499. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  43500. return this.buffer;
  43501. }
  43502. }
  43503. /**
  43504. * Sets the values of the second array to the first array.
  43505. *
  43506. * @private
  43507. * @param {TypedArray} a - The first array.
  43508. * @param {TypedArray} b - The second array.
  43509. * @param {number} offset - An index offset for the first array.
  43510. */
  43511. function setArray( a, b, offset ) {
  43512. for ( let i = 0, l = b.length; i < l; i ++ ) {
  43513. a[ offset + i ] = b[ i ];
  43514. }
  43515. }
  43516. /**
  43517. * Returns `true` if the given arrays are equal.
  43518. *
  43519. * @private
  43520. * @param {TypedArray} a - The first array.
  43521. * @param {TypedArray} b - The second array.
  43522. * @param {number} offset - An index offset for the first array.
  43523. * @return {boolean} Whether the given arrays are equal or not.
  43524. */
  43525. function arraysEqual( a, b, offset ) {
  43526. for ( let i = 0, l = b.length; i < l; i ++ ) {
  43527. if ( a[ offset + i ] !== b[ i ] ) return false;
  43528. }
  43529. return true;
  43530. }
  43531. let _id$3 = 0;
  43532. /**
  43533. * A special form of uniforms group that represents
  43534. * the individual uniforms as node-based uniforms.
  43535. *
  43536. * @private
  43537. * @augments UniformsGroup
  43538. */
  43539. class NodeUniformsGroup extends UniformsGroup {
  43540. /**
  43541. * Constructs a new node-based uniforms group.
  43542. *
  43543. * @param {string} name - The group's name.
  43544. * @param {UniformGroupNode} groupNode - The uniform group node.
  43545. */
  43546. constructor( name, groupNode ) {
  43547. super( name );
  43548. /**
  43549. * The group's ID.
  43550. *
  43551. * @type {number}
  43552. */
  43553. this.id = _id$3 ++;
  43554. /**
  43555. * The uniform group node.
  43556. *
  43557. * @type {UniformGroupNode}
  43558. */
  43559. this.groupNode = groupNode;
  43560. /**
  43561. * This flag can be used for type testing.
  43562. *
  43563. * @type {boolean}
  43564. * @readonly
  43565. * @default true
  43566. */
  43567. this.isNodeUniformsGroup = true;
  43568. }
  43569. }
  43570. /**
  43571. * Represents a sampler binding type.
  43572. *
  43573. * @private
  43574. * @augments Binding
  43575. */
  43576. class Sampler extends Binding {
  43577. /**
  43578. * Constructs a new sampler.
  43579. *
  43580. * @param {string} name - The samplers's name.
  43581. * @param {?Texture} texture - The texture this binding is referring to.
  43582. */
  43583. constructor( name, texture ) {
  43584. super( name );
  43585. /**
  43586. * The texture the sampler is referring to.
  43587. *
  43588. * @private
  43589. * @type {?Texture}
  43590. */
  43591. this._texture = null;
  43592. /**
  43593. * An event listener which is added to {@link texture}'s dispose event.
  43594. *
  43595. * @private
  43596. * @type {Function}
  43597. */
  43598. this._onTextureDispose = () => {
  43599. this.generation = null;
  43600. this.version = 0;
  43601. };
  43602. // Assignment to the texture via a setter must occur after "_onTextureDispose" is initialized.
  43603. this.texture = texture;
  43604. /**
  43605. * The binding's version.
  43606. *
  43607. * @type {number}
  43608. */
  43609. this.version = texture ? texture.version : 0;
  43610. /**
  43611. * The binding's generation which is an additional version
  43612. * qualifier.
  43613. *
  43614. * @type {?number}
  43615. * @default null
  43616. */
  43617. this.generation = null;
  43618. /**
  43619. * The binding's sampler key.
  43620. *
  43621. * @type {string}
  43622. * @default ''
  43623. */
  43624. this.samplerKey = '';
  43625. /**
  43626. * This flag can be used for type testing.
  43627. *
  43628. * @type {boolean}
  43629. * @readonly
  43630. * @default true
  43631. */
  43632. this.isSampler = true;
  43633. }
  43634. /**
  43635. * Sets the texture of this sampler.
  43636. *
  43637. * @param {Texture} value - The texture to set.
  43638. */
  43639. set texture( value ) {
  43640. if ( this._texture === value ) return;
  43641. if ( this._texture ) {
  43642. this._texture.removeEventListener( 'dispose', this._onTextureDispose );
  43643. }
  43644. this._texture = value;
  43645. this.generation = null;
  43646. this.version = 0;
  43647. if ( this._texture ) {
  43648. this._texture.addEventListener( 'dispose', this._onTextureDispose );
  43649. }
  43650. }
  43651. /**
  43652. * Gets the texture of this sampler.
  43653. * @return {?Texture} The texture.
  43654. */
  43655. get texture() {
  43656. return this._texture;
  43657. }
  43658. /**
  43659. * Updates the binding.
  43660. *
  43661. * @return {boolean} Whether the texture has been updated and must be
  43662. * uploaded to the GPU.
  43663. */
  43664. update() {
  43665. const { texture, version } = this;
  43666. if ( version !== texture.version ) {
  43667. this.version = texture.version;
  43668. return true;
  43669. }
  43670. return false;
  43671. }
  43672. clone() {
  43673. const clonedSampler = super.clone();
  43674. // fix dispose handler for cloned instances
  43675. // TODO: Find better solution, see #31747
  43676. clonedSampler._texture = null;
  43677. clonedSampler._onTextureDispose = () => {
  43678. clonedSampler.generation = null;
  43679. clonedSampler.version = 0;
  43680. };
  43681. clonedSampler.texture = this.texture;
  43682. return clonedSampler;
  43683. }
  43684. }
  43685. let _id$2 = 0;
  43686. /**
  43687. * Represents a sampled texture binding type.
  43688. *
  43689. * @private
  43690. * @augments Sampler
  43691. */
  43692. class SampledTexture extends Sampler {
  43693. /**
  43694. * Constructs a new sampled texture.
  43695. *
  43696. * @param {string} name - The sampled texture's name.
  43697. * @param {?Texture} texture - The texture this binding is referring to.
  43698. */
  43699. constructor( name, texture ) {
  43700. super( name, texture );
  43701. /**
  43702. * This identifier.
  43703. *
  43704. * @type {number}
  43705. */
  43706. this.id = _id$2 ++;
  43707. /**
  43708. * Whether the texture is a storage texture or not.
  43709. *
  43710. * @type {boolean}
  43711. * @default false
  43712. */
  43713. this.store = false;
  43714. /**
  43715. * The mip level to bind for storage textures.
  43716. *
  43717. * @type {number}
  43718. * @default 0
  43719. */
  43720. this.mipLevel = 0;
  43721. /**
  43722. * This flag can be used for type testing.
  43723. *
  43724. * @type {boolean}
  43725. * @readonly
  43726. * @default true
  43727. */
  43728. this.isSampledTexture = true;
  43729. }
  43730. }
  43731. /**
  43732. * A special form of sampled texture binding type.
  43733. * It's texture value is managed by a node object.
  43734. *
  43735. * @private
  43736. * @augments SampledTexture
  43737. */
  43738. class NodeSampledTexture extends SampledTexture {
  43739. /**
  43740. * Constructs a new node-based sampled texture.
  43741. *
  43742. * @param {string} name - The textures's name.
  43743. * @param {TextureNode} textureNode - The texture node.
  43744. * @param {UniformGroupNode} groupNode - The uniform group node.
  43745. * @param {?string} [access=null] - The access type.
  43746. */
  43747. constructor( name, textureNode, groupNode, access = null ) {
  43748. super( name, textureNode ? textureNode.value : null );
  43749. /**
  43750. * The texture node.
  43751. *
  43752. * @type {TextureNode}
  43753. */
  43754. this.textureNode = textureNode;
  43755. /**
  43756. * The uniform group node.
  43757. *
  43758. * @type {UniformGroupNode}
  43759. */
  43760. this.groupNode = groupNode;
  43761. /**
  43762. * The access type.
  43763. *
  43764. * @type {?string}
  43765. * @default null
  43766. */
  43767. this.access = access;
  43768. }
  43769. /**
  43770. * Updates the binding.
  43771. *
  43772. * @return {boolean} Whether the texture has been updated and must be
  43773. * uploaded to the GPU.
  43774. */
  43775. update() {
  43776. const { textureNode } = this;
  43777. if ( this.texture !== textureNode.value ) {
  43778. this.texture = textureNode.value;
  43779. return true;
  43780. }
  43781. return super.update();
  43782. }
  43783. }
  43784. /**
  43785. * A special form of sampled cube texture binding type.
  43786. * It's texture value is managed by a node object.
  43787. *
  43788. * @private
  43789. * @augments NodeSampledTexture
  43790. */
  43791. class NodeSampledCubeTexture extends NodeSampledTexture {
  43792. /**
  43793. * Constructs a new node-based sampled cube texture.
  43794. *
  43795. * @param {string} name - The textures's name.
  43796. * @param {TextureNode} textureNode - The texture node.
  43797. * @param {UniformGroupNode} groupNode - The uniform group node.
  43798. * @param {?string} [access=null] - The access type.
  43799. */
  43800. constructor( name, textureNode, groupNode, access = null ) {
  43801. super( name, textureNode, groupNode, access );
  43802. /**
  43803. * This flag can be used for type testing.
  43804. *
  43805. * @type {boolean}
  43806. * @readonly
  43807. * @default true
  43808. */
  43809. this.isSampledCubeTexture = true;
  43810. }
  43811. }
  43812. /**
  43813. * A special form of sampled 3D texture binding type.
  43814. * It's texture value is managed by a node object.
  43815. *
  43816. * @private
  43817. * @augments NodeSampledTexture
  43818. */
  43819. class NodeSampledTexture3D extends NodeSampledTexture {
  43820. /**
  43821. * Constructs a new node-based sampled 3D texture.
  43822. *
  43823. * @param {string} name - The textures's name.
  43824. * @param {TextureNode} textureNode - The texture node.
  43825. * @param {UniformGroupNode} groupNode - The uniform group node.
  43826. * @param {?string} [access=null] - The access type.
  43827. */
  43828. constructor( name, textureNode, groupNode, access = null ) {
  43829. super( name, textureNode, groupNode, access );
  43830. /**
  43831. * This flag can be used for type testing.
  43832. *
  43833. * @type {boolean}
  43834. * @readonly
  43835. * @default true
  43836. */
  43837. this.isSampledTexture3D = true;
  43838. }
  43839. }
  43840. const glslPolyfills = {
  43841. bitcast_int_uint: new CodeNode( /* glsl */'uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }' ),
  43842. bitcast_uint_int: new CodeNode( /* glsl */'uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }' )
  43843. };
  43844. const glslMethods = {
  43845. textureDimensions: 'textureSize',
  43846. equals: 'equal',
  43847. bitcast_float_int: 'floatBitsToInt',
  43848. bitcast_int_float: 'intBitsToFloat',
  43849. bitcast_uint_float: 'uintBitsToFloat',
  43850. bitcast_float_uint: 'floatBitsToUint',
  43851. bitcast_uint_int: 'tsl_bitcast_uint_to_int',
  43852. bitcast_int_uint: 'tsl_bitcast_int_to_uint'
  43853. };
  43854. const precisionLib = {
  43855. low: 'lowp',
  43856. medium: 'mediump',
  43857. high: 'highp'
  43858. };
  43859. const supports$1 = {
  43860. swizzleAssign: true,
  43861. storageBuffer: false
  43862. };
  43863. const interpolationTypeMap = {
  43864. perspective: 'smooth',
  43865. linear: 'noperspective'
  43866. };
  43867. const interpolationModeMap = {
  43868. 'centroid': 'centroid'
  43869. };
  43870. const defaultPrecisions = `
  43871. precision highp float;
  43872. precision highp int;
  43873. precision highp sampler2D;
  43874. precision highp sampler3D;
  43875. precision highp samplerCube;
  43876. precision highp sampler2DArray;
  43877. precision highp usampler2D;
  43878. precision highp usampler3D;
  43879. precision highp usamplerCube;
  43880. precision highp usampler2DArray;
  43881. precision highp isampler2D;
  43882. precision highp isampler3D;
  43883. precision highp isamplerCube;
  43884. precision highp isampler2DArray;
  43885. precision lowp sampler2DShadow;
  43886. precision lowp sampler2DArrayShadow;
  43887. precision lowp samplerCubeShadow;
  43888. `;
  43889. /**
  43890. * A node builder targeting GLSL.
  43891. *
  43892. * This module generates GLSL shader code from node materials and also
  43893. * generates the respective bindings and vertex buffer definitions. These
  43894. * data are later used by the renderer to create render and compute pipelines
  43895. * for render objects.
  43896. *
  43897. * @augments NodeBuilder
  43898. */
  43899. class GLSLNodeBuilder extends NodeBuilder {
  43900. /**
  43901. * Constructs a new GLSL node builder renderer.
  43902. *
  43903. * @param {Object3D} object - The 3D object.
  43904. * @param {Renderer} renderer - The renderer.
  43905. */
  43906. constructor( object, renderer ) {
  43907. super( object, renderer, new GLSLNodeParser() );
  43908. /**
  43909. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  43910. * another dictionary which manages UBOs per group ('render','frame','object').
  43911. *
  43912. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  43913. */
  43914. this.uniformGroups = {};
  43915. /**
  43916. * An array that holds objects defining the varying and attribute data in
  43917. * context of Transform Feedback.
  43918. *
  43919. * @type {Array<Object<string,AttributeNode|string>>}
  43920. */
  43921. this.transforms = [];
  43922. /**
  43923. * A dictionary that holds for each shader stage a Map of used extensions.
  43924. *
  43925. * @type {Object<string,Map<string,Object>>}
  43926. */
  43927. this.extensions = {};
  43928. /**
  43929. * A dictionary that holds for each shader stage an Array of used builtins.
  43930. *
  43931. * @type {Object<string,Array<string>>}
  43932. */
  43933. this.builtins = { vertex: [], fragment: [], compute: [] };
  43934. }
  43935. /**
  43936. * Checks if the given texture requires a manual conversion to the working color space.
  43937. *
  43938. * @param {Texture} texture - The texture to check.
  43939. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  43940. */
  43941. needsToWorkingColorSpace( texture ) {
  43942. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  43943. }
  43944. /**
  43945. * Includes the given method name into the current
  43946. * function node.
  43947. *
  43948. * @private
  43949. * @param {string} name - The method name to include.
  43950. * @return {CodeNode} The respective code node.
  43951. */
  43952. _include( name ) {
  43953. const codeNode = glslPolyfills[ name ];
  43954. codeNode.build( this );
  43955. this.addInclude( codeNode );
  43956. return codeNode;
  43957. }
  43958. /**
  43959. * Returns the native shader method name for a given generic name.
  43960. *
  43961. * @param {string} method - The method name to resolve.
  43962. * @return {string} The resolved GLSL method name.
  43963. */
  43964. getMethod( method ) {
  43965. if ( glslPolyfills[ method ] !== undefined ) {
  43966. this._include( method );
  43967. }
  43968. return glslMethods[ method ] || method;
  43969. }
  43970. /**
  43971. * Returns the bitcast method name for a given input and outputType.
  43972. *
  43973. * @param {string} type - The output type to bitcast to.
  43974. * @param {string} inputType - The input type of the.
  43975. * @return {string} The resolved WGSL bitcast invocation.
  43976. */
  43977. getBitcastMethod( type, inputType ) {
  43978. return this.getMethod( `bitcast_${ inputType }_${ type }` );
  43979. }
  43980. /**
  43981. * Returns the native snippet for a ternary operation.
  43982. *
  43983. * @param {string} condSnippet - The condition determining which expression gets resolved.
  43984. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  43985. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  43986. * @return {string} The resolved method name.
  43987. */
  43988. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  43989. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  43990. }
  43991. /**
  43992. * Returns the output struct name. Not relevant for GLSL.
  43993. *
  43994. * @return {string}
  43995. */
  43996. getOutputStructName() {
  43997. return '';
  43998. }
  43999. /**
  44000. * Builds the given shader node.
  44001. *
  44002. * @param {ShaderNodeInternal} shaderNode - The shader node.
  44003. * @return {string} The GLSL function code.
  44004. */
  44005. buildFunctionCode( shaderNode ) {
  44006. const layout = shaderNode.layout;
  44007. const flowData = this.flowShaderNode( shaderNode );
  44008. const parameters = [];
  44009. for ( const input of layout.inputs ) {
  44010. parameters.push( this.getType( input.type ) + ' ' + input.name );
  44011. }
  44012. //
  44013. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  44014. ${ flowData.vars }
  44015. ${ flowData.code }
  44016. return ${ flowData.result };
  44017. }`;
  44018. //
  44019. return code;
  44020. }
  44021. /**
  44022. * Setups the Pixel Buffer Object (PBO) for the given storage
  44023. * buffer node.
  44024. *
  44025. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  44026. */
  44027. setupPBO( storageBufferNode ) {
  44028. const attribute = storageBufferNode.value;
  44029. if ( attribute.pbo === undefined ) {
  44030. const originalArray = attribute.array;
  44031. const numElements = attribute.count * attribute.itemSize;
  44032. const { itemSize } = attribute;
  44033. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  44034. let format = isInteger ? RedIntegerFormat : RedFormat;
  44035. if ( itemSize === 2 ) {
  44036. format = isInteger ? RGIntegerFormat : RGFormat;
  44037. } else if ( itemSize === 3 ) {
  44038. format = isInteger ? RGBIntegerFormat : RGBFormat;
  44039. } else if ( itemSize === 4 ) {
  44040. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  44041. }
  44042. const typeMap = {
  44043. Float32Array: FloatType,
  44044. Uint8Array: UnsignedByteType,
  44045. Uint16Array: UnsignedShortType,
  44046. Uint32Array: UnsignedIntType,
  44047. Int8Array: ByteType,
  44048. Int16Array: ShortType,
  44049. Int32Array: IntType,
  44050. Uint8ClampedArray: UnsignedByteType,
  44051. };
  44052. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  44053. let height = Math.ceil( ( numElements / itemSize ) / width );
  44054. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  44055. const newSize = width * height * itemSize;
  44056. const newArray = new originalArray.constructor( newSize );
  44057. newArray.set( originalArray, 0 );
  44058. attribute.array = newArray;
  44059. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  44060. pboTexture.needsUpdate = true;
  44061. pboTexture.isPBOTexture = true;
  44062. const pbo = new TextureNode( pboTexture, null, null );
  44063. pbo.setPrecision( 'high' );
  44064. attribute.pboNode = pbo;
  44065. attribute.pbo = pbo.value;
  44066. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  44067. }
  44068. }
  44069. /**
  44070. * Returns a GLSL snippet that represents the property name of the given node.
  44071. *
  44072. * @param {Node} node - The node.
  44073. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44074. * @return {string} The property name.
  44075. */
  44076. getPropertyName( node, shaderStage = this.shaderStage ) {
  44077. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  44078. return shaderStage.charAt( 0 ) + '_' + node.name;
  44079. }
  44080. return super.getPropertyName( node, shaderStage );
  44081. }
  44082. /**
  44083. * Setups the Pixel Buffer Object (PBO) for the given storage
  44084. * buffer node.
  44085. *
  44086. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  44087. * @return {string} The property name.
  44088. */
  44089. generatePBO( storageArrayElementNode ) {
  44090. const { node, indexNode } = storageArrayElementNode;
  44091. const attribute = node.value;
  44092. if ( this.renderer.backend.has( attribute ) ) {
  44093. const attributeData = this.renderer.backend.get( attribute );
  44094. attributeData.pbo = attribute.pbo;
  44095. }
  44096. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  44097. const textureName = this.getPropertyName( nodeUniform );
  44098. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  44099. const indexSnippet = indexNode.build( this, 'uint' );
  44100. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  44101. let propertyName = elementNodeData.propertyName;
  44102. if ( propertyName === undefined ) {
  44103. // property element
  44104. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  44105. propertyName = this.getPropertyName( nodeVar );
  44106. // property size
  44107. const bufferNodeData = this.getDataFromNode( node );
  44108. let propertySizeName = bufferNodeData.propertySizeName;
  44109. if ( propertySizeName === undefined ) {
  44110. propertySizeName = propertyName + 'Size';
  44111. this.getVarFromNode( node, propertySizeName, 'uint' );
  44112. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  44113. bufferNodeData.propertySizeName = propertySizeName;
  44114. }
  44115. //
  44116. const { itemSize } = attribute;
  44117. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  44118. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  44119. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, '0', null, null );
  44120. //
  44121. let prefix = 'vec4';
  44122. if ( attribute.pbo.type === UnsignedIntType ) {
  44123. prefix = 'uvec4';
  44124. } else if ( attribute.pbo.type === IntType ) {
  44125. prefix = 'ivec4';
  44126. }
  44127. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  44128. elementNodeData.propertyName = propertyName;
  44129. }
  44130. return propertyName;
  44131. }
  44132. /**
  44133. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  44134. *
  44135. * @param {?Texture} texture - The texture.
  44136. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44137. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44138. * @param {?string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44139. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  44140. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44141. * @return {string} The GLSL snippet.
  44142. */
  44143. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  44144. if ( levelSnippet === null ) levelSnippet = '0';
  44145. let snippet;
  44146. if ( depthSnippet ) {
  44147. if ( offsetSnippet ) {
  44148. snippet = `texelFetchOffset( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet }, ${ offsetSnippet } )`;
  44149. } else {
  44150. snippet = `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  44151. }
  44152. } else {
  44153. if ( offsetSnippet ) {
  44154. snippet = `texelFetchOffset( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  44155. } else {
  44156. snippet = `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  44157. }
  44158. }
  44159. if ( texture !== null && texture.isDepthTexture ) {
  44160. snippet += '.x';
  44161. }
  44162. return snippet;
  44163. }
  44164. /**
  44165. * Generates the GLSL snippet for sampling/loading the given texture.
  44166. *
  44167. * @param {Texture} texture - The texture.
  44168. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44169. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44170. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  44171. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44172. * @return {string} The GLSL snippet.
  44173. */
  44174. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet ) {
  44175. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  44176. if ( texture.isDepthTexture ) {
  44177. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } ).x`;
  44178. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  44179. }
  44180. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } )`;
  44181. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  44182. }
  44183. /**
  44184. * Generates the GLSL snippet when sampling textures with explicit mip level.
  44185. *
  44186. * @param {Texture} texture - The texture.
  44187. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44188. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44189. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44190. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44191. * @return {string} The GLSL snippet.
  44192. */
  44193. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, offsetSnippet ) {
  44194. if ( offsetSnippet ) {
  44195. return `textureLodOffset( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  44196. }
  44197. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  44198. }
  44199. /**
  44200. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  44201. *
  44202. * @param {Texture} texture - The texture.
  44203. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44204. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44205. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  44206. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44207. * @return {string} The GLSL snippet.
  44208. */
  44209. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, offsetSnippet ) {
  44210. if ( offsetSnippet ) {
  44211. return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ biasSnippet } )`;
  44212. }
  44213. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  44214. }
  44215. /**
  44216. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  44217. *
  44218. * @param {Texture} texture - The texture.
  44219. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44220. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44221. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  44222. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44223. * @return {string} The GLSL snippet.
  44224. */
  44225. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, offsetSnippet ) {
  44226. if ( offsetSnippet ) {
  44227. return `textureGradOffset( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  44228. }
  44229. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  44230. }
  44231. /**
  44232. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  44233. * against a reference value.
  44234. *
  44235. * @param {Texture} texture - The texture.
  44236. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44237. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44238. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  44239. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  44240. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44241. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44242. * @return {string} The GLSL snippet.
  44243. */
  44244. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  44245. if ( shaderStage === 'fragment' ) {
  44246. if ( depthSnippet ) {
  44247. if ( offsetSnippet ) {
  44248. return `textureOffset( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  44249. }
  44250. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  44251. }
  44252. if ( offsetSnippet ) {
  44253. return `textureOffset( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  44254. }
  44255. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  44256. } else {
  44257. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  44258. }
  44259. }
  44260. /**
  44261. * Returns the variables of the given shader stage as a GLSL string.
  44262. *
  44263. * @param {string} shaderStage - The shader stage.
  44264. * @return {string} The GLSL snippet that defines the variables.
  44265. */
  44266. getVars( shaderStage ) {
  44267. const snippets = [];
  44268. const vars = this.vars[ shaderStage ];
  44269. if ( vars !== undefined ) {
  44270. for ( const variable of vars ) {
  44271. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  44272. }
  44273. }
  44274. return snippets.join( '\n\t' );
  44275. }
  44276. /**
  44277. * Returns the uniforms of the given shader stage as a GLSL string.
  44278. *
  44279. * @param {string} shaderStage - The shader stage.
  44280. * @return {string} The GLSL snippet that defines the uniforms.
  44281. */
  44282. getUniforms( shaderStage ) {
  44283. const uniforms = this.uniforms[ shaderStage ];
  44284. const bindingSnippets = [];
  44285. const uniformGroups = {};
  44286. for ( const uniform of uniforms ) {
  44287. let snippet = null;
  44288. let group = false;
  44289. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  44290. const texture = uniform.node.value;
  44291. let typePrefix = '';
  44292. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  44293. if ( texture.type === UnsignedIntType ) {
  44294. typePrefix = 'u';
  44295. } else if ( texture.type === IntType ) {
  44296. typePrefix = 'i';
  44297. }
  44298. }
  44299. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  44300. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  44301. } else if ( texture.compareFunction ) {
  44302. if ( texture.isArrayTexture === true ) {
  44303. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  44304. } else {
  44305. snippet = `sampler2DShadow ${ uniform.name };`;
  44306. }
  44307. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  44308. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  44309. } else {
  44310. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  44311. }
  44312. } else if ( uniform.type === 'cubeTexture' ) {
  44313. snippet = `samplerCube ${ uniform.name };`;
  44314. } else if ( uniform.type === 'buffer' ) {
  44315. const bufferNode = uniform.node;
  44316. const bufferType = this.getType( bufferNode.bufferType );
  44317. const bufferCount = bufferNode.bufferCount;
  44318. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  44319. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  44320. } else {
  44321. const vectorType = this.getVectorType( uniform.type );
  44322. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  44323. group = true;
  44324. }
  44325. const precision = uniform.node.precision;
  44326. if ( precision !== null ) {
  44327. snippet = precisionLib[ precision ] + ' ' + snippet;
  44328. }
  44329. if ( group ) {
  44330. snippet = '\t' + snippet;
  44331. const groupName = uniform.groupNode.name;
  44332. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  44333. groupSnippets.push( snippet );
  44334. } else {
  44335. snippet = 'uniform ' + snippet;
  44336. bindingSnippets.push( snippet );
  44337. }
  44338. }
  44339. let output = '';
  44340. for ( const name in uniformGroups ) {
  44341. const groupSnippets = uniformGroups[ name ];
  44342. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  44343. }
  44344. output += bindingSnippets.join( '\n' );
  44345. return output;
  44346. }
  44347. /**
  44348. * Returns the type for a given buffer attribute.
  44349. *
  44350. * @param {BufferAttribute} attribute - The buffer attribute.
  44351. * @return {string} The type.
  44352. */
  44353. getTypeFromAttribute( attribute ) {
  44354. let nodeType = super.getTypeFromAttribute( attribute );
  44355. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  44356. let dataAttribute = attribute;
  44357. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  44358. const array = dataAttribute.array;
  44359. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  44360. nodeType = nodeType.slice( 1 );
  44361. }
  44362. }
  44363. return nodeType;
  44364. }
  44365. /**
  44366. * Returns the shader attributes of the given shader stage as a GLSL string.
  44367. *
  44368. * @param {string} shaderStage - The shader stage.
  44369. * @return {string} The GLSL snippet that defines the shader attributes.
  44370. */
  44371. getAttributes( shaderStage ) {
  44372. let snippet = '';
  44373. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  44374. const attributes = this.getAttributesArray();
  44375. let location = 0;
  44376. for ( const attribute of attributes ) {
  44377. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  44378. }
  44379. }
  44380. return snippet;
  44381. }
  44382. /**
  44383. * Returns the members of the given struct type node as a GLSL string.
  44384. *
  44385. * @param {StructTypeNode} struct - The struct type node.
  44386. * @return {string} The GLSL snippet that defines the struct members.
  44387. */
  44388. getStructMembers( struct ) {
  44389. const snippets = [];
  44390. for ( const member of struct.members ) {
  44391. snippets.push( `\t${ member.type } ${ member.name };` );
  44392. }
  44393. return snippets.join( '\n' );
  44394. }
  44395. /**
  44396. * Returns the structs of the given shader stage as a GLSL string.
  44397. *
  44398. * @param {string} shaderStage - The shader stage.
  44399. * @return {string} The GLSL snippet that defines the structs.
  44400. */
  44401. getStructs( shaderStage ) {
  44402. const snippets = [];
  44403. const structs = this.structs[ shaderStage ];
  44404. const outputSnippet = [];
  44405. for ( const struct of structs ) {
  44406. if ( struct.output ) {
  44407. for ( const member of struct.members ) {
  44408. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  44409. }
  44410. } else {
  44411. let snippet = 'struct ' + struct.name + ' {\n';
  44412. snippet += this.getStructMembers( struct );
  44413. snippet += '\n};\n';
  44414. snippets.push( snippet );
  44415. }
  44416. }
  44417. if ( outputSnippet.length === 0 ) {
  44418. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  44419. }
  44420. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  44421. }
  44422. /**
  44423. * Returns the varyings of the given shader stage as a GLSL string.
  44424. *
  44425. * @param {string} shaderStage - The shader stage.
  44426. * @return {string} The GLSL snippet that defines the varyings.
  44427. */
  44428. getVaryings( shaderStage ) {
  44429. let snippet = '';
  44430. const varyings = this.varyings;
  44431. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  44432. for ( const varying of varyings ) {
  44433. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  44434. const type = this.getType( varying.type );
  44435. if ( varying.needsInterpolation ) {
  44436. if ( varying.interpolationType ) {
  44437. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  44438. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  44439. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  44440. } else {
  44441. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  44442. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  44443. }
  44444. } else {
  44445. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  44446. }
  44447. }
  44448. } else if ( shaderStage === 'fragment' ) {
  44449. for ( const varying of varyings ) {
  44450. if ( varying.needsInterpolation ) {
  44451. const type = this.getType( varying.type );
  44452. if ( varying.interpolationType ) {
  44453. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  44454. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  44455. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  44456. } else {
  44457. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  44458. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  44459. }
  44460. }
  44461. }
  44462. }
  44463. for ( const builtin of this.builtins[ shaderStage ] ) {
  44464. snippet += `${builtin};\n`;
  44465. }
  44466. return snippet;
  44467. }
  44468. /**
  44469. * Returns the vertex index builtin.
  44470. *
  44471. * @return {string} The vertex index.
  44472. */
  44473. getVertexIndex() {
  44474. return 'uint( gl_VertexID )';
  44475. }
  44476. /**
  44477. * Contextually returns either the vertex stage instance index builtin
  44478. * or the linearized index of an compute invocation within a grid of workgroups.
  44479. *
  44480. * @return {string} The instance index.
  44481. */
  44482. getInstanceIndex() {
  44483. return 'uint( gl_InstanceID )';
  44484. }
  44485. /**
  44486. * Returns a builtin representing the index of an invocation within its workgroup.
  44487. *
  44488. * @return {string} The invocation local index.
  44489. */
  44490. getInvocationLocalIndex() {
  44491. const workgroupSize = this.object.workgroupSize;
  44492. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  44493. return `uint( gl_InstanceID ) % ${size}u`;
  44494. }
  44495. /**
  44496. * Returns a builtin representing the size of a subgroup within the current shader.
  44497. */
  44498. getSubgroupSize() {
  44499. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node' );
  44500. }
  44501. /**
  44502. * Returns a builtin representing the index of an invocation within its subgroup.
  44503. */
  44504. getInvocationSubgroupIndex() {
  44505. error( 'GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node' );
  44506. }
  44507. /**
  44508. * Returns a builtin representing the index of the current invocation's subgroup within its workgroup.
  44509. */
  44510. getSubgroupIndex() {
  44511. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node' );
  44512. }
  44513. /**
  44514. * Returns the draw index builtin.
  44515. *
  44516. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  44517. */
  44518. getDrawIndex() {
  44519. const extensions = this.renderer.backend.extensions;
  44520. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  44521. return 'uint( gl_DrawID )';
  44522. }
  44523. return null;
  44524. }
  44525. /**
  44526. * Returns the front facing builtin.
  44527. *
  44528. * @return {string} The front facing builtin.
  44529. */
  44530. getFrontFacing() {
  44531. return 'gl_FrontFacing';
  44532. }
  44533. /**
  44534. * Returns the frag coord builtin.
  44535. *
  44536. * @return {string} The frag coord builtin.
  44537. */
  44538. getFragCoord() {
  44539. return 'gl_FragCoord.xy';
  44540. }
  44541. /**
  44542. * Returns the frag depth builtin.
  44543. *
  44544. * @return {string} The frag depth builtin.
  44545. */
  44546. getFragDepth() {
  44547. return 'gl_FragDepth';
  44548. }
  44549. /**
  44550. * Enables the given extension.
  44551. *
  44552. * @param {string} name - The extension name.
  44553. * @param {string} behavior - The extension behavior.
  44554. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  44555. */
  44556. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  44557. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  44558. if ( map.has( name ) === false ) {
  44559. map.set( name, {
  44560. name,
  44561. behavior
  44562. } );
  44563. }
  44564. }
  44565. /**
  44566. * Returns the enabled extensions of the given shader stage as a GLSL string.
  44567. *
  44568. * @param {string} shaderStage - The shader stage.
  44569. * @return {string} The GLSL snippet that defines the enabled extensions.
  44570. */
  44571. getExtensions( shaderStage ) {
  44572. const snippets = [];
  44573. if ( shaderStage === 'vertex' ) {
  44574. const ext = this.renderer.backend.extensions;
  44575. const isBatchedMesh = this.object.isBatchedMesh;
  44576. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  44577. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  44578. }
  44579. }
  44580. const extensions = this.extensions[ shaderStage ];
  44581. if ( extensions !== undefined ) {
  44582. for ( const { name, behavior } of extensions.values() ) {
  44583. snippets.push( `#extension ${name} : ${behavior}` );
  44584. }
  44585. }
  44586. return snippets.join( '\n' );
  44587. }
  44588. /**
  44589. * Returns the clip distances builtin.
  44590. *
  44591. * @return {string} The clip distances builtin.
  44592. */
  44593. getClipDistance() {
  44594. return 'gl_ClipDistance';
  44595. }
  44596. /**
  44597. * Whether the requested feature is available or not.
  44598. *
  44599. * @param {string} name - The requested feature.
  44600. * @return {boolean} Whether the requested feature is supported or not.
  44601. */
  44602. isAvailable( name ) {
  44603. let result = supports$1[ name ];
  44604. if ( result === undefined ) {
  44605. let extensionName;
  44606. result = false;
  44607. switch ( name ) {
  44608. case 'float32Filterable':
  44609. extensionName = 'OES_texture_float_linear';
  44610. break;
  44611. case 'clipDistance':
  44612. extensionName = 'WEBGL_clip_cull_distance';
  44613. break;
  44614. }
  44615. if ( extensionName !== undefined ) {
  44616. const extensions = this.renderer.backend.extensions;
  44617. if ( extensions.has( extensionName ) ) {
  44618. extensions.get( extensionName );
  44619. result = true;
  44620. }
  44621. }
  44622. supports$1[ name ] = result;
  44623. }
  44624. return result;
  44625. }
  44626. /**
  44627. * Whether to flip texture data along its vertical axis or not.
  44628. *
  44629. * @return {boolean} Returns always `true` in context of GLSL.
  44630. */
  44631. isFlipY() {
  44632. return true;
  44633. }
  44634. /**
  44635. * Enables hardware clipping.
  44636. *
  44637. * @param {string} planeCount - The clipping plane count.
  44638. */
  44639. enableHardwareClipping( planeCount ) {
  44640. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  44641. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  44642. }
  44643. /**
  44644. * Enables multiview.
  44645. */
  44646. enableMultiview() {
  44647. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  44648. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  44649. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  44650. }
  44651. /**
  44652. * Registers a transform in context of Transform Feedback.
  44653. *
  44654. * @param {string} varyingName - The varying name.
  44655. * @param {AttributeNode} attributeNode - The attribute node.
  44656. */
  44657. registerTransform( varyingName, attributeNode ) {
  44658. this.transforms.push( { varyingName, attributeNode } );
  44659. }
  44660. /**
  44661. * Returns the transforms of the given shader stage as a GLSL string.
  44662. *
  44663. * @param {string} shaderStage - The shader stage.
  44664. * @return {string} The GLSL snippet that defines the transforms.
  44665. */
  44666. getTransforms( /* shaderStage */ ) {
  44667. const transforms = this.transforms;
  44668. let snippet = '';
  44669. for ( let i = 0; i < transforms.length; i ++ ) {
  44670. const transform = transforms[ i ];
  44671. const attributeName = this.getPropertyName( transform.attributeNode );
  44672. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  44673. }
  44674. return snippet;
  44675. }
  44676. /**
  44677. * Returns a GLSL struct based on the given name and variables.
  44678. *
  44679. * @private
  44680. * @param {string} name - The struct name.
  44681. * @param {string} vars - The struct variables.
  44682. * @return {string} The GLSL snippet representing a struct.
  44683. */
  44684. _getGLSLUniformStruct( name, vars ) {
  44685. return `
  44686. layout( std140 ) uniform ${name} {
  44687. ${vars}
  44688. };`;
  44689. }
  44690. /**
  44691. * Returns a GLSL vertex shader based on the given shader data.
  44692. *
  44693. * @private
  44694. * @param {Object} shaderData - The shader data.
  44695. * @return {string} The vertex shader.
  44696. */
  44697. _getGLSLVertexCode( shaderData ) {
  44698. return `#version 300 es
  44699. ${ this.getSignature() }
  44700. // extensions
  44701. ${shaderData.extensions}
  44702. // precision
  44703. ${ defaultPrecisions }
  44704. // uniforms
  44705. ${shaderData.uniforms}
  44706. // varyings
  44707. ${shaderData.varyings}
  44708. // attributes
  44709. ${shaderData.attributes}
  44710. // codes
  44711. ${shaderData.codes}
  44712. void main() {
  44713. // vars
  44714. ${shaderData.vars}
  44715. // transforms
  44716. ${shaderData.transforms}
  44717. // flow
  44718. ${shaderData.flow}
  44719. gl_PointSize = 1.0;
  44720. }
  44721. `;
  44722. }
  44723. /**
  44724. * Returns a GLSL fragment shader based on the given shader data.
  44725. *
  44726. * @private
  44727. * @param {Object} shaderData - The shader data.
  44728. * @return {string} The vertex shader.
  44729. */
  44730. _getGLSLFragmentCode( shaderData ) {
  44731. return `#version 300 es
  44732. ${ this.getSignature() }
  44733. // extensions
  44734. ${shaderData.extensions}
  44735. // precision
  44736. ${ defaultPrecisions }
  44737. // structs
  44738. ${shaderData.structs}
  44739. // uniforms
  44740. ${shaderData.uniforms}
  44741. // varyings
  44742. ${shaderData.varyings}
  44743. // codes
  44744. ${shaderData.codes}
  44745. void main() {
  44746. // vars
  44747. ${shaderData.vars}
  44748. // flow
  44749. ${shaderData.flow}
  44750. }
  44751. `;
  44752. }
  44753. /**
  44754. * Controls the code build of the shader stages.
  44755. */
  44756. buildCode() {
  44757. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  44758. this.sortBindingGroups();
  44759. for ( const shaderStage in shadersData ) {
  44760. let flow = '// code\n\n';
  44761. flow += this.flowCode[ shaderStage ];
  44762. const flowNodes = this.flowNodes[ shaderStage ];
  44763. const mainNode = flowNodes[ flowNodes.length - 1 ];
  44764. for ( const node of flowNodes ) {
  44765. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  44766. const slotName = node.name;
  44767. if ( slotName ) {
  44768. if ( flow.length > 0 ) flow += '\n';
  44769. flow += `\t// flow -> ${ slotName }\n\t`;
  44770. }
  44771. flow += `${ flowSlotData.code }\n\t`;
  44772. if ( node === mainNode && shaderStage !== 'compute' ) {
  44773. flow += '// result\n\t';
  44774. if ( shaderStage === 'vertex' ) {
  44775. flow += 'gl_Position = ';
  44776. flow += `${ flowSlotData.result };`;
  44777. } else if ( shaderStage === 'fragment' ) {
  44778. if ( ! node.outputNode.isOutputStructNode ) {
  44779. flow += 'fragColor = ';
  44780. flow += `${ flowSlotData.result };`;
  44781. }
  44782. }
  44783. }
  44784. }
  44785. const stageData = shadersData[ shaderStage ];
  44786. stageData.extensions = this.getExtensions( shaderStage );
  44787. stageData.uniforms = this.getUniforms( shaderStage );
  44788. stageData.attributes = this.getAttributes( shaderStage );
  44789. stageData.varyings = this.getVaryings( shaderStage );
  44790. stageData.vars = this.getVars( shaderStage );
  44791. stageData.structs = this.getStructs( shaderStage );
  44792. stageData.codes = this.getCodes( shaderStage );
  44793. stageData.transforms = this.getTransforms( shaderStage );
  44794. stageData.flow = flow;
  44795. }
  44796. if ( this.material !== null ) {
  44797. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  44798. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  44799. } else {
  44800. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  44801. }
  44802. }
  44803. /**
  44804. * This method is one of the more important ones since it's responsible
  44805. * for generating a matching binding instance for the given uniform node.
  44806. *
  44807. * These bindings are later used in the renderer to create bind groups
  44808. * and layouts.
  44809. *
  44810. * @param {UniformNode} node - The uniform node.
  44811. * @param {string} type - The node data type.
  44812. * @param {string} shaderStage - The shader stage.
  44813. * @param {?string} [name=null] - An optional uniform name.
  44814. * @return {NodeUniform} The node uniform object.
  44815. */
  44816. getUniformFromNode( node, type, shaderStage, name = null ) {
  44817. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  44818. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  44819. let uniformGPU = nodeData.uniformGPU;
  44820. if ( uniformGPU === undefined ) {
  44821. const group = node.groupNode;
  44822. const groupName = group.name;
  44823. const bindings = this.getBindGroupArray( groupName, shaderStage );
  44824. if ( type === 'texture' ) {
  44825. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  44826. bindings.push( uniformGPU );
  44827. } else if ( type === 'cubeTexture' ) {
  44828. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  44829. bindings.push( uniformGPU );
  44830. } else if ( type === 'texture3D' ) {
  44831. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  44832. bindings.push( uniformGPU );
  44833. } else if ( type === 'buffer' ) {
  44834. uniformNode.name = `buffer${ node.id }`;
  44835. const sharedData = this.getSharedDataFromNode( node );
  44836. let buffer = sharedData.buffer;
  44837. if ( buffer === undefined ) {
  44838. node.name = `NodeBuffer_${ node.id }`;
  44839. buffer = new NodeUniformBuffer( node, group );
  44840. buffer.name = node.name;
  44841. sharedData.buffer = buffer;
  44842. }
  44843. bindings.push( buffer );
  44844. uniformGPU = buffer;
  44845. } else {
  44846. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  44847. let uniformsGroup = uniformsStage[ groupName ];
  44848. if ( uniformsGroup === undefined ) {
  44849. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  44850. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44851. uniformsStage[ groupName ] = uniformsGroup;
  44852. bindings.push( uniformsGroup );
  44853. }
  44854. uniformGPU = this.getNodeUniform( uniformNode, type );
  44855. uniformsGroup.addUniform( uniformGPU );
  44856. }
  44857. nodeData.uniformGPU = uniformGPU;
  44858. }
  44859. return uniformNode;
  44860. }
  44861. }
  44862. let _vector2 = null;
  44863. let _color4 = null;
  44864. /**
  44865. * Most of the rendering related logic is implemented in the
  44866. * {@link Renderer} module and related management components.
  44867. * Sometimes it is required though to execute commands which are
  44868. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  44869. * This abstract base class defines an interface that encapsulates
  44870. * all backend-related logic. Derived classes for each backend must
  44871. * implement the interface.
  44872. *
  44873. * @abstract
  44874. * @private
  44875. */
  44876. class Backend {
  44877. /**
  44878. * Constructs a new backend.
  44879. *
  44880. * @param {Object} parameters - An object holding parameters for the backend.
  44881. */
  44882. constructor( parameters = {} ) {
  44883. /**
  44884. * The parameters of the backend.
  44885. *
  44886. * @type {Object}
  44887. */
  44888. this.parameters = Object.assign( {}, parameters );
  44889. /**
  44890. * This weak map holds backend-specific data of objects
  44891. * like textures, attributes or render targets.
  44892. *
  44893. * @type {WeakMap<Object, Object>}
  44894. */
  44895. this.data = new WeakMap();
  44896. /**
  44897. * A reference to the renderer.
  44898. *
  44899. * @type {?Renderer}
  44900. * @default null
  44901. */
  44902. this.renderer = null;
  44903. /**
  44904. * A reference to the canvas element the renderer is drawing to.
  44905. *
  44906. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  44907. * @default null
  44908. */
  44909. this.domElement = null;
  44910. /**
  44911. * A reference to the timestamp query pool.
  44912. *
  44913. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  44914. */
  44915. this.timestampQueryPool = {
  44916. [ TimestampQuery.RENDER ]: null,
  44917. [ TimestampQuery.COMPUTE ]: null
  44918. };
  44919. /**
  44920. * Whether to track timestamps with a Timestamp Query API or not.
  44921. *
  44922. * @type {boolean}
  44923. * @default false
  44924. */
  44925. this.trackTimestamp = ( parameters.trackTimestamp === true );
  44926. }
  44927. /**
  44928. * Initializes the backend so it is ready for usage. Concrete backends
  44929. * are supposed to implement their rendering context creation and related
  44930. * operations in this method.
  44931. *
  44932. * @async
  44933. * @param {Renderer} renderer - The renderer.
  44934. * @return {Promise} A Promise that resolves when the backend has been initialized.
  44935. */
  44936. async init( renderer ) {
  44937. this.renderer = renderer;
  44938. }
  44939. /**
  44940. * The coordinate system of the backend.
  44941. *
  44942. * @abstract
  44943. * @type {number}
  44944. * @readonly
  44945. */
  44946. get coordinateSystem() {}
  44947. // render context
  44948. /**
  44949. * This method is executed at the beginning of a render call and
  44950. * can be used by the backend to prepare the state for upcoming
  44951. * draw calls.
  44952. *
  44953. * @abstract
  44954. * @param {RenderContext} renderContext - The render context.
  44955. */
  44956. beginRender( /*renderContext*/ ) {}
  44957. /**
  44958. * This method is executed at the end of a render call and
  44959. * can be used by the backend to finalize work after draw
  44960. * calls.
  44961. *
  44962. * @abstract
  44963. * @param {RenderContext} renderContext - The render context.
  44964. */
  44965. finishRender( /*renderContext*/ ) {}
  44966. /**
  44967. * This method is executed at the beginning of a compute call and
  44968. * can be used by the backend to prepare the state for upcoming
  44969. * compute tasks.
  44970. *
  44971. * @abstract
  44972. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  44973. */
  44974. beginCompute( /*computeGroup*/ ) {}
  44975. /**
  44976. * This method is executed at the end of a compute call and
  44977. * can be used by the backend to finalize work after compute
  44978. * tasks.
  44979. *
  44980. * @abstract
  44981. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  44982. */
  44983. finishCompute( /*computeGroup*/ ) {}
  44984. // render object
  44985. /**
  44986. * Executes a draw command for the given render object.
  44987. *
  44988. * @abstract
  44989. * @param {RenderObject} renderObject - The render object to draw.
  44990. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  44991. */
  44992. draw( /*renderObject, info*/ ) { }
  44993. // compute node
  44994. /**
  44995. * Executes a compute command for the given compute node.
  44996. *
  44997. * @abstract
  44998. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  44999. * @param {Node} computeNode - The compute node.
  45000. * @param {Array<BindGroup>} bindings - The bindings.
  45001. * @param {ComputePipeline} computePipeline - The compute pipeline.
  45002. */
  45003. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  45004. // program
  45005. /**
  45006. * Creates a shader program from the given programmable stage.
  45007. *
  45008. * @abstract
  45009. * @param {ProgrammableStage} program - The programmable stage.
  45010. */
  45011. createProgram( /*program*/ ) { }
  45012. /**
  45013. * Destroys the shader program of the given programmable stage.
  45014. *
  45015. * @abstract
  45016. * @param {ProgrammableStage} program - The programmable stage.
  45017. */
  45018. destroyProgram( /*program*/ ) { }
  45019. // bindings
  45020. /**
  45021. * Creates bindings from the given bind group definition.
  45022. *
  45023. * @abstract
  45024. * @param {BindGroup} bindGroup - The bind group.
  45025. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45026. * @param {number} cacheIndex - The cache index.
  45027. * @param {number} version - The version.
  45028. */
  45029. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  45030. /**
  45031. * Updates the given bind group definition.
  45032. *
  45033. * @abstract
  45034. * @param {BindGroup} bindGroup - The bind group.
  45035. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45036. * @param {number} cacheIndex - The cache index.
  45037. * @param {number} version - The version.
  45038. */
  45039. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  45040. /**
  45041. * Updates a buffer binding.
  45042. *
  45043. * @abstract
  45044. * @param {Buffer} binding - The buffer binding to update.
  45045. */
  45046. updateBinding( /*binding*/ ) { }
  45047. // pipeline
  45048. /**
  45049. * Creates a render pipeline for the given render object.
  45050. *
  45051. * @abstract
  45052. * @param {RenderObject} renderObject - The render object.
  45053. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  45054. */
  45055. createRenderPipeline( /*renderObject, promises*/ ) { }
  45056. /**
  45057. * Creates a compute pipeline for the given compute node.
  45058. *
  45059. * @abstract
  45060. * @param {ComputePipeline} computePipeline - The compute pipeline.
  45061. * @param {Array<BindGroup>} bindings - The bindings.
  45062. */
  45063. createComputePipeline( /*computePipeline, bindings*/ ) { }
  45064. // cache key
  45065. /**
  45066. * Returns `true` if the render pipeline requires an update.
  45067. *
  45068. * @abstract
  45069. * @param {RenderObject} renderObject - The render object.
  45070. * @return {boolean} Whether the render pipeline requires an update or not.
  45071. */
  45072. needsRenderUpdate( /*renderObject*/ ) { }
  45073. /**
  45074. * Returns a cache key that is used to identify render pipelines.
  45075. *
  45076. * @abstract
  45077. * @param {RenderObject} renderObject - The render object.
  45078. * @return {string} The cache key.
  45079. */
  45080. getRenderCacheKey( /*renderObject*/ ) { }
  45081. // node builder
  45082. /**
  45083. * Returns a node builder for the given render object.
  45084. *
  45085. * @abstract
  45086. * @param {RenderObject} renderObject - The render object.
  45087. * @param {Renderer} renderer - The renderer.
  45088. * @return {NodeBuilder} The node builder.
  45089. */
  45090. createNodeBuilder( /*renderObject, renderer*/ ) { }
  45091. // textures
  45092. /**
  45093. * Updates a GPU sampler for the given texture.
  45094. *
  45095. * @abstract
  45096. * @param {Texture} texture - The texture to update the sampler for.
  45097. * @return {string} The current sampler key.
  45098. */
  45099. updateSampler( /*texture*/ ) { }
  45100. /**
  45101. * Creates a default texture for the given texture that can be used
  45102. * as a placeholder until the actual texture is ready for usage.
  45103. *
  45104. * @abstract
  45105. * @param {Texture} texture - The texture to create a default texture for.
  45106. */
  45107. createDefaultTexture( /*texture*/ ) { }
  45108. /**
  45109. * Defines a texture on the GPU for the given texture object.
  45110. *
  45111. * @abstract
  45112. * @param {Texture} texture - The texture.
  45113. * @param {Object} [options={}] - Optional configuration parameter.
  45114. */
  45115. createTexture( /*texture, options={}*/ ) { }
  45116. /**
  45117. * Uploads the updated texture data to the GPU.
  45118. *
  45119. * @abstract
  45120. * @param {Texture} texture - The texture.
  45121. * @param {Object} [options={}] - Optional configuration parameter.
  45122. */
  45123. updateTexture( /*texture, options = {}*/ ) { }
  45124. /**
  45125. * Generates mipmaps for the given texture.
  45126. *
  45127. * @abstract
  45128. * @param {Texture} texture - The texture.
  45129. */
  45130. generateMipmaps( /*texture*/ ) { }
  45131. /**
  45132. * Destroys the GPU data for the given texture object.
  45133. *
  45134. * @abstract
  45135. * @param {Texture} texture - The texture.
  45136. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  45137. */
  45138. destroyTexture( /*texture, isDefaultTexture*/ ) { }
  45139. /**
  45140. * Returns texture data as a typed array.
  45141. *
  45142. * @abstract
  45143. * @async
  45144. * @param {Texture} texture - The texture to copy.
  45145. * @param {number} x - The x coordinate of the copy origin.
  45146. * @param {number} y - The y coordinate of the copy origin.
  45147. * @param {number} width - The width of the copy.
  45148. * @param {number} height - The height of the copy.
  45149. * @param {number} faceIndex - The face index.
  45150. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  45151. */
  45152. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  45153. /**
  45154. * Copies data of the given source texture to the given destination texture.
  45155. *
  45156. * @abstract
  45157. * @param {Texture} srcTexture - The source texture.
  45158. * @param {Texture} dstTexture - The destination texture.
  45159. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  45160. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  45161. * @param {number} [srcLevel=0] - The source mip level to copy from.
  45162. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  45163. */
  45164. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  45165. /**
  45166. * Copies the current bound framebuffer to the given texture.
  45167. *
  45168. * @abstract
  45169. * @param {Texture} texture - The destination texture.
  45170. * @param {RenderContext} renderContext - The render context.
  45171. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  45172. */
  45173. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  45174. // attributes
  45175. /**
  45176. * Creates the GPU buffer of a shader attribute.
  45177. *
  45178. * @abstract
  45179. * @param {BufferAttribute} attribute - The buffer attribute.
  45180. */
  45181. createAttribute( /*attribute*/ ) { }
  45182. /**
  45183. * Creates the GPU buffer of an indexed shader attribute.
  45184. *
  45185. * @abstract
  45186. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  45187. */
  45188. createIndexAttribute( /*attribute*/ ) { }
  45189. /**
  45190. * Creates the GPU buffer of a storage attribute.
  45191. *
  45192. * @abstract
  45193. * @param {BufferAttribute} attribute - The buffer attribute.
  45194. */
  45195. createStorageAttribute( /*attribute*/ ) { }
  45196. /**
  45197. * Updates the GPU buffer of a shader attribute.
  45198. *
  45199. * @abstract
  45200. * @param {BufferAttribute} attribute - The buffer attribute to update.
  45201. */
  45202. updateAttribute( /*attribute*/ ) { }
  45203. /**
  45204. * Destroys the GPU buffer of a shader attribute.
  45205. *
  45206. * @abstract
  45207. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  45208. */
  45209. destroyAttribute( /*attribute*/ ) { }
  45210. // canvas
  45211. /**
  45212. * Returns the backend's rendering context.
  45213. *
  45214. * @abstract
  45215. * @return {Object} The rendering context.
  45216. */
  45217. getContext() { }
  45218. /**
  45219. * Backends can use this method if they have to run
  45220. * logic when the renderer gets resized.
  45221. *
  45222. * @abstract
  45223. */
  45224. updateSize() { }
  45225. /**
  45226. * Updates the viewport with the values from the given render context.
  45227. *
  45228. * @abstract
  45229. * @param {RenderContext} renderContext - The render context.
  45230. */
  45231. updateViewport( /*renderContext*/ ) {}
  45232. // utils
  45233. /**
  45234. * Updates a unique identifier for the given render context that can be used
  45235. * to allocate resources like occlusion queries or timestamp queries.
  45236. *
  45237. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  45238. */
  45239. updateTimeStampUID( abstractRenderContext ) {
  45240. const contextData = this.get( abstractRenderContext );
  45241. const frame = this.renderer.info.frame;
  45242. let prefix;
  45243. if ( abstractRenderContext.isComputeNode === true ) {
  45244. prefix = 'c:' + this.renderer.info.compute.frameCalls;
  45245. } else {
  45246. prefix = 'r:' + this.renderer.info.render.frameCalls;
  45247. }
  45248. contextData.timestampUID = prefix + ':' + abstractRenderContext.id + ':f' + frame;
  45249. }
  45250. /**
  45251. * Returns a unique identifier for the given render context that can be used
  45252. * to allocate resources like occlusion queries or timestamp queries.
  45253. *
  45254. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  45255. * @return {string} The unique identifier.
  45256. */
  45257. getTimestampUID( abstractRenderContext ) {
  45258. return this.get( abstractRenderContext ).timestampUID;
  45259. }
  45260. /**
  45261. * Returns all timestamp frames for the given type.
  45262. *
  45263. * @param {string} type - The type of the time stamp.
  45264. * @return {Array<number>} The timestamp frames.
  45265. */
  45266. getTimestampFrames( type ) {
  45267. const queryPool = this.timestampQueryPool[ type ];
  45268. return queryPool ? queryPool.getTimestampFrames() : [];
  45269. }
  45270. /**
  45271. * Returns the query pool for the given uid.
  45272. *
  45273. * @param {string} uid - The unique identifier.
  45274. * @return {TimestampQueryPool} The query pool.
  45275. */
  45276. _getQueryPool( uid ) {
  45277. const type = uid.startsWith( 'c:' ) ? TimestampQuery.COMPUTE : TimestampQuery.RENDER;
  45278. const queryPool = this.timestampQueryPool[ type ];
  45279. return queryPool;
  45280. }
  45281. /**
  45282. * Returns the timestamp for the given uid.
  45283. *
  45284. * @param {string} uid - The unique identifier.
  45285. * @return {number} The timestamp.
  45286. */
  45287. getTimestamp( uid ) {
  45288. const queryPool = this._getQueryPool( uid );
  45289. return queryPool.getTimestamp( uid );
  45290. }
  45291. /**
  45292. * Returns `true` if a timestamp for the given uid is available.
  45293. *
  45294. * @param {string} uid - The unique identifier.
  45295. * @return {boolean} Whether the timestamp is available or not.
  45296. */
  45297. hasTimestamp( uid ) {
  45298. const queryPool = this._getQueryPool( uid );
  45299. return queryPool.hasTimestamp( uid );
  45300. }
  45301. /**
  45302. * Returns `true` if the given 3D object is fully occluded by other
  45303. * 3D objects in the scene. Backends must implement this method by using
  45304. * a Occlusion Query API.
  45305. *
  45306. * @abstract
  45307. * @param {RenderContext} renderContext - The render context.
  45308. * @param {Object3D} object - The 3D object to test.
  45309. * @return {boolean} Whether the 3D object is fully occluded or not.
  45310. */
  45311. isOccluded( /*renderContext, object*/ ) {}
  45312. /**
  45313. * Resolves the time stamp for the given render context and type.
  45314. *
  45315. * @async
  45316. * @abstract
  45317. * @param {string} [type='render'] - The type of the time stamp.
  45318. * @return {Promise<number>} A Promise that resolves with the time stamp.
  45319. */
  45320. async resolveTimestampsAsync( type = 'render' ) {
  45321. if ( ! this.trackTimestamp ) {
  45322. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  45323. return;
  45324. }
  45325. const queryPool = this.timestampQueryPool[ type ];
  45326. if ( ! queryPool ) {
  45327. return;
  45328. }
  45329. const duration = await queryPool.resolveQueriesAsync();
  45330. this.renderer.info[ type ].timestamp = duration;
  45331. return duration;
  45332. }
  45333. /**
  45334. * This method performs a readback operation by moving buffer data from
  45335. * a storage buffer attribute from the GPU to the CPU.
  45336. *
  45337. * @async
  45338. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  45339. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  45340. */
  45341. async getArrayBufferAsync( /* attribute */ ) {}
  45342. /**
  45343. * Checks if the given feature is supported by the backend.
  45344. *
  45345. * @async
  45346. * @abstract
  45347. * @param {string} name - The feature's name.
  45348. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  45349. */
  45350. async hasFeatureAsync( /*name*/ ) { }
  45351. /**
  45352. * Checks if the given feature is supported by the backend.
  45353. *
  45354. * @abstract
  45355. * @param {string} name - The feature's name.
  45356. * @return {boolean} Whether the feature is supported or not.
  45357. */
  45358. hasFeature( /*name*/ ) {}
  45359. /**
  45360. * Returns the maximum anisotropy texture filtering value.
  45361. *
  45362. * @abstract
  45363. * @return {number} The maximum anisotropy texture filtering value.
  45364. */
  45365. getMaxAnisotropy() {}
  45366. /**
  45367. * Returns the drawing buffer size.
  45368. *
  45369. * @return {Vector2} The drawing buffer size.
  45370. */
  45371. getDrawingBufferSize() {
  45372. _vector2 = _vector2 || new Vector2();
  45373. return this.renderer.getDrawingBufferSize( _vector2 );
  45374. }
  45375. /**
  45376. * Defines the scissor test.
  45377. *
  45378. * @abstract
  45379. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  45380. */
  45381. setScissorTest( /*boolean*/ ) { }
  45382. /**
  45383. * Returns the clear color and alpha into a single
  45384. * color object.
  45385. *
  45386. * @return {Color4} The clear color.
  45387. */
  45388. getClearColor() {
  45389. const renderer = this.renderer;
  45390. _color4 = _color4 || new Color4();
  45391. renderer.getClearColor( _color4 );
  45392. _color4.getRGB( _color4 );
  45393. return _color4;
  45394. }
  45395. /**
  45396. * Returns the DOM element. If no DOM element exists, the backend
  45397. * creates a new one.
  45398. *
  45399. * @return {HTMLCanvasElement} The DOM element.
  45400. */
  45401. getDomElement() {
  45402. let domElement = this.domElement;
  45403. if ( domElement === null ) {
  45404. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  45405. // OffscreenCanvas does not have setAttribute, see #22811
  45406. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  45407. this.domElement = domElement;
  45408. }
  45409. return domElement;
  45410. }
  45411. /**
  45412. * Sets a dictionary for the given object into the
  45413. * internal data structure.
  45414. *
  45415. * @param {Object} object - The object.
  45416. * @param {Object} value - The dictionary to set.
  45417. */
  45418. set( object, value ) {
  45419. this.data.set( object, value );
  45420. }
  45421. /**
  45422. * Returns the dictionary for the given object.
  45423. *
  45424. * @param {Object} object - The object.
  45425. * @return {Object} The object's dictionary.
  45426. */
  45427. get( object ) {
  45428. let map = this.data.get( object );
  45429. if ( map === undefined ) {
  45430. map = {};
  45431. this.data.set( object, map );
  45432. }
  45433. return map;
  45434. }
  45435. /**
  45436. * Checks if the given object has a dictionary
  45437. * with data defined.
  45438. *
  45439. * @param {Object} object - The object.
  45440. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  45441. */
  45442. has( object ) {
  45443. return this.data.has( object );
  45444. }
  45445. /**
  45446. * Deletes an object from the internal data structure.
  45447. *
  45448. * @param {Object} object - The object to delete.
  45449. */
  45450. delete( object ) {
  45451. this.data.delete( object );
  45452. }
  45453. /**
  45454. * Frees internal resources.
  45455. *
  45456. * @abstract
  45457. */
  45458. dispose() { }
  45459. }
  45460. let _id$1 = 0;
  45461. /**
  45462. * This module is internally used in context of compute shaders.
  45463. * This type of shader is not natively supported in WebGL 2 and
  45464. * thus implemented via Transform Feedback. `DualAttributeData`
  45465. * manages the related data.
  45466. *
  45467. * @private
  45468. */
  45469. class DualAttributeData {
  45470. constructor( attributeData, dualBuffer ) {
  45471. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  45472. this.type = attributeData.type;
  45473. this.bufferType = attributeData.bufferType;
  45474. this.pbo = attributeData.pbo;
  45475. this.byteLength = attributeData.byteLength;
  45476. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  45477. this.version = attributeData.version;
  45478. this.isInteger = attributeData.isInteger;
  45479. this.activeBufferIndex = 0;
  45480. this.baseId = attributeData.id;
  45481. }
  45482. get id() {
  45483. return `${ this.baseId }|${ this.activeBufferIndex }`;
  45484. }
  45485. get bufferGPU() {
  45486. return this.buffers[ this.activeBufferIndex ];
  45487. }
  45488. get transformBuffer() {
  45489. return this.buffers[ this.activeBufferIndex ^ 1 ];
  45490. }
  45491. switchBuffers() {
  45492. this.activeBufferIndex ^= 1;
  45493. }
  45494. }
  45495. /**
  45496. * A WebGL 2 backend utility module for managing shader attributes.
  45497. *
  45498. * @private
  45499. */
  45500. class WebGLAttributeUtils {
  45501. /**
  45502. * Constructs a new utility object.
  45503. *
  45504. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45505. */
  45506. constructor( backend ) {
  45507. /**
  45508. * A reference to the WebGL 2 backend.
  45509. *
  45510. * @type {WebGLBackend}
  45511. */
  45512. this.backend = backend;
  45513. }
  45514. /**
  45515. * Creates the GPU buffer for the given buffer attribute.
  45516. *
  45517. * @param {BufferAttribute} attribute - The buffer attribute.
  45518. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  45519. */
  45520. createAttribute( attribute, bufferType ) {
  45521. const backend = this.backend;
  45522. const { gl } = backend;
  45523. const array = attribute.array;
  45524. const usage = attribute.usage || gl.STATIC_DRAW;
  45525. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  45526. const bufferData = backend.get( bufferAttribute );
  45527. let bufferGPU = bufferData.bufferGPU;
  45528. if ( bufferGPU === undefined ) {
  45529. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  45530. bufferData.bufferGPU = bufferGPU;
  45531. bufferData.bufferType = bufferType;
  45532. bufferData.version = bufferAttribute.version;
  45533. }
  45534. //attribute.onUploadCallback();
  45535. let type;
  45536. if ( array instanceof Float32Array ) {
  45537. type = gl.FLOAT;
  45538. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  45539. type = gl.HALF_FLOAT;
  45540. } else if ( array instanceof Uint16Array ) {
  45541. if ( attribute.isFloat16BufferAttribute ) {
  45542. type = gl.HALF_FLOAT;
  45543. } else {
  45544. type = gl.UNSIGNED_SHORT;
  45545. }
  45546. } else if ( array instanceof Int16Array ) {
  45547. type = gl.SHORT;
  45548. } else if ( array instanceof Uint32Array ) {
  45549. type = gl.UNSIGNED_INT;
  45550. } else if ( array instanceof Int32Array ) {
  45551. type = gl.INT;
  45552. } else if ( array instanceof Int8Array ) {
  45553. type = gl.BYTE;
  45554. } else if ( array instanceof Uint8Array ) {
  45555. type = gl.UNSIGNED_BYTE;
  45556. } else if ( array instanceof Uint8ClampedArray ) {
  45557. type = gl.UNSIGNED_BYTE;
  45558. } else {
  45559. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  45560. }
  45561. let attributeData = {
  45562. bufferGPU,
  45563. bufferType,
  45564. type,
  45565. byteLength: array.byteLength,
  45566. bytesPerElement: array.BYTES_PER_ELEMENT,
  45567. version: attribute.version,
  45568. pbo: attribute.pbo,
  45569. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  45570. id: _id$1 ++
  45571. };
  45572. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  45573. // create buffer for transform feedback use
  45574. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  45575. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  45576. }
  45577. backend.set( attribute, attributeData );
  45578. }
  45579. /**
  45580. * Updates the GPU buffer of the given buffer attribute.
  45581. *
  45582. * @param {BufferAttribute} attribute - The buffer attribute.
  45583. */
  45584. updateAttribute( attribute ) {
  45585. const backend = this.backend;
  45586. const { gl } = backend;
  45587. const array = attribute.array;
  45588. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  45589. const bufferData = backend.get( bufferAttribute );
  45590. const bufferType = bufferData.bufferType;
  45591. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  45592. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  45593. if ( updateRanges.length === 0 ) {
  45594. // Not using update ranges
  45595. gl.bufferSubData( bufferType, 0, array );
  45596. } else {
  45597. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  45598. const range = updateRanges[ i ];
  45599. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  45600. array, range.start, range.count );
  45601. }
  45602. bufferAttribute.clearUpdateRanges();
  45603. }
  45604. gl.bindBuffer( bufferType, null );
  45605. bufferData.version = bufferAttribute.version;
  45606. }
  45607. /**
  45608. * Destroys the GPU buffer of the given buffer attribute.
  45609. *
  45610. * @param {BufferAttribute} attribute - The buffer attribute.
  45611. */
  45612. destroyAttribute( attribute ) {
  45613. const backend = this.backend;
  45614. const { gl } = backend;
  45615. if ( attribute.isInterleavedBufferAttribute ) {
  45616. backend.delete( attribute.data );
  45617. }
  45618. const attributeData = backend.get( attribute );
  45619. gl.deleteBuffer( attributeData.bufferGPU );
  45620. backend.delete( attribute );
  45621. }
  45622. /**
  45623. * This method performs a readback operation by moving buffer data from
  45624. * a storage buffer attribute from the GPU to the CPU.
  45625. *
  45626. * @async
  45627. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  45628. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  45629. */
  45630. async getArrayBufferAsync( attribute ) {
  45631. const backend = this.backend;
  45632. const { gl } = backend;
  45633. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  45634. const { bufferGPU } = backend.get( bufferAttribute );
  45635. const array = attribute.array;
  45636. const byteLength = array.byteLength;
  45637. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  45638. const writeBuffer = gl.createBuffer();
  45639. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  45640. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  45641. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  45642. await backend.utils._clientWaitAsync();
  45643. const dstBuffer = new attribute.array.constructor( array.length );
  45644. // Ensure the buffer is bound before reading
  45645. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  45646. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  45647. gl.deleteBuffer( writeBuffer );
  45648. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  45649. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  45650. return dstBuffer.buffer;
  45651. }
  45652. /**
  45653. * Creates a WebGL buffer with the given data.
  45654. *
  45655. * @private
  45656. * @param {WebGL2RenderingContext} gl - The rendering context.
  45657. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  45658. * @param {TypedArray} array - The array of the buffer attribute.
  45659. * @param {GLenum} usage - The usage.
  45660. * @return {WebGLBuffer} The WebGL buffer.
  45661. */
  45662. _createBuffer( gl, bufferType, array, usage ) {
  45663. const bufferGPU = gl.createBuffer();
  45664. gl.bindBuffer( bufferType, bufferGPU );
  45665. gl.bufferData( bufferType, array, usage );
  45666. gl.bindBuffer( bufferType, null );
  45667. return bufferGPU;
  45668. }
  45669. }
  45670. let equationToGL, factorToGL;
  45671. /**
  45672. * A WebGL 2 backend utility module for managing the WebGL state.
  45673. *
  45674. * The major goal of this module is to reduce the number of state changes
  45675. * by caching the WEbGL state with a series of variables. In this way, the
  45676. * renderer only executes state change commands when necessary which
  45677. * improves the overall performance.
  45678. *
  45679. * @private
  45680. */
  45681. class WebGLState {
  45682. /**
  45683. * Constructs a new utility object.
  45684. *
  45685. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45686. */
  45687. constructor( backend ) {
  45688. /**
  45689. * A reference to the WebGL 2 backend.
  45690. *
  45691. * @type {WebGLBackend}
  45692. */
  45693. this.backend = backend;
  45694. /**
  45695. * A reference to the rendering context.
  45696. *
  45697. * @type {WebGL2RenderingContext}
  45698. */
  45699. this.gl = this.backend.gl;
  45700. // Below properties are intended to cache
  45701. // the WebGL state and are not explicitly
  45702. // documented for convenience reasons.
  45703. this.enabled = {};
  45704. this.currentFlipSided = null;
  45705. this.currentCullFace = null;
  45706. this.currentProgram = null;
  45707. this.currentBlendingEnabled = false;
  45708. this.currentBlending = null;
  45709. this.currentBlendSrc = null;
  45710. this.currentBlendDst = null;
  45711. this.currentBlendSrcAlpha = null;
  45712. this.currentBlendDstAlpha = null;
  45713. this.currentPremultipledAlpha = null;
  45714. this.currentPolygonOffsetFactor = null;
  45715. this.currentPolygonOffsetUnits = null;
  45716. this.currentColorMask = null;
  45717. this.currentDepthFunc = null;
  45718. this.currentDepthMask = null;
  45719. this.currentStencilFunc = null;
  45720. this.currentStencilRef = null;
  45721. this.currentStencilFuncMask = null;
  45722. this.currentStencilFail = null;
  45723. this.currentStencilZFail = null;
  45724. this.currentStencilZPass = null;
  45725. this.currentStencilMask = null;
  45726. this.currentLineWidth = null;
  45727. this.currentClippingPlanes = 0;
  45728. this.currentVAO = null;
  45729. this.currentIndex = null;
  45730. this.currentBoundFramebuffers = {};
  45731. this.currentDrawbuffers = new WeakMap();
  45732. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  45733. this.currentTextureSlot = null;
  45734. this.currentBoundTextures = {};
  45735. this.currentBoundBufferBases = {};
  45736. this._init();
  45737. }
  45738. /**
  45739. * Inits the state of the utility.
  45740. *
  45741. * @private
  45742. */
  45743. _init() {
  45744. const gl = this.gl;
  45745. // Store only WebGL constants here.
  45746. equationToGL = {
  45747. [ AddEquation ]: gl.FUNC_ADD,
  45748. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  45749. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  45750. };
  45751. factorToGL = {
  45752. [ ZeroFactor ]: gl.ZERO,
  45753. [ OneFactor ]: gl.ONE,
  45754. [ SrcColorFactor ]: gl.SRC_COLOR,
  45755. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  45756. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  45757. [ DstColorFactor ]: gl.DST_COLOR,
  45758. [ DstAlphaFactor ]: gl.DST_ALPHA,
  45759. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  45760. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  45761. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  45762. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  45763. };
  45764. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  45765. const viewportParam = gl.getParameter( gl.VIEWPORT );
  45766. this.currentScissor = new Vector4().fromArray( scissorParam );
  45767. this.currentViewport = new Vector4().fromArray( viewportParam );
  45768. this._tempVec4 = new Vector4();
  45769. }
  45770. /**
  45771. * Enables the given WebGL capability.
  45772. *
  45773. * This method caches the capability state so
  45774. * `gl.enable()` is only called when necessary.
  45775. *
  45776. * @param {GLenum} id - The capability to enable.
  45777. */
  45778. enable( id ) {
  45779. const { enabled } = this;
  45780. if ( enabled[ id ] !== true ) {
  45781. this.gl.enable( id );
  45782. enabled[ id ] = true;
  45783. }
  45784. }
  45785. /**
  45786. * Disables the given WebGL capability.
  45787. *
  45788. * This method caches the capability state so
  45789. * `gl.disable()` is only called when necessary.
  45790. *
  45791. * @param {GLenum} id - The capability to enable.
  45792. */
  45793. disable( id ) {
  45794. const { enabled } = this;
  45795. if ( enabled[ id ] !== false ) {
  45796. this.gl.disable( id );
  45797. enabled[ id ] = false;
  45798. }
  45799. }
  45800. /**
  45801. * Specifies whether polygons are front- or back-facing
  45802. * by setting the winding orientation.
  45803. *
  45804. * This method caches the state so `gl.frontFace()` is only
  45805. * called when necessary.
  45806. *
  45807. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  45808. */
  45809. setFlipSided( flipSided ) {
  45810. if ( this.currentFlipSided !== flipSided ) {
  45811. const { gl } = this;
  45812. if ( flipSided ) {
  45813. gl.frontFace( gl.CW );
  45814. } else {
  45815. gl.frontFace( gl.CCW );
  45816. }
  45817. this.currentFlipSided = flipSided;
  45818. }
  45819. }
  45820. /**
  45821. * Specifies whether or not front- and/or back-facing
  45822. * polygons can be culled.
  45823. *
  45824. * This method caches the state so `gl.cullFace()` is only
  45825. * called when necessary.
  45826. *
  45827. * @param {number} cullFace - Defines which polygons are candidates for culling.
  45828. */
  45829. setCullFace( cullFace ) {
  45830. const { gl } = this;
  45831. if ( cullFace !== CullFaceNone ) {
  45832. this.enable( gl.CULL_FACE );
  45833. if ( cullFace !== this.currentCullFace ) {
  45834. if ( cullFace === CullFaceBack ) {
  45835. gl.cullFace( gl.BACK );
  45836. } else if ( cullFace === CullFaceFront ) {
  45837. gl.cullFace( gl.FRONT );
  45838. } else {
  45839. gl.cullFace( gl.FRONT_AND_BACK );
  45840. }
  45841. }
  45842. } else {
  45843. this.disable( gl.CULL_FACE );
  45844. }
  45845. this.currentCullFace = cullFace;
  45846. }
  45847. /**
  45848. * Specifies the width of line primitives.
  45849. *
  45850. * This method caches the state so `gl.lineWidth()` is only
  45851. * called when necessary.
  45852. *
  45853. * @param {number} width - The line width.
  45854. */
  45855. setLineWidth( width ) {
  45856. const { currentLineWidth, gl } = this;
  45857. if ( width !== currentLineWidth ) {
  45858. gl.lineWidth( width );
  45859. this.currentLineWidth = width;
  45860. }
  45861. }
  45862. setMRTBlending( textures ) {
  45863. const gl = this.gl;
  45864. const drawBuffersIndexedExt = this.backend.drawBuffersIndexedExt;
  45865. if ( ! drawBuffersIndexedExt ) return;
  45866. for ( let i = 1; i < textures.length; i ++ ) {
  45867. // use opaque blending for additional render targets
  45868. drawBuffersIndexedExt.blendFuncSeparateiOES( i, gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  45869. }
  45870. }
  45871. /**
  45872. * Defines the blending.
  45873. *
  45874. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  45875. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  45876. *
  45877. * @param {number} blending - The blending type.
  45878. * @param {number} blendEquation - The blending equation.
  45879. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  45880. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  45881. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  45882. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  45883. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  45884. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  45885. */
  45886. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  45887. const { gl } = this;
  45888. if ( blending === NoBlending ) {
  45889. if ( this.currentBlendingEnabled === true ) {
  45890. this.disable( gl.BLEND );
  45891. this.currentBlendingEnabled = false;
  45892. }
  45893. return;
  45894. }
  45895. if ( this.currentBlendingEnabled === false ) {
  45896. this.enable( gl.BLEND );
  45897. this.currentBlendingEnabled = true;
  45898. }
  45899. if ( blending !== CustomBlending ) {
  45900. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  45901. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  45902. gl.blendEquation( gl.FUNC_ADD );
  45903. this.currentBlendEquation = AddEquation;
  45904. this.currentBlendEquationAlpha = AddEquation;
  45905. }
  45906. if ( premultipliedAlpha ) {
  45907. switch ( blending ) {
  45908. case NormalBlending:
  45909. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  45910. break;
  45911. case AdditiveBlending:
  45912. gl.blendFunc( gl.ONE, gl.ONE );
  45913. break;
  45914. case SubtractiveBlending:
  45915. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  45916. break;
  45917. case MultiplyBlending:
  45918. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  45919. break;
  45920. default:
  45921. error( 'WebGLState: Invalid blending: ', blending );
  45922. break;
  45923. }
  45924. } else {
  45925. switch ( blending ) {
  45926. case NormalBlending:
  45927. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  45928. break;
  45929. case AdditiveBlending:
  45930. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  45931. break;
  45932. case SubtractiveBlending:
  45933. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  45934. break;
  45935. case MultiplyBlending:
  45936. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  45937. break;
  45938. default:
  45939. error( 'WebGLState: Invalid blending: ', blending );
  45940. break;
  45941. }
  45942. }
  45943. this.currentBlendSrc = null;
  45944. this.currentBlendDst = null;
  45945. this.currentBlendSrcAlpha = null;
  45946. this.currentBlendDstAlpha = null;
  45947. this.currentBlending = blending;
  45948. this.currentPremultipledAlpha = premultipliedAlpha;
  45949. }
  45950. return;
  45951. }
  45952. // custom blending
  45953. blendEquationAlpha = blendEquationAlpha || blendEquation;
  45954. blendSrcAlpha = blendSrcAlpha || blendSrc;
  45955. blendDstAlpha = blendDstAlpha || blendDst;
  45956. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  45957. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  45958. this.currentBlendEquation = blendEquation;
  45959. this.currentBlendEquationAlpha = blendEquationAlpha;
  45960. }
  45961. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  45962. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  45963. this.currentBlendSrc = blendSrc;
  45964. this.currentBlendDst = blendDst;
  45965. this.currentBlendSrcAlpha = blendSrcAlpha;
  45966. this.currentBlendDstAlpha = blendDstAlpha;
  45967. }
  45968. this.currentBlending = blending;
  45969. this.currentPremultipledAlpha = false;
  45970. }
  45971. /**
  45972. * Specifies whether colors can be written when rendering
  45973. * into a framebuffer or not.
  45974. *
  45975. * This method caches the state so `gl.colorMask()` is only
  45976. * called when necessary.
  45977. *
  45978. * @param {boolean} colorMask - The color mask.
  45979. */
  45980. setColorMask( colorMask ) {
  45981. if ( this.currentColorMask !== colorMask ) {
  45982. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  45983. this.currentColorMask = colorMask;
  45984. }
  45985. }
  45986. /**
  45987. * Specifies whether the depth test is enabled or not.
  45988. *
  45989. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  45990. */
  45991. setDepthTest( depthTest ) {
  45992. const { gl } = this;
  45993. if ( depthTest ) {
  45994. this.enable( gl.DEPTH_TEST );
  45995. } else {
  45996. this.disable( gl.DEPTH_TEST );
  45997. }
  45998. }
  45999. /**
  46000. * Specifies whether depth values can be written when rendering
  46001. * into a framebuffer or not.
  46002. *
  46003. * This method caches the state so `gl.depthMask()` is only
  46004. * called when necessary.
  46005. *
  46006. * @param {boolean} depthMask - The depth mask.
  46007. */
  46008. setDepthMask( depthMask ) {
  46009. if ( this.currentDepthMask !== depthMask ) {
  46010. this.gl.depthMask( depthMask );
  46011. this.currentDepthMask = depthMask;
  46012. }
  46013. }
  46014. /**
  46015. * Specifies the depth compare function.
  46016. *
  46017. * This method caches the state so `gl.depthFunc()` is only
  46018. * called when necessary.
  46019. *
  46020. * @param {number} depthFunc - The depth compare function.
  46021. */
  46022. setDepthFunc( depthFunc ) {
  46023. if ( this.currentDepthFunc !== depthFunc ) {
  46024. const { gl } = this;
  46025. switch ( depthFunc ) {
  46026. case NeverDepth:
  46027. gl.depthFunc( gl.NEVER );
  46028. break;
  46029. case AlwaysDepth:
  46030. gl.depthFunc( gl.ALWAYS );
  46031. break;
  46032. case LessDepth:
  46033. gl.depthFunc( gl.LESS );
  46034. break;
  46035. case LessEqualDepth:
  46036. gl.depthFunc( gl.LEQUAL );
  46037. break;
  46038. case EqualDepth:
  46039. gl.depthFunc( gl.EQUAL );
  46040. break;
  46041. case GreaterEqualDepth:
  46042. gl.depthFunc( gl.GEQUAL );
  46043. break;
  46044. case GreaterDepth:
  46045. gl.depthFunc( gl.GREATER );
  46046. break;
  46047. case NotEqualDepth:
  46048. gl.depthFunc( gl.NOTEQUAL );
  46049. break;
  46050. default:
  46051. gl.depthFunc( gl.LEQUAL );
  46052. }
  46053. this.currentDepthFunc = depthFunc;
  46054. }
  46055. }
  46056. /**
  46057. * Specifies the scissor box.
  46058. *
  46059. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  46060. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  46061. * @param {number} width - The width of the viewport.
  46062. * @param {number} height - The height of the viewport.
  46063. *
  46064. */
  46065. scissor( x, y, width, height ) {
  46066. const scissor = this._tempVec4.set( x, y, width, height );
  46067. if ( this.currentScissor.equals( scissor ) === false ) {
  46068. const { gl } = this;
  46069. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  46070. this.currentScissor.copy( scissor );
  46071. }
  46072. }
  46073. /**
  46074. * Specifies the viewport.
  46075. *
  46076. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  46077. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  46078. * @param {number} width - The width of the viewport.
  46079. * @param {number} height - The height of the viewport.
  46080. *
  46081. */
  46082. viewport( x, y, width, height ) {
  46083. const viewport = this._tempVec4.set( x, y, width, height );
  46084. if ( this.currentViewport.equals( viewport ) === false ) {
  46085. const { gl } = this;
  46086. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  46087. this.currentViewport.copy( viewport );
  46088. }
  46089. }
  46090. /**
  46091. * Defines the scissor test.
  46092. *
  46093. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  46094. */
  46095. setScissorTest( boolean ) {
  46096. const gl = this.gl;
  46097. if ( boolean ) {
  46098. gl.enable( gl.SCISSOR_TEST );
  46099. } else {
  46100. gl.disable( gl.SCISSOR_TEST );
  46101. }
  46102. }
  46103. /**
  46104. * Specifies whether the stencil test is enabled or not.
  46105. *
  46106. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  46107. */
  46108. setStencilTest( stencilTest ) {
  46109. const { gl } = this;
  46110. if ( stencilTest ) {
  46111. this.enable( gl.STENCIL_TEST );
  46112. } else {
  46113. this.disable( gl.STENCIL_TEST );
  46114. }
  46115. }
  46116. /**
  46117. * Specifies whether stencil values can be written when rendering
  46118. * into a framebuffer or not.
  46119. *
  46120. * This method caches the state so `gl.stencilMask()` is only
  46121. * called when necessary.
  46122. *
  46123. * @param {boolean} stencilMask - The stencil mask.
  46124. */
  46125. setStencilMask( stencilMask ) {
  46126. if ( this.currentStencilMask !== stencilMask ) {
  46127. this.gl.stencilMask( stencilMask );
  46128. this.currentStencilMask = stencilMask;
  46129. }
  46130. }
  46131. /**
  46132. * Specifies whether the stencil test functions.
  46133. *
  46134. * This method caches the state so `gl.stencilFunc()` is only
  46135. * called when necessary.
  46136. *
  46137. * @param {number} stencilFunc - The stencil compare function.
  46138. * @param {number} stencilRef - The reference value for the stencil test.
  46139. * @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.
  46140. */
  46141. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  46142. if ( this.currentStencilFunc !== stencilFunc ||
  46143. this.currentStencilRef !== stencilRef ||
  46144. this.currentStencilFuncMask !== stencilMask ) {
  46145. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  46146. this.currentStencilFunc = stencilFunc;
  46147. this.currentStencilRef = stencilRef;
  46148. this.currentStencilFuncMask = stencilMask;
  46149. }
  46150. }
  46151. /**
  46152. * Specifies whether the stencil test operation.
  46153. *
  46154. * This method caches the state so `gl.stencilOp()` is only
  46155. * called when necessary.
  46156. *
  46157. * @param {number} stencilFail - The function to use when the stencil test fails.
  46158. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  46159. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  46160. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  46161. */
  46162. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  46163. if ( this.currentStencilFail !== stencilFail ||
  46164. this.currentStencilZFail !== stencilZFail ||
  46165. this.currentStencilZPass !== stencilZPass ) {
  46166. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  46167. this.currentStencilFail = stencilFail;
  46168. this.currentStencilZFail = stencilZFail;
  46169. this.currentStencilZPass = stencilZPass;
  46170. }
  46171. }
  46172. /**
  46173. * Configures the WebGL state for the given material.
  46174. *
  46175. * @param {Material} material - The material to configure the state for.
  46176. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  46177. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  46178. */
  46179. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  46180. const { gl } = this;
  46181. material.side === DoubleSide
  46182. ? this.disable( gl.CULL_FACE )
  46183. : this.enable( gl.CULL_FACE );
  46184. let flipSided = ( material.side === BackSide );
  46185. if ( frontFaceCW ) flipSided = ! flipSided;
  46186. this.setFlipSided( flipSided );
  46187. ( material.blending === NormalBlending && material.transparent === false )
  46188. ? this.setBlending( NoBlending )
  46189. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  46190. this.setDepthFunc( material.depthFunc );
  46191. this.setDepthTest( material.depthTest );
  46192. this.setDepthMask( material.depthWrite );
  46193. this.setColorMask( material.colorWrite );
  46194. const stencilWrite = material.stencilWrite;
  46195. this.setStencilTest( stencilWrite );
  46196. if ( stencilWrite ) {
  46197. this.setStencilMask( material.stencilWriteMask );
  46198. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  46199. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  46200. }
  46201. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  46202. material.alphaToCoverage === true && this.backend.renderer.currentSamples > 0
  46203. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  46204. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  46205. if ( hardwareClippingPlanes > 0 ) {
  46206. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  46207. const CLIP_DISTANCE0_WEBGL = 0x3000;
  46208. for ( let i = 0; i < 8; i ++ ) {
  46209. if ( i < hardwareClippingPlanes ) {
  46210. this.enable( CLIP_DISTANCE0_WEBGL + i );
  46211. } else {
  46212. this.disable( CLIP_DISTANCE0_WEBGL + i );
  46213. }
  46214. }
  46215. }
  46216. }
  46217. }
  46218. /**
  46219. * Specifies the polygon offset.
  46220. *
  46221. * This method caches the state so `gl.polygonOffset()` is only
  46222. * called when necessary.
  46223. *
  46224. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  46225. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  46226. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  46227. */
  46228. setPolygonOffset( polygonOffset, factor, units ) {
  46229. const { gl } = this;
  46230. if ( polygonOffset ) {
  46231. this.enable( gl.POLYGON_OFFSET_FILL );
  46232. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  46233. gl.polygonOffset( factor, units );
  46234. this.currentPolygonOffsetFactor = factor;
  46235. this.currentPolygonOffsetUnits = units;
  46236. }
  46237. } else {
  46238. this.disable( gl.POLYGON_OFFSET_FILL );
  46239. }
  46240. }
  46241. /**
  46242. * Defines the usage of the given WebGL program.
  46243. *
  46244. * This method caches the state so `gl.useProgram()` is only
  46245. * called when necessary.
  46246. *
  46247. * @param {WebGLProgram} program - The WebGL program to use.
  46248. * @return {boolean} Whether a program change has been executed or not.
  46249. */
  46250. useProgram( program ) {
  46251. if ( this.currentProgram !== program ) {
  46252. this.gl.useProgram( program );
  46253. this.currentProgram = program;
  46254. return true;
  46255. }
  46256. return false;
  46257. }
  46258. /**
  46259. * Sets the vertex state by binding the given VAO and element buffer.
  46260. *
  46261. * @param {WebGLVertexArrayObject} vao - The VAO.
  46262. * @param {?WebGLBuffer} indexBuffer - The index buffer.
  46263. * @return {boolean} Whether a vertex state has been changed or not.
  46264. */
  46265. setVertexState( vao, indexBuffer = null ) {
  46266. const gl = this.gl;
  46267. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  46268. gl.bindVertexArray( vao );
  46269. if ( indexBuffer !== null ) {
  46270. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  46271. }
  46272. this.currentVAO = vao;
  46273. this.currentIndex = indexBuffer;
  46274. return true;
  46275. }
  46276. return false;
  46277. }
  46278. /**
  46279. * Resets the vertex array state by resetting the VAO and element buffer.
  46280. */
  46281. resetVertexState() {
  46282. const gl = this.gl;
  46283. gl.bindVertexArray( null );
  46284. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  46285. this.currentVAO = null;
  46286. this.currentIndex = null;
  46287. }
  46288. // framebuffer
  46289. /**
  46290. * Binds the given framebuffer.
  46291. *
  46292. * This method caches the state so `gl.bindFramebuffer()` is only
  46293. * called when necessary.
  46294. *
  46295. * @param {number} target - The binding point (target).
  46296. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  46297. * @return {boolean} Whether a bind has been executed or not.
  46298. */
  46299. bindFramebuffer( target, framebuffer ) {
  46300. const { gl, currentBoundFramebuffers } = this;
  46301. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  46302. gl.bindFramebuffer( target, framebuffer );
  46303. currentBoundFramebuffers[ target ] = framebuffer;
  46304. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  46305. if ( target === gl.DRAW_FRAMEBUFFER ) {
  46306. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  46307. }
  46308. if ( target === gl.FRAMEBUFFER ) {
  46309. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  46310. }
  46311. return true;
  46312. }
  46313. return false;
  46314. }
  46315. /**
  46316. * Defines draw buffers to which fragment colors are written into.
  46317. * Configures the MRT setup of custom framebuffers.
  46318. *
  46319. * This method caches the state so `gl.drawBuffers()` is only
  46320. * called when necessary.
  46321. *
  46322. * @param {RenderContext} renderContext - The render context.
  46323. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  46324. */
  46325. drawBuffers( renderContext, framebuffer ) {
  46326. const { gl } = this;
  46327. let drawBuffers = [];
  46328. let needsUpdate = false;
  46329. if ( renderContext.textures !== null ) {
  46330. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  46331. if ( drawBuffers === undefined ) {
  46332. drawBuffers = [];
  46333. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  46334. }
  46335. const textures = renderContext.textures;
  46336. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  46337. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  46338. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  46339. }
  46340. drawBuffers.length = textures.length;
  46341. needsUpdate = true;
  46342. }
  46343. } else {
  46344. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  46345. drawBuffers[ 0 ] = gl.BACK;
  46346. needsUpdate = true;
  46347. }
  46348. }
  46349. if ( needsUpdate ) {
  46350. gl.drawBuffers( drawBuffers );
  46351. }
  46352. }
  46353. // texture
  46354. /**
  46355. * Makes the given texture unit active.
  46356. *
  46357. * This method caches the state so `gl.activeTexture()` is only
  46358. * called when necessary.
  46359. *
  46360. * @param {number} webglSlot - The texture unit to make active.
  46361. */
  46362. activeTexture( webglSlot ) {
  46363. const { gl, currentTextureSlot, maxTextures } = this;
  46364. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  46365. if ( currentTextureSlot !== webglSlot ) {
  46366. gl.activeTexture( webglSlot );
  46367. this.currentTextureSlot = webglSlot;
  46368. }
  46369. }
  46370. /**
  46371. * Binds the given WebGL texture to a target.
  46372. *
  46373. * This method caches the state so `gl.bindTexture()` is only
  46374. * called when necessary.
  46375. *
  46376. * @param {number} webglType - The binding point (target).
  46377. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  46378. * @param {number} webglSlot - The texture.
  46379. */
  46380. bindTexture( webglType, webglTexture, webglSlot ) {
  46381. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  46382. if ( webglSlot === undefined ) {
  46383. if ( currentTextureSlot === null ) {
  46384. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  46385. } else {
  46386. webglSlot = currentTextureSlot;
  46387. }
  46388. }
  46389. let boundTexture = currentBoundTextures[ webglSlot ];
  46390. if ( boundTexture === undefined ) {
  46391. boundTexture = { type: undefined, texture: undefined };
  46392. currentBoundTextures[ webglSlot ] = boundTexture;
  46393. }
  46394. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  46395. if ( currentTextureSlot !== webglSlot ) {
  46396. gl.activeTexture( webglSlot );
  46397. this.currentTextureSlot = webglSlot;
  46398. }
  46399. gl.bindTexture( webglType, webglTexture );
  46400. boundTexture.type = webglType;
  46401. boundTexture.texture = webglTexture;
  46402. }
  46403. }
  46404. /**
  46405. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  46406. *
  46407. * This method caches the state so `gl.bindBufferBase()` is only
  46408. * called when necessary.
  46409. *
  46410. * @param {number} target - The target for the bind operation.
  46411. * @param {number} index - The index of the target.
  46412. * @param {WebGLBuffer} buffer - The WebGL buffer.
  46413. * @return {boolean} Whether a bind has been executed or not.
  46414. */
  46415. bindBufferBase( target, index, buffer ) {
  46416. const { gl } = this;
  46417. const key = `${target}-${index}`;
  46418. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  46419. gl.bindBufferBase( target, index, buffer );
  46420. this.currentBoundBufferBases[ key ] = buffer;
  46421. return true;
  46422. }
  46423. return false;
  46424. }
  46425. /**
  46426. * Unbinds the current bound texture.
  46427. *
  46428. * This method caches the state so `gl.bindTexture()` is only
  46429. * called when necessary.
  46430. */
  46431. unbindTexture() {
  46432. const { gl, currentTextureSlot, currentBoundTextures } = this;
  46433. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  46434. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  46435. gl.bindTexture( boundTexture.type, null );
  46436. boundTexture.type = undefined;
  46437. boundTexture.texture = undefined;
  46438. }
  46439. }
  46440. }
  46441. /**
  46442. * A WebGL 2 backend utility module with common helpers.
  46443. *
  46444. * @private
  46445. */
  46446. class WebGLUtils {
  46447. /**
  46448. * Constructs a new utility object.
  46449. *
  46450. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46451. */
  46452. constructor( backend ) {
  46453. /**
  46454. * A reference to the WebGL 2 backend.
  46455. *
  46456. * @type {WebGLBackend}
  46457. */
  46458. this.backend = backend;
  46459. /**
  46460. * A reference to the rendering context.
  46461. *
  46462. * @type {WebGL2RenderingContext}
  46463. */
  46464. this.gl = this.backend.gl;
  46465. /**
  46466. * A reference to a backend module holding extension-related
  46467. * utility functions.
  46468. *
  46469. * @type {WebGLExtensions}
  46470. */
  46471. this.extensions = backend.extensions;
  46472. }
  46473. /**
  46474. * Converts the given three.js constant into a WebGL constant.
  46475. * The method currently supports the conversion of texture formats
  46476. * and types.
  46477. *
  46478. * @param {number} p - The three.js constant.
  46479. * @param {string} [colorSpace=NoColorSpace] - The color space.
  46480. * @return {?number} The corresponding WebGL constant.
  46481. */
  46482. convert( p, colorSpace = NoColorSpace ) {
  46483. const { gl, extensions } = this;
  46484. let extension;
  46485. const transfer = ColorManagement.getTransfer( colorSpace );
  46486. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  46487. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  46488. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  46489. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  46490. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  46491. if ( p === ByteType ) return gl.BYTE;
  46492. if ( p === ShortType ) return gl.SHORT;
  46493. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  46494. if ( p === IntType ) return gl.INT;
  46495. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  46496. if ( p === FloatType ) return gl.FLOAT;
  46497. if ( p === HalfFloatType ) {
  46498. return gl.HALF_FLOAT;
  46499. }
  46500. if ( p === AlphaFormat ) return gl.ALPHA;
  46501. if ( p === RGBFormat ) return gl.RGB;
  46502. if ( p === RGBAFormat ) return gl.RGBA;
  46503. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  46504. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  46505. // WebGL2 formats.
  46506. if ( p === RedFormat ) return gl.RED;
  46507. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  46508. if ( p === RGFormat ) return gl.RG;
  46509. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  46510. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  46511. // S3TC
  46512. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  46513. if ( transfer === SRGBTransfer ) {
  46514. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  46515. if ( extension !== null ) {
  46516. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  46517. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  46518. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  46519. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  46520. } else {
  46521. return null;
  46522. }
  46523. } else {
  46524. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  46525. if ( extension !== null ) {
  46526. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  46527. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  46528. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  46529. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  46530. } else {
  46531. return null;
  46532. }
  46533. }
  46534. }
  46535. // PVRTC
  46536. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  46537. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  46538. if ( extension !== null ) {
  46539. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  46540. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  46541. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  46542. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  46543. } else {
  46544. return null;
  46545. }
  46546. }
  46547. // ETC
  46548. 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 ) {
  46549. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  46550. if ( extension !== null ) {
  46551. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  46552. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  46553. if ( p === R11_EAC_Format ) return extension.COMPRESSED_R11_EAC;
  46554. if ( p === SIGNED_R11_EAC_Format ) return extension.COMPRESSED_SIGNED_R11_EAC;
  46555. if ( p === RG11_EAC_Format ) return extension.COMPRESSED_RG11_EAC;
  46556. if ( p === SIGNED_RG11_EAC_Format ) return extension.COMPRESSED_SIGNED_RG11_EAC;
  46557. } else {
  46558. return null;
  46559. }
  46560. }
  46561. // ASTC
  46562. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  46563. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  46564. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  46565. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  46566. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  46567. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  46568. if ( extension !== null ) {
  46569. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  46570. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  46571. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  46572. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  46573. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  46574. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  46575. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  46576. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  46577. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  46578. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  46579. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  46580. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  46581. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  46582. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  46583. } else {
  46584. return null;
  46585. }
  46586. }
  46587. // BPTC
  46588. if ( p === RGBA_BPTC_Format ) {
  46589. extension = extensions.get( 'EXT_texture_compression_bptc' );
  46590. if ( extension !== null ) {
  46591. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  46592. } else {
  46593. return null;
  46594. }
  46595. }
  46596. // RGTC
  46597. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  46598. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  46599. if ( extension !== null ) {
  46600. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  46601. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  46602. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  46603. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  46604. } else {
  46605. return null;
  46606. }
  46607. }
  46608. //
  46609. if ( p === UnsignedInt248Type ) {
  46610. return gl.UNSIGNED_INT_24_8;
  46611. }
  46612. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  46613. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  46614. }
  46615. /**
  46616. * This method can be used to synchronize the CPU with the GPU by waiting until
  46617. * ongoing GPU commands have been completed.
  46618. *
  46619. * @private
  46620. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  46621. */
  46622. _clientWaitAsync() {
  46623. const { gl } = this;
  46624. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  46625. gl.flush();
  46626. return new Promise( ( resolve, reject ) => {
  46627. function test() {
  46628. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  46629. if ( res === gl.WAIT_FAILED ) {
  46630. gl.deleteSync( sync );
  46631. reject();
  46632. return;
  46633. }
  46634. if ( res === gl.TIMEOUT_EXPIRED ) {
  46635. requestAnimationFrame( test );
  46636. return;
  46637. }
  46638. gl.deleteSync( sync );
  46639. resolve();
  46640. }
  46641. test();
  46642. } );
  46643. }
  46644. }
  46645. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  46646. /**
  46647. * A WebGL 2 backend utility module for managing textures.
  46648. *
  46649. * @private
  46650. */
  46651. class WebGLTextureUtils {
  46652. /**
  46653. * Constructs a new utility object.
  46654. *
  46655. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46656. */
  46657. constructor( backend ) {
  46658. /**
  46659. * A reference to the WebGL 2 backend.
  46660. *
  46661. * @type {WebGLBackend}
  46662. */
  46663. this.backend = backend;
  46664. /**
  46665. * A reference to the rendering context.
  46666. *
  46667. * @type {WebGL2RenderingContext}
  46668. */
  46669. this.gl = backend.gl;
  46670. /**
  46671. * A reference to a backend module holding extension-related
  46672. * utility functions.
  46673. *
  46674. * @type {WebGLExtensions}
  46675. */
  46676. this.extensions = backend.extensions;
  46677. /**
  46678. * A dictionary for managing default textures. The key
  46679. * is the binding point (target), the value the WEbGL texture object.
  46680. *
  46681. * @type {Object<GLenum,WebGLTexture>}
  46682. */
  46683. this.defaultTextures = {};
  46684. /**
  46685. * A scratch framebuffer used for attaching the source texture in
  46686. * {@link copyTextureToTexture}.
  46687. *
  46688. * @private
  46689. * @type {?WebGLFramebuffer}
  46690. */
  46691. this._srcFramebuffer = null;
  46692. /**
  46693. * A scratch framebuffer used for attaching the destination texture in
  46694. * {@link copyTextureToTexture}.
  46695. *
  46696. * @private
  46697. * @type {?WebGLFramebuffer}
  46698. */
  46699. this._dstFramebuffer = null;
  46700. if ( initialized === false ) {
  46701. this._init();
  46702. initialized = true;
  46703. }
  46704. }
  46705. /**
  46706. * Inits the state of the utility.
  46707. *
  46708. * @private
  46709. */
  46710. _init() {
  46711. const gl = this.gl;
  46712. // Store only WebGL constants here.
  46713. wrappingToGL = {
  46714. [ RepeatWrapping ]: gl.REPEAT,
  46715. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  46716. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  46717. };
  46718. filterToGL = {
  46719. [ NearestFilter ]: gl.NEAREST,
  46720. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  46721. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  46722. [ LinearFilter ]: gl.LINEAR,
  46723. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  46724. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  46725. };
  46726. compareToGL = {
  46727. [ NeverCompare ]: gl.NEVER,
  46728. [ AlwaysCompare ]: gl.ALWAYS,
  46729. [ LessCompare ]: gl.LESS,
  46730. [ LessEqualCompare ]: gl.LEQUAL,
  46731. [ EqualCompare ]: gl.EQUAL,
  46732. [ GreaterEqualCompare ]: gl.GEQUAL,
  46733. [ GreaterCompare ]: gl.GREATER,
  46734. [ NotEqualCompare ]: gl.NOTEQUAL
  46735. };
  46736. }
  46737. /**
  46738. * Returns the native texture type for the given texture.
  46739. *
  46740. * @param {Texture} texture - The texture.
  46741. * @return {GLenum} The native texture type.
  46742. */
  46743. getGLTextureType( texture ) {
  46744. const { gl } = this;
  46745. let glTextureType;
  46746. if ( texture.isCubeTexture === true ) {
  46747. glTextureType = gl.TEXTURE_CUBE_MAP;
  46748. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  46749. glTextureType = gl.TEXTURE_2D_ARRAY;
  46750. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  46751. glTextureType = gl.TEXTURE_3D;
  46752. } else {
  46753. glTextureType = gl.TEXTURE_2D;
  46754. }
  46755. return glTextureType;
  46756. }
  46757. /**
  46758. * Returns the native texture type for the given texture.
  46759. *
  46760. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  46761. * @param {GLenum} glFormat - The WebGL format.
  46762. * @param {GLenum} glType - The WebGL type.
  46763. * @param {string} colorSpace - The texture's color space.
  46764. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  46765. * @return {GLenum} The internal format.
  46766. */
  46767. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  46768. const { gl, extensions } = this;
  46769. if ( internalFormatName !== null ) {
  46770. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  46771. warn( 'WebGLBackend: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  46772. }
  46773. let internalFormat = glFormat;
  46774. if ( glFormat === gl.RED ) {
  46775. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  46776. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  46777. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  46778. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  46779. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  46780. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  46781. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  46782. if ( glType === gl.INT ) internalFormat = gl.R32I;
  46783. }
  46784. if ( glFormat === gl.RED_INTEGER ) {
  46785. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  46786. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  46787. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  46788. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  46789. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  46790. if ( glType === gl.INT ) internalFormat = gl.R32I;
  46791. }
  46792. if ( glFormat === gl.RG ) {
  46793. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  46794. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  46795. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  46796. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  46797. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  46798. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  46799. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  46800. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  46801. }
  46802. if ( glFormat === gl.RG_INTEGER ) {
  46803. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  46804. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  46805. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  46806. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  46807. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  46808. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  46809. }
  46810. if ( glFormat === gl.RGB ) {
  46811. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  46812. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  46813. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  46814. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  46815. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  46816. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  46817. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  46818. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  46819. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  46820. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  46821. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  46822. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  46823. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  46824. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  46825. if ( glType === gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = gl.R11F_G11F_B10F;
  46826. }
  46827. if ( glFormat === gl.RGB_INTEGER ) {
  46828. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  46829. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  46830. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  46831. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  46832. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  46833. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  46834. }
  46835. if ( glFormat === gl.RGBA ) {
  46836. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  46837. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  46838. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  46839. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  46840. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  46841. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  46842. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  46843. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  46844. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  46845. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  46846. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  46847. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  46848. }
  46849. if ( glFormat === gl.RGBA_INTEGER ) {
  46850. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  46851. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  46852. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  46853. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  46854. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  46855. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  46856. }
  46857. if ( glFormat === gl.DEPTH_COMPONENT ) {
  46858. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  46859. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  46860. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  46861. }
  46862. if ( glFormat === gl.DEPTH_STENCIL ) {
  46863. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  46864. }
  46865. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  46866. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  46867. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  46868. extensions.get( 'EXT_color_buffer_float' );
  46869. }
  46870. return internalFormat;
  46871. }
  46872. /**
  46873. * Sets the texture parameters for the given texture.
  46874. *
  46875. * @param {GLenum} textureType - The texture type.
  46876. * @param {Texture} texture - The texture.
  46877. */
  46878. setTextureParameters( textureType, texture ) {
  46879. const { gl, extensions, backend } = this;
  46880. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  46881. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  46882. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  46883. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  46884. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  46885. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  46886. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  46887. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  46888. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  46889. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  46890. // WebGL 2 does not support wrapping for depth 2D array textures
  46891. if ( ! texture.isArrayTexture ) {
  46892. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  46893. }
  46894. }
  46895. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  46896. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  46897. // follow WebGPU backend mapping for texture filtering
  46898. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  46899. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  46900. if ( texture.compareFunction ) {
  46901. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  46902. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  46903. }
  46904. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  46905. if ( texture.magFilter === NearestFilter ) return;
  46906. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  46907. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  46908. if ( texture.anisotropy > 1 ) {
  46909. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  46910. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  46911. }
  46912. }
  46913. }
  46914. /**
  46915. * Creates a default texture for the given texture that can be used
  46916. * as a placeholder until the actual texture is ready for usage.
  46917. *
  46918. * @param {Texture} texture - The texture to create a default texture for.
  46919. */
  46920. createDefaultTexture( texture ) {
  46921. const { gl, backend, defaultTextures } = this;
  46922. const glTextureType = this.getGLTextureType( texture );
  46923. let textureGPU = defaultTextures[ glTextureType ];
  46924. if ( textureGPU === undefined ) {
  46925. textureGPU = gl.createTexture();
  46926. backend.state.bindTexture( glTextureType, textureGPU );
  46927. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  46928. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  46929. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  46930. defaultTextures[ glTextureType ] = textureGPU;
  46931. }
  46932. backend.set( texture, {
  46933. textureGPU,
  46934. glTextureType
  46935. } );
  46936. }
  46937. /**
  46938. * Defines a texture on the GPU for the given texture object.
  46939. *
  46940. * @param {Texture} texture - The texture.
  46941. * @param {Object} [options={}] - Optional configuration parameter.
  46942. * @return {undefined}
  46943. */
  46944. createTexture( texture, options ) {
  46945. const { gl, backend } = this;
  46946. const { levels, width, height, depth } = options;
  46947. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  46948. const glType = backend.utils.convert( texture.type );
  46949. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  46950. const textureGPU = gl.createTexture();
  46951. const glTextureType = this.getGLTextureType( texture );
  46952. backend.state.bindTexture( glTextureType, textureGPU );
  46953. this.setTextureParameters( glTextureType, texture );
  46954. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  46955. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  46956. } else if ( texture.isData3DTexture ) {
  46957. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  46958. } else if ( ! texture.isVideoTexture ) {
  46959. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  46960. }
  46961. backend.set( texture, {
  46962. textureGPU,
  46963. glTextureType,
  46964. glFormat,
  46965. glType,
  46966. glInternalFormat
  46967. } );
  46968. }
  46969. /**
  46970. * Uploads texture buffer data to the GPU memory.
  46971. *
  46972. * @param {WebGLBuffer} buffer - The buffer data.
  46973. * @param {Texture} texture - The texture,
  46974. */
  46975. copyBufferToTexture( buffer, texture ) {
  46976. const { gl, backend } = this;
  46977. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  46978. const { width, height } = texture.source.data;
  46979. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  46980. backend.state.bindTexture( glTextureType, textureGPU );
  46981. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  46982. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  46983. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  46984. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  46985. backend.state.unbindTexture();
  46986. // debug
  46987. // const framebuffer = gl.createFramebuffer();
  46988. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  46989. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  46990. // const readout = new Float32Array( width * height * 4 );
  46991. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  46992. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  46993. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  46994. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  46995. // log( readout );
  46996. }
  46997. /**
  46998. * Uploads the updated texture data to the GPU.
  46999. *
  47000. * @param {Texture} texture - The texture.
  47001. * @param {Object} [options={}] - Optional configuration parameter.
  47002. */
  47003. updateTexture( texture, options ) {
  47004. const { gl } = this;
  47005. const { width, height } = options;
  47006. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  47007. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  47008. return;
  47009. this.backend.state.bindTexture( glTextureType, textureGPU );
  47010. this.setTextureParameters( glTextureType, texture );
  47011. if ( texture.isCompressedTexture ) {
  47012. const mipmaps = texture.mipmaps;
  47013. const image = options.image;
  47014. for ( let i = 0; i < mipmaps.length; i ++ ) {
  47015. const mipmap = mipmaps[ i ];
  47016. if ( texture.isCompressedArrayTexture ) {
  47017. if ( texture.format !== gl.RGBA ) {
  47018. if ( glFormat !== null ) {
  47019. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  47020. } else {
  47021. warn( 'WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  47022. }
  47023. } else {
  47024. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  47025. }
  47026. } else {
  47027. if ( glFormat !== null ) {
  47028. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  47029. } else {
  47030. warn( 'WebGLBackend: Unsupported compressed texture format' );
  47031. }
  47032. }
  47033. }
  47034. } else if ( texture.isCubeTexture ) {
  47035. const images = options.images;
  47036. const mipmaps = texture.mipmaps;
  47037. for ( let i = 0; i < 6; i ++ ) {
  47038. const image = getImage( images[ i ] );
  47039. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  47040. for ( let j = 0; j < mipmaps.length; j ++ ) {
  47041. const mipmap = mipmaps[ j ];
  47042. const image = getImage( mipmap.images[ i ] );
  47043. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, image.width, image.height, glFormat, glType, image );
  47044. }
  47045. }
  47046. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  47047. const image = options.image;
  47048. if ( texture.layerUpdates.size > 0 ) {
  47049. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  47050. for ( const layerIndex of texture.layerUpdates ) {
  47051. const layerData = image.data.subarray(
  47052. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  47053. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  47054. );
  47055. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  47056. }
  47057. texture.clearLayerUpdates();
  47058. } else {
  47059. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  47060. }
  47061. } else if ( texture.isData3DTexture ) {
  47062. const image = options.image;
  47063. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  47064. } else if ( texture.isVideoTexture ) {
  47065. texture.update();
  47066. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  47067. } else {
  47068. const mipmaps = texture.mipmaps;
  47069. if ( mipmaps.length > 0 ) {
  47070. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  47071. const mipmap = mipmaps[ i ];
  47072. const image = getImage( mipmap );
  47073. gl.texSubImage2D( glTextureType, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, image );
  47074. }
  47075. } else {
  47076. const image = getImage( options.image );
  47077. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  47078. }
  47079. }
  47080. }
  47081. /**
  47082. * Generates mipmaps for the given texture.
  47083. *
  47084. * @param {Texture} texture - The texture.
  47085. */
  47086. generateMipmaps( texture ) {
  47087. const { gl, backend } = this;
  47088. const { textureGPU, glTextureType } = backend.get( texture );
  47089. backend.state.bindTexture( glTextureType, textureGPU );
  47090. gl.generateMipmap( glTextureType );
  47091. }
  47092. /**
  47093. * Deallocates the render buffers of the given render target.
  47094. *
  47095. * @param {RenderTarget} renderTarget - The render target.
  47096. */
  47097. deallocateRenderBuffers( renderTarget ) {
  47098. const { gl, backend } = this;
  47099. // remove framebuffer reference
  47100. if ( renderTarget ) {
  47101. const renderContextData = backend.get( renderTarget );
  47102. renderContextData.renderBufferStorageSetup = undefined;
  47103. if ( renderContextData.framebuffers ) {
  47104. for ( const cacheKey in renderContextData.framebuffers ) {
  47105. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  47106. }
  47107. delete renderContextData.framebuffers;
  47108. }
  47109. if ( renderContextData.depthRenderbuffer ) {
  47110. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  47111. delete renderContextData.depthRenderbuffer;
  47112. }
  47113. if ( renderContextData.stencilRenderbuffer ) {
  47114. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  47115. delete renderContextData.stencilRenderbuffer;
  47116. }
  47117. if ( renderContextData.msaaFrameBuffer ) {
  47118. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  47119. delete renderContextData.msaaFrameBuffer;
  47120. }
  47121. if ( renderContextData.msaaRenderbuffers ) {
  47122. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  47123. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  47124. }
  47125. delete renderContextData.msaaRenderbuffers;
  47126. }
  47127. }
  47128. }
  47129. /**
  47130. * Destroys the GPU data for the given texture object.
  47131. *
  47132. * @param {Texture} texture - The texture.
  47133. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  47134. */
  47135. destroyTexture( texture, isDefaultTexture = false ) {
  47136. const { gl, backend } = this;
  47137. const { textureGPU, renderTarget } = backend.get( texture );
  47138. this.deallocateRenderBuffers( renderTarget );
  47139. if ( isDefaultTexture === false ) {
  47140. gl.deleteTexture( textureGPU );
  47141. }
  47142. backend.delete( texture );
  47143. }
  47144. /**
  47145. * Copies data of the given source texture to the given destination texture.
  47146. *
  47147. * @param {Texture} srcTexture - The source texture.
  47148. * @param {Texture} dstTexture - The destination texture.
  47149. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  47150. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  47151. * @param {number} [srcLevel=0] - The source mip level to copy from.
  47152. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  47153. */
  47154. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  47155. const { gl, backend } = this;
  47156. const { state } = this.backend;
  47157. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  47158. state.bindTexture( glTextureType, dstTextureGPU );
  47159. // gather the necessary dimensions to copy
  47160. let width, height, depth, minX, minY, minZ;
  47161. let dstX, dstY, dstZ;
  47162. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  47163. if ( srcRegion !== null ) {
  47164. width = srcRegion.max.x - srcRegion.min.x;
  47165. height = srcRegion.max.y - srcRegion.min.y;
  47166. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  47167. minX = srcRegion.min.x;
  47168. minY = srcRegion.min.y;
  47169. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  47170. } else {
  47171. const levelScale = Math.pow( 2, - srcLevel );
  47172. width = Math.floor( image.width * levelScale );
  47173. height = Math.floor( image.height * levelScale );
  47174. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  47175. depth = image.depth;
  47176. } else if ( srcTexture.isData3DTexture ) {
  47177. depth = Math.floor( image.depth * levelScale );
  47178. } else {
  47179. depth = 1;
  47180. }
  47181. minX = 0;
  47182. minY = 0;
  47183. minZ = 0;
  47184. }
  47185. if ( dstPosition !== null ) {
  47186. dstX = dstPosition.x;
  47187. dstY = dstPosition.y;
  47188. dstZ = dstPosition.z;
  47189. } else {
  47190. dstX = 0;
  47191. dstY = 0;
  47192. dstZ = 0;
  47193. }
  47194. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  47195. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  47196. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  47197. // used for copying data from cpu
  47198. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  47199. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  47200. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  47201. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  47202. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  47203. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  47204. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  47205. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  47206. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  47207. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  47208. // set up the src texture
  47209. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture || dstTexture.isArrayTexture;
  47210. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  47211. if ( srcTexture.isDepthTexture ) {
  47212. const srcTextureData = backend.get( srcTexture );
  47213. const dstTextureData = backend.get( dstTexture );
  47214. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  47215. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  47216. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  47217. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  47218. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  47219. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  47220. for ( let i = 0; i < depth; i ++ ) {
  47221. // if the source or destination are a 3d target then a layer needs to be bound
  47222. if ( isSrc3D ) {
  47223. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  47224. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  47225. }
  47226. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST );
  47227. }
  47228. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  47229. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  47230. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || backend.has( srcTexture ) ) {
  47231. // get the appropriate frame buffers
  47232. const srcTextureData = backend.get( srcTexture );
  47233. if ( this._srcFramebuffer === null ) this._srcFramebuffer = gl.createFramebuffer();
  47234. if ( this._dstFramebuffer === null ) this._dstFramebuffer = gl.createFramebuffer();
  47235. // bind the frame buffer targets
  47236. state.bindFramebuffer( gl.READ_FRAMEBUFFER, this._srcFramebuffer );
  47237. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, this._dstFramebuffer );
  47238. for ( let i = 0; i < depth; i ++ ) {
  47239. // assign the correct layers and mip maps to the frame buffers
  47240. if ( isSrc3D ) {
  47241. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  47242. } else {
  47243. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, srcTextureData.textureGPU, srcLevel );
  47244. }
  47245. if ( isDst3D ) {
  47246. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  47247. } else {
  47248. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dstTextureGPU, dstLevel );
  47249. }
  47250. // copy the data using the fastest function that can achieve the copy
  47251. if ( srcLevel !== 0 ) {
  47252. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST );
  47253. } else if ( isDst3D ) {
  47254. gl.copyTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  47255. } else {
  47256. gl.copyTexSubImage2D( glTextureType, dstLevel, dstX, dstY, minX, minY, width, height );
  47257. }
  47258. }
  47259. // unbind read, draw buffers
  47260. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  47261. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  47262. } else {
  47263. if ( isDst3D ) {
  47264. // copy data into the 3d texture
  47265. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  47266. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  47267. } else if ( dstTexture.isCompressedArrayTexture ) {
  47268. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  47269. } else {
  47270. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  47271. }
  47272. } else {
  47273. // copy data into the 2d texture
  47274. if ( srcTexture.isDataTexture ) {
  47275. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  47276. } else if ( srcTexture.isCompressedTexture ) {
  47277. gl.compressedTexSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  47278. } else {
  47279. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  47280. }
  47281. }
  47282. }
  47283. // reset values
  47284. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  47285. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  47286. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  47287. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  47288. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  47289. // Generate mipmaps only when copying level 0
  47290. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  47291. gl.generateMipmap( glTextureType );
  47292. }
  47293. state.unbindTexture();
  47294. }
  47295. /**
  47296. * Copies the current bound framebuffer to the given texture.
  47297. *
  47298. * @param {Texture} texture - The destination texture.
  47299. * @param {RenderContext} renderContext - The render context.
  47300. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  47301. */
  47302. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  47303. const { gl } = this;
  47304. const { state } = this.backend;
  47305. const { textureGPU } = this.backend.get( texture );
  47306. const { x, y, z: width, w: height } = rectangle;
  47307. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  47308. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  47309. if ( requireDrawFrameBuffer ) {
  47310. const partial = ( x !== 0 || y !== 0 );
  47311. let mask;
  47312. let attachment;
  47313. if ( texture.isDepthTexture === true ) {
  47314. mask = gl.DEPTH_BUFFER_BIT;
  47315. attachment = gl.DEPTH_ATTACHMENT;
  47316. if ( renderContext.stencil ) {
  47317. mask |= gl.STENCIL_BUFFER_BIT;
  47318. }
  47319. } else {
  47320. mask = gl.COLOR_BUFFER_BIT;
  47321. attachment = gl.COLOR_ATTACHMENT0;
  47322. }
  47323. if ( partial ) {
  47324. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  47325. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  47326. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  47327. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  47328. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  47329. const flippedY = srcHeight - y - height;
  47330. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  47331. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  47332. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  47333. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  47334. state.unbindTexture();
  47335. } else {
  47336. const fb = gl.createFramebuffer();
  47337. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  47338. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  47339. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  47340. gl.deleteFramebuffer( fb );
  47341. }
  47342. } else {
  47343. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  47344. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  47345. state.unbindTexture();
  47346. }
  47347. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  47348. this.backend._setFramebuffer( renderContext );
  47349. }
  47350. /**
  47351. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  47352. *
  47353. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  47354. * @param {RenderContext} renderContext - The render context.
  47355. * @param {number} samples - The MSAA sample count.
  47356. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  47357. */
  47358. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  47359. const { gl } = this;
  47360. const renderTarget = renderContext.renderTarget;
  47361. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  47362. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  47363. if ( depthBuffer && ! stencilBuffer ) {
  47364. let glInternalFormat = gl.DEPTH_COMPONENT24;
  47365. if ( useMultisampledRTT === true ) {
  47366. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  47367. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  47368. } else if ( samples > 0 ) {
  47369. if ( depthTexture && depthTexture.isDepthTexture ) {
  47370. if ( depthTexture.type === gl.FLOAT ) {
  47371. glInternalFormat = gl.DEPTH_COMPONENT32F;
  47372. }
  47373. }
  47374. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  47375. } else {
  47376. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  47377. }
  47378. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  47379. } else if ( depthBuffer && stencilBuffer ) {
  47380. if ( samples > 0 ) {
  47381. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  47382. } else {
  47383. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  47384. }
  47385. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  47386. }
  47387. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  47388. }
  47389. /**
  47390. * Returns texture data as a typed array.
  47391. *
  47392. * @async
  47393. * @param {Texture} texture - The texture to copy.
  47394. * @param {number} x - The x coordinate of the copy origin.
  47395. * @param {number} y - The y coordinate of the copy origin.
  47396. * @param {number} width - The width of the copy.
  47397. * @param {number} height - The height of the copy.
  47398. * @param {number} faceIndex - The face index.
  47399. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47400. */
  47401. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  47402. const { backend, gl } = this;
  47403. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  47404. const fb = gl.createFramebuffer();
  47405. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  47406. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  47407. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  47408. const typedArrayType = this._getTypedArrayType( glType );
  47409. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  47410. const elementCount = width * height;
  47411. const byteLength = elementCount * bytesPerTexel;
  47412. const buffer = gl.createBuffer();
  47413. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  47414. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  47415. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  47416. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  47417. await backend.utils._clientWaitAsync();
  47418. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  47419. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  47420. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  47421. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  47422. gl.deleteFramebuffer( fb );
  47423. return dstBuffer;
  47424. }
  47425. /**
  47426. * Returns the corresponding typed array type for the given WebGL data type.
  47427. *
  47428. * @private
  47429. * @param {GLenum} glType - The WebGL data type.
  47430. * @return {TypedArray.constructor} The typed array type.
  47431. */
  47432. _getTypedArrayType( glType ) {
  47433. const { gl } = this;
  47434. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  47435. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  47436. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  47437. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  47438. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  47439. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  47440. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  47441. if ( glType === gl.FLOAT ) return Float32Array;
  47442. throw new Error( `Unsupported WebGL type: ${glType}` );
  47443. }
  47444. /**
  47445. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  47446. *
  47447. * @private
  47448. * @param {GLenum} glType - The WebGL data type.
  47449. * @param {GLenum} glFormat - The WebGL texture format.
  47450. * @return {number} The bytes-per-texel.
  47451. */
  47452. _getBytesPerTexel( glType, glFormat ) {
  47453. const { gl } = this;
  47454. let bytesPerComponent = 0;
  47455. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  47456. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  47457. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  47458. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  47459. glType === gl.UNSIGNED_SHORT ||
  47460. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  47461. if ( glType === gl.UNSIGNED_INT ||
  47462. glType === gl.FLOAT ) bytesPerComponent = 4;
  47463. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  47464. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  47465. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  47466. }
  47467. /**
  47468. * Frees the internal resources.
  47469. */
  47470. dispose() {
  47471. const { gl } = this;
  47472. if ( this._srcFramebuffer !== null ) gl.deleteFramebuffer( this._srcFramebuffer );
  47473. if ( this._dstFramebuffer !== null ) gl.deleteFramebuffer( this._dstFramebuffer );
  47474. }
  47475. }
  47476. function getImage( source ) {
  47477. if ( source.isDataTexture ) {
  47478. return source.image.data;
  47479. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  47480. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  47481. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  47482. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  47483. return source;
  47484. }
  47485. return source.data;
  47486. }
  47487. /**
  47488. * A WebGL 2 backend utility module for managing extensions.
  47489. *
  47490. * @private
  47491. */
  47492. class WebGLExtensions {
  47493. /**
  47494. * Constructs a new utility object.
  47495. *
  47496. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47497. */
  47498. constructor( backend ) {
  47499. /**
  47500. * A reference to the WebGL 2 backend.
  47501. *
  47502. * @type {WebGLBackend}
  47503. */
  47504. this.backend = backend;
  47505. /**
  47506. * A reference to the rendering context.
  47507. *
  47508. * @type {WebGL2RenderingContext}
  47509. */
  47510. this.gl = this.backend.gl;
  47511. /**
  47512. * A list with all the supported WebGL extensions.
  47513. *
  47514. * @type {Array<string>}
  47515. */
  47516. this.availableExtensions = this.gl.getSupportedExtensions();
  47517. /**
  47518. * A dictionary with requested WebGL extensions.
  47519. * The key is the name of the extension, the value
  47520. * the requested extension object.
  47521. *
  47522. * @type {Object<string,Object>}
  47523. */
  47524. this.extensions = {};
  47525. }
  47526. /**
  47527. * Returns the extension object for the given extension name.
  47528. *
  47529. * @param {string} name - The extension name.
  47530. * @return {Object} The extension object.
  47531. */
  47532. get( name ) {
  47533. let extension = this.extensions[ name ];
  47534. if ( extension === undefined ) {
  47535. extension = this.gl.getExtension( name );
  47536. this.extensions[ name ] = extension;
  47537. }
  47538. return extension;
  47539. }
  47540. /**
  47541. * Returns `true` if the requested extension is available.
  47542. *
  47543. * @param {string} name - The extension name.
  47544. * @return {boolean} Whether the given extension is available or not.
  47545. */
  47546. has( name ) {
  47547. return this.availableExtensions.includes( name );
  47548. }
  47549. }
  47550. /**
  47551. * A WebGL 2 backend utility module for managing the device's capabilities.
  47552. *
  47553. * @private
  47554. */
  47555. class WebGLCapabilities {
  47556. /**
  47557. * Constructs a new utility object.
  47558. *
  47559. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47560. */
  47561. constructor( backend ) {
  47562. /**
  47563. * A reference to the WebGL 2 backend.
  47564. *
  47565. * @type {WebGLBackend}
  47566. */
  47567. this.backend = backend;
  47568. /**
  47569. * This value holds the cached max anisotropy value.
  47570. *
  47571. * @type {?number}
  47572. * @default null
  47573. */
  47574. this.maxAnisotropy = null;
  47575. }
  47576. /**
  47577. * Returns the maximum anisotropy texture filtering value. This value
  47578. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  47579. * WebGL extension.
  47580. *
  47581. * @return {number} The maximum anisotropy texture filtering value.
  47582. */
  47583. getMaxAnisotropy() {
  47584. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  47585. const gl = this.backend.gl;
  47586. const extensions = this.backend.extensions;
  47587. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  47588. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  47589. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  47590. } else {
  47591. this.maxAnisotropy = 0;
  47592. }
  47593. return this.maxAnisotropy;
  47594. }
  47595. }
  47596. const GLFeatureName = {
  47597. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  47598. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  47599. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  47600. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  47601. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  47602. 'WEBGL_compressed_texture_s3tc': 'texture-compression-s3tc',
  47603. 'EXT_texture_compression_bptc': 'texture-compression-bc',
  47604. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  47605. 'OVR_multiview2': 'OVR_multiview2'
  47606. };
  47607. class WebGLBufferRenderer {
  47608. constructor( backend ) {
  47609. this.gl = backend.gl;
  47610. this.extensions = backend.extensions;
  47611. this.info = backend.renderer.info;
  47612. this.mode = null;
  47613. this.index = 0;
  47614. this.type = null;
  47615. this.object = null;
  47616. }
  47617. render( start, count ) {
  47618. const { gl, mode, object, type, info, index } = this;
  47619. if ( index !== 0 ) {
  47620. gl.drawElements( mode, count, type, start );
  47621. } else {
  47622. gl.drawArrays( mode, start, count );
  47623. }
  47624. info.update( object, count, 1 );
  47625. }
  47626. renderInstances( start, count, primcount ) {
  47627. const { gl, mode, type, index, object, info } = this;
  47628. if ( primcount === 0 ) return;
  47629. if ( index !== 0 ) {
  47630. gl.drawElementsInstanced( mode, count, type, start, primcount );
  47631. } else {
  47632. gl.drawArraysInstanced( mode, start, count, primcount );
  47633. }
  47634. info.update( object, count, primcount );
  47635. }
  47636. renderMultiDraw( starts, counts, drawCount ) {
  47637. const { extensions, mode, object, info } = this;
  47638. if ( drawCount === 0 ) return;
  47639. const extension = extensions.get( 'WEBGL_multi_draw' );
  47640. if ( extension === null ) {
  47641. for ( let i = 0; i < drawCount; i ++ ) {
  47642. this.render( starts[ i ], counts[ i ] );
  47643. }
  47644. } else {
  47645. if ( this.index !== 0 ) {
  47646. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  47647. } else {
  47648. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  47649. }
  47650. let elementCount = 0;
  47651. for ( let i = 0; i < drawCount; i ++ ) {
  47652. elementCount += counts[ i ];
  47653. }
  47654. info.update( object, elementCount, 1 );
  47655. }
  47656. }
  47657. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  47658. const { extensions, mode, object, info } = this;
  47659. if ( drawCount === 0 ) return;
  47660. const extension = extensions.get( 'WEBGL_multi_draw' );
  47661. if ( extension === null ) {
  47662. for ( let i = 0; i < drawCount; i ++ ) {
  47663. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  47664. }
  47665. } else {
  47666. if ( this.index !== 0 ) {
  47667. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  47668. } else {
  47669. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  47670. }
  47671. let elementCount = 0;
  47672. for ( let i = 0; i < drawCount; i ++ ) {
  47673. elementCount += counts[ i ] * primcount[ i ];
  47674. }
  47675. info.update( object, elementCount, 1 );
  47676. }
  47677. }
  47678. //
  47679. }
  47680. /**
  47681. * Abstract base class of a timestamp query pool.
  47682. *
  47683. * @abstract
  47684. */
  47685. class TimestampQueryPool {
  47686. /**
  47687. * Creates a new timestamp query pool.
  47688. *
  47689. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  47690. */
  47691. constructor( maxQueries = 256 ) {
  47692. /**
  47693. * Whether to track timestamps or not.
  47694. *
  47695. * @type {boolean}
  47696. * @default true
  47697. */
  47698. this.trackTimestamp = true;
  47699. /**
  47700. * Maximum number of queries this pool can hold.
  47701. *
  47702. * @type {number}
  47703. * @default 256
  47704. */
  47705. this.maxQueries = maxQueries;
  47706. /**
  47707. * How many queries allocated so far.
  47708. *
  47709. * @type {number}
  47710. * @default 0
  47711. */
  47712. this.currentQueryIndex = 0;
  47713. /**
  47714. * Tracks offsets for different contexts.
  47715. *
  47716. * @type {Map<string, number>}
  47717. */
  47718. this.queryOffsets = new Map();
  47719. /**
  47720. * Whether the pool has been disposed or not.
  47721. *
  47722. * @type {boolean}
  47723. * @default false
  47724. */
  47725. this.isDisposed = false;
  47726. /**
  47727. * TODO
  47728. *
  47729. * @type {number}
  47730. * @default 0
  47731. */
  47732. this.lastValue = 0;
  47733. /**
  47734. * Stores all timestamp frames.
  47735. *
  47736. * @type {Array<number>}
  47737. */
  47738. this.frames = [];
  47739. /**
  47740. * TODO
  47741. *
  47742. * @type {boolean}
  47743. * @default false
  47744. */
  47745. this.pendingResolve = false;
  47746. /**
  47747. * Stores the latest timestamp for each render context.
  47748. *
  47749. * @type {Map<string, number>}
  47750. */
  47751. this.timestamps = new Map();
  47752. }
  47753. /**
  47754. * Returns all timestamp frames.
  47755. *
  47756. * @return {Array<number>} The timestamp frames.
  47757. */
  47758. getTimestampFrames() {
  47759. return this.frames;
  47760. }
  47761. /**
  47762. * Returns the timestamp for a given render context.
  47763. *
  47764. * @param {string} uid - A unique identifier for the render context.
  47765. * @return {?number} The timestamp, or undefined if not available.
  47766. */
  47767. getTimestamp( uid ) {
  47768. let timestamp = this.timestamps.get( uid );
  47769. if ( timestamp === undefined ) {
  47770. warn( `TimestampQueryPool: No timestamp available for uid ${ uid }.` );
  47771. timestamp = 0;
  47772. }
  47773. return timestamp;
  47774. }
  47775. /**
  47776. * Returns whether a timestamp is available for a given render context.
  47777. *
  47778. * @param {string} uid - A unique identifier for the render context.
  47779. * @return {boolean} True if a timestamp is available, false otherwise.
  47780. */
  47781. hasTimestamp( uid ) {
  47782. return this.timestamps.has( uid );
  47783. }
  47784. /**
  47785. * Allocate queries for a specific uid.
  47786. *
  47787. * @abstract
  47788. * @param {string} uid - A unique identifier for the render context.
  47789. * @param {number} frameId - The current frame identifier.
  47790. * @returns {?number}
  47791. */
  47792. allocateQueriesForContext( /* uid, frameId */ ) {}
  47793. /**
  47794. * Resolve all timestamps and return data (or process them).
  47795. *
  47796. * @abstract
  47797. * @async
  47798. * @returns {Promise<number>|number} The resolved timestamp value.
  47799. */
  47800. async resolveQueriesAsync() {}
  47801. /**
  47802. * Dispose of the query pool.
  47803. *
  47804. * @abstract
  47805. */
  47806. dispose() {}
  47807. }
  47808. /**
  47809. * Manages a pool of WebGL timestamp queries for performance measurement.
  47810. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  47811. *
  47812. * @augments TimestampQueryPool
  47813. */
  47814. class WebGLTimestampQueryPool extends TimestampQueryPool {
  47815. /**
  47816. * Creates a new WebGL timestamp query pool.
  47817. *
  47818. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  47819. * @param {string} type - The type identifier for this query pool.
  47820. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  47821. */
  47822. constructor( gl, type, maxQueries = 2048 ) {
  47823. super( maxQueries );
  47824. this.gl = gl;
  47825. this.type = type;
  47826. // Check for timer query extensions
  47827. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  47828. gl.getExtension( 'EXT_disjoint_timer_query' );
  47829. if ( ! this.ext ) {
  47830. warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  47831. this.trackTimestamp = false;
  47832. return;
  47833. }
  47834. // Create query objects
  47835. this.queries = [];
  47836. for ( let i = 0; i < this.maxQueries; i ++ ) {
  47837. this.queries.push( gl.createQuery() );
  47838. }
  47839. this.activeQuery = null;
  47840. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  47841. }
  47842. /**
  47843. * Allocates a pair of queries for a given render context.
  47844. *
  47845. * @param {string} uid - A unique identifier for the render context.
  47846. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  47847. */
  47848. allocateQueriesForContext( uid ) {
  47849. if ( ! this.trackTimestamp ) return null;
  47850. // Check if we have enough space for a new query pair
  47851. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  47852. 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() } ).` );
  47853. return null;
  47854. }
  47855. const baseOffset = this.currentQueryIndex;
  47856. this.currentQueryIndex += 2;
  47857. // Initialize query states
  47858. this.queryStates.set( baseOffset, 'inactive' );
  47859. this.queryOffsets.set( uid, baseOffset );
  47860. return baseOffset;
  47861. }
  47862. /**
  47863. * Begins a timestamp query for the specified render context.
  47864. *
  47865. * @param {string} uid - A unique identifier for the render context.
  47866. */
  47867. beginQuery( uid ) {
  47868. if ( ! this.trackTimestamp || this.isDisposed ) {
  47869. return;
  47870. }
  47871. const baseOffset = this.queryOffsets.get( uid );
  47872. if ( baseOffset == null ) {
  47873. return;
  47874. }
  47875. // Don't start a new query if there's an active one
  47876. if ( this.activeQuery !== null ) {
  47877. return;
  47878. }
  47879. const query = this.queries[ baseOffset ];
  47880. if ( ! query ) {
  47881. return;
  47882. }
  47883. try {
  47884. // Only begin if query is inactive
  47885. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  47886. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  47887. this.activeQuery = baseOffset;
  47888. this.queryStates.set( baseOffset, 'started' );
  47889. }
  47890. } catch ( e ) {
  47891. error( 'Error in beginQuery:', e );
  47892. this.activeQuery = null;
  47893. this.queryStates.set( baseOffset, 'inactive' );
  47894. }
  47895. }
  47896. /**
  47897. * Ends the active timestamp query for the specified render context.
  47898. *
  47899. * @param {string} uid - A unique identifier for the render context.
  47900. */
  47901. endQuery( uid ) {
  47902. if ( ! this.trackTimestamp || this.isDisposed ) {
  47903. return;
  47904. }
  47905. const baseOffset = this.queryOffsets.get( uid );
  47906. if ( baseOffset == null ) {
  47907. return;
  47908. }
  47909. // Only end if this is the active query
  47910. if ( this.activeQuery !== baseOffset ) {
  47911. return;
  47912. }
  47913. try {
  47914. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  47915. this.queryStates.set( baseOffset, 'ended' );
  47916. this.activeQuery = null;
  47917. } catch ( e ) {
  47918. error( 'Error in endQuery:', e );
  47919. // Reset state on error
  47920. this.queryStates.set( baseOffset, 'inactive' );
  47921. this.activeQuery = null;
  47922. }
  47923. }
  47924. /**
  47925. * Asynchronously resolves all completed queries and returns the total duration.
  47926. *
  47927. * @async
  47928. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  47929. */
  47930. async resolveQueriesAsync() {
  47931. if ( ! this.trackTimestamp || this.pendingResolve ) {
  47932. return this.lastValue;
  47933. }
  47934. this.pendingResolve = true;
  47935. try {
  47936. // Wait for all ended queries to complete
  47937. const resolvePromises = new Map();
  47938. for ( const [ uid, baseOffset ] of this.queryOffsets ) {
  47939. const state = this.queryStates.get( baseOffset );
  47940. if ( state === 'ended' ) {
  47941. const query = this.queries[ baseOffset ];
  47942. resolvePromises.set( uid, this.resolveQuery( query ) );
  47943. }
  47944. }
  47945. if ( resolvePromises.size === 0 ) {
  47946. return this.lastValue;
  47947. }
  47948. //
  47949. const framesDuration = {};
  47950. const frames = [];
  47951. for ( const [ uid, promise ] of resolvePromises ) {
  47952. const match = uid.match( /^(.*):f(\d+)$/ );
  47953. const frame = parseInt( match[ 2 ] );
  47954. if ( frames.includes( frame ) === false ) {
  47955. frames.push( frame );
  47956. }
  47957. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  47958. const duration = await promise;
  47959. this.timestamps.set( uid, duration );
  47960. framesDuration[ frame ] += duration;
  47961. }
  47962. // Return the total duration of the last frame
  47963. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  47964. // Store the last valid result
  47965. this.lastValue = totalDuration;
  47966. this.frames = frames;
  47967. // Reset states
  47968. this.currentQueryIndex = 0;
  47969. this.queryOffsets.clear();
  47970. this.queryStates.clear();
  47971. this.activeQuery = null;
  47972. return totalDuration;
  47973. } catch ( e ) {
  47974. error( 'Error resolving queries:', e );
  47975. return this.lastValue;
  47976. } finally {
  47977. this.pendingResolve = false;
  47978. }
  47979. }
  47980. /**
  47981. * Resolves a single query, checking for completion and disjoint operation.
  47982. *
  47983. * @async
  47984. * @param {WebGLQuery} query - The query object to resolve.
  47985. * @returns {Promise<number>} The elapsed time in milliseconds.
  47986. */
  47987. async resolveQuery( query ) {
  47988. return new Promise( ( resolve ) => {
  47989. if ( this.isDisposed ) {
  47990. resolve( this.lastValue );
  47991. return;
  47992. }
  47993. let timeoutId;
  47994. let isResolved = false;
  47995. const cleanup = () => {
  47996. if ( timeoutId ) {
  47997. clearTimeout( timeoutId );
  47998. timeoutId = null;
  47999. }
  48000. };
  48001. const finalizeResolution = ( value ) => {
  48002. if ( ! isResolved ) {
  48003. isResolved = true;
  48004. cleanup();
  48005. resolve( value );
  48006. }
  48007. };
  48008. const checkQuery = () => {
  48009. if ( this.isDisposed ) {
  48010. finalizeResolution( this.lastValue );
  48011. return;
  48012. }
  48013. try {
  48014. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  48015. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  48016. if ( disjoint ) {
  48017. finalizeResolution( this.lastValue );
  48018. return;
  48019. }
  48020. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  48021. if ( ! available ) {
  48022. timeoutId = setTimeout( checkQuery, 1 );
  48023. return;
  48024. }
  48025. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  48026. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  48027. } catch ( e ) {
  48028. error( 'Error checking query:', e );
  48029. resolve( this.lastValue );
  48030. }
  48031. };
  48032. checkQuery();
  48033. } );
  48034. }
  48035. /**
  48036. * Releases all resources held by this query pool.
  48037. * This includes deleting all query objects and clearing internal state.
  48038. */
  48039. dispose() {
  48040. if ( this.isDisposed ) {
  48041. return;
  48042. }
  48043. this.isDisposed = true;
  48044. if ( ! this.trackTimestamp ) return;
  48045. for ( const query of this.queries ) {
  48046. this.gl.deleteQuery( query );
  48047. }
  48048. this.queries = [];
  48049. this.queryStates.clear();
  48050. this.queryOffsets.clear();
  48051. this.lastValue = 0;
  48052. this.activeQuery = null;
  48053. }
  48054. }
  48055. /**
  48056. * A backend implementation targeting WebGL 2.
  48057. *
  48058. * @private
  48059. * @augments Backend
  48060. */
  48061. class WebGLBackend extends Backend {
  48062. /**
  48063. * WebGLBackend options.
  48064. *
  48065. * @typedef {Object} WebGLBackend~Options
  48066. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  48067. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  48068. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  48069. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  48070. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  48071. * @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.
  48072. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  48073. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  48074. */
  48075. /**
  48076. * Constructs a new WebGPU backend.
  48077. *
  48078. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  48079. */
  48080. constructor( parameters = {} ) {
  48081. super( parameters );
  48082. /**
  48083. * This flag can be used for type testing.
  48084. *
  48085. * @type {boolean}
  48086. * @readonly
  48087. * @default true
  48088. */
  48089. this.isWebGLBackend = true;
  48090. /**
  48091. * A reference to a backend module holding shader attribute-related
  48092. * utility functions.
  48093. *
  48094. * @type {?WebGLAttributeUtils}
  48095. * @default null
  48096. */
  48097. this.attributeUtils = null;
  48098. /**
  48099. * A reference to a backend module holding extension-related
  48100. * utility functions.
  48101. *
  48102. * @type {?WebGLExtensions}
  48103. * @default null
  48104. */
  48105. this.extensions = null;
  48106. /**
  48107. * A reference to a backend module holding capability-related
  48108. * utility functions.
  48109. *
  48110. * @type {?WebGLCapabilities}
  48111. * @default null
  48112. */
  48113. this.capabilities = null;
  48114. /**
  48115. * A reference to a backend module holding texture-related
  48116. * utility functions.
  48117. *
  48118. * @type {?WebGLTextureUtils}
  48119. * @default null
  48120. */
  48121. this.textureUtils = null;
  48122. /**
  48123. * A reference to a backend module holding renderer-related
  48124. * utility functions.
  48125. *
  48126. * @type {?WebGLBufferRenderer}
  48127. * @default null
  48128. */
  48129. this.bufferRenderer = null;
  48130. /**
  48131. * A reference to the rendering context.
  48132. *
  48133. * @type {?WebGL2RenderingContext}
  48134. * @default null
  48135. */
  48136. this.gl = null;
  48137. /**
  48138. * A reference to a backend module holding state-related
  48139. * utility functions.
  48140. *
  48141. * @type {?WebGLState}
  48142. * @default null
  48143. */
  48144. this.state = null;
  48145. /**
  48146. * A reference to a backend module holding common
  48147. * utility functions.
  48148. *
  48149. * @type {?WebGLUtils}
  48150. * @default null
  48151. */
  48152. this.utils = null;
  48153. /**
  48154. * Dictionary for caching VAOs.
  48155. *
  48156. * @type {Object<string,WebGLVertexArrayObject>}
  48157. */
  48158. this.vaoCache = {};
  48159. /**
  48160. * Dictionary for caching transform feedback objects.
  48161. *
  48162. * @type {Object<string,WebGLTransformFeedback>}
  48163. */
  48164. this.transformFeedbackCache = {};
  48165. /**
  48166. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  48167. * Only relevant when using compute shaders.
  48168. *
  48169. * @type {boolean}
  48170. * @default false
  48171. */
  48172. this.discard = false;
  48173. /**
  48174. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  48175. * device does not support the extension.
  48176. *
  48177. * @type {?EXTDisjointTimerQueryWebGL2}
  48178. * @default null
  48179. */
  48180. this.disjoint = null;
  48181. /**
  48182. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  48183. * device does not support the extension.
  48184. *
  48185. * @type {?KHRParallelShaderCompile}
  48186. * @default null
  48187. */
  48188. this.parallel = null;
  48189. /**
  48190. * A reference to the current render context.
  48191. *
  48192. * @private
  48193. * @type {RenderContext}
  48194. * @default null
  48195. */
  48196. this._currentContext = null;
  48197. /**
  48198. * A unique collection of bindings.
  48199. *
  48200. * @private
  48201. * @type {WeakSet<Array<BindGroup>>}
  48202. */
  48203. this._knownBindings = new WeakSet();
  48204. /**
  48205. * Whether the device supports framebuffers invalidation or not.
  48206. *
  48207. * @private
  48208. * @type {boolean}
  48209. */
  48210. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  48211. /**
  48212. * The target framebuffer when rendering with
  48213. * the WebXR device API.
  48214. *
  48215. * @private
  48216. * @type {?WebGLFramebuffer}
  48217. * @default null
  48218. */
  48219. this._xrFramebuffer = null;
  48220. }
  48221. /**
  48222. * Initializes the backend so it is ready for usage.
  48223. *
  48224. * @param {Renderer} renderer - The renderer.
  48225. */
  48226. init( renderer ) {
  48227. super.init( renderer );
  48228. //
  48229. const parameters = this.parameters;
  48230. const contextAttributes = {
  48231. antialias: renderer.currentSamples > 0,
  48232. alpha: true, // always true for performance reasons
  48233. depth: renderer.depth,
  48234. stencil: renderer.stencil
  48235. };
  48236. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  48237. function onContextLost( event ) {
  48238. event.preventDefault();
  48239. const contextLossInfo = {
  48240. api: 'WebGL',
  48241. message: event.statusMessage || 'Unknown reason',
  48242. reason: null,
  48243. originalEvent: event
  48244. };
  48245. renderer.onDeviceLost( contextLossInfo );
  48246. }
  48247. this._onContextLost = onContextLost;
  48248. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  48249. this.gl = glContext;
  48250. this.extensions = new WebGLExtensions( this );
  48251. this.capabilities = new WebGLCapabilities( this );
  48252. this.attributeUtils = new WebGLAttributeUtils( this );
  48253. this.textureUtils = new WebGLTextureUtils( this );
  48254. this.bufferRenderer = new WebGLBufferRenderer( this );
  48255. this.state = new WebGLState( this );
  48256. this.utils = new WebGLUtils( this );
  48257. this.extensions.get( 'EXT_color_buffer_float' );
  48258. this.extensions.get( 'WEBGL_clip_cull_distance' );
  48259. this.extensions.get( 'OES_texture_float_linear' );
  48260. this.extensions.get( 'EXT_color_buffer_half_float' );
  48261. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  48262. this.extensions.get( 'WEBGL_render_shared_exponent' );
  48263. this.extensions.get( 'WEBGL_multi_draw' );
  48264. this.extensions.get( 'OVR_multiview2' );
  48265. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  48266. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  48267. this.drawBuffersIndexedExt = this.extensions.get( 'OES_draw_buffers_indexed' );
  48268. }
  48269. /**
  48270. * The coordinate system of the backend.
  48271. *
  48272. * @type {number}
  48273. * @readonly
  48274. */
  48275. get coordinateSystem() {
  48276. return WebGLCoordinateSystem;
  48277. }
  48278. /**
  48279. * This method performs a readback operation by moving buffer data from
  48280. * a storage buffer attribute from the GPU to the CPU.
  48281. *
  48282. * @async
  48283. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  48284. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  48285. */
  48286. async getArrayBufferAsync( attribute ) {
  48287. return await this.attributeUtils.getArrayBufferAsync( attribute );
  48288. }
  48289. /**
  48290. * Ensures the backend is XR compatible.
  48291. *
  48292. * @async
  48293. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  48294. */
  48295. async makeXRCompatible() {
  48296. const attributes = this.gl.getContextAttributes();
  48297. if ( attributes.xrCompatible !== true ) {
  48298. await this.gl.makeXRCompatible();
  48299. }
  48300. }
  48301. /**
  48302. * Sets the XR rendering destination.
  48303. *
  48304. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  48305. */
  48306. setXRTarget( xrFramebuffer ) {
  48307. this._xrFramebuffer = xrFramebuffer;
  48308. }
  48309. /**
  48310. * Configures the given XR render target with external textures.
  48311. *
  48312. * This method is only relevant when using the WebXR Layers API.
  48313. *
  48314. * @param {XRRenderTarget} renderTarget - The XR render target.
  48315. * @param {WebGLTexture} colorTexture - A native color texture.
  48316. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  48317. */
  48318. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  48319. const gl = this.gl;
  48320. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  48321. if ( depthTexture !== null ) {
  48322. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  48323. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  48324. // The multisample_render_to_texture extension doesn't work properly if there
  48325. // are midframe flushes and an external depth texture.
  48326. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  48327. warn( 'WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  48328. }
  48329. renderTarget._autoAllocateDepthBuffer = false;
  48330. }
  48331. }
  48332. /**
  48333. * Inits a time stamp query for the given render context.
  48334. *
  48335. * @param {string} type - The type of the timestamp query.
  48336. * @param {string} uid - A unique identifier for the timestamp query.
  48337. */
  48338. initTimestampQuery( type, uid ) {
  48339. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  48340. if ( ! this.timestampQueryPool[ type ] ) {
  48341. // TODO: Variable maxQueries?
  48342. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  48343. }
  48344. const timestampQueryPool = this.timestampQueryPool[ type ];
  48345. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  48346. if ( baseOffset !== null ) {
  48347. timestampQueryPool.beginQuery( uid );
  48348. }
  48349. }
  48350. // timestamp utils
  48351. /**
  48352. * Prepares the timestamp buffer.
  48353. *
  48354. * @param {string} type - The type of the timestamp query.
  48355. * @param {string} uid - A unique identifier for the timestamp query.
  48356. */
  48357. prepareTimestampBuffer( type, uid ) {
  48358. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  48359. const timestampQueryPool = this.timestampQueryPool[ type ];
  48360. timestampQueryPool.endQuery( uid );
  48361. }
  48362. /**
  48363. * Returns the backend's rendering context.
  48364. *
  48365. * @return {WebGL2RenderingContext} The rendering context.
  48366. */
  48367. getContext() {
  48368. return this.gl;
  48369. }
  48370. /**
  48371. * This method is executed at the beginning of a render call and prepares
  48372. * the WebGL state for upcoming render calls
  48373. *
  48374. * @param {RenderContext} renderContext - The render context.
  48375. */
  48376. beginRender( renderContext ) {
  48377. const { state } = this;
  48378. const renderContextData = this.get( renderContext );
  48379. //
  48380. if ( renderContext.viewport ) {
  48381. this.updateViewport( renderContext );
  48382. } else {
  48383. const { width, height } = this.getDrawingBufferSize();
  48384. state.viewport( 0, 0, width, height );
  48385. }
  48386. if ( renderContext.scissor ) {
  48387. const { x, y, width, height } = renderContext.scissorValue;
  48388. state.scissor( x, renderContext.height - height - y, width, height );
  48389. }
  48390. //
  48391. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  48392. renderContextData.previousContext = this._currentContext;
  48393. this._currentContext = renderContext;
  48394. this._setFramebuffer( renderContext );
  48395. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  48396. const occlusionQueryCount = renderContext.occlusionQueryCount;
  48397. if ( occlusionQueryCount > 0 ) {
  48398. // Get a reference to the array of objects with queries. The renderContextData property
  48399. // can be changed by another render pass before the async reading of all previous queries complete
  48400. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  48401. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  48402. renderContextData.lastOcclusionObject = null;
  48403. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  48404. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  48405. renderContextData.occlusionQueryIndex = 0;
  48406. }
  48407. }
  48408. /**
  48409. * This method is executed at the end of a render call and finalizes work
  48410. * after draw calls.
  48411. *
  48412. * @param {RenderContext} renderContext - The render context.
  48413. */
  48414. finishRender( renderContext ) {
  48415. const { gl, state } = this;
  48416. const renderContextData = this.get( renderContext );
  48417. const previousContext = renderContextData.previousContext;
  48418. state.resetVertexState();
  48419. const occlusionQueryCount = renderContext.occlusionQueryCount;
  48420. if ( occlusionQueryCount > 0 ) {
  48421. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  48422. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  48423. }
  48424. this.resolveOccludedAsync( renderContext );
  48425. }
  48426. const textures = renderContext.textures;
  48427. if ( textures !== null ) {
  48428. for ( let i = 0; i < textures.length; i ++ ) {
  48429. const texture = textures[ i ];
  48430. if ( texture.generateMipmaps ) {
  48431. this.generateMipmaps( texture );
  48432. }
  48433. }
  48434. }
  48435. this._currentContext = previousContext;
  48436. this._resolveRenderTarget( renderContext );
  48437. if ( previousContext !== null ) {
  48438. this._setFramebuffer( previousContext );
  48439. if ( previousContext.viewport ) {
  48440. this.updateViewport( previousContext );
  48441. } else {
  48442. const { width, height } = this.getDrawingBufferSize();
  48443. state.viewport( 0, 0, width, height );
  48444. }
  48445. }
  48446. this.prepareTimestampBuffer( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  48447. }
  48448. /**
  48449. * This method processes the result of occlusion queries and writes it
  48450. * into render context data.
  48451. *
  48452. * @async
  48453. * @param {RenderContext} renderContext - The render context.
  48454. */
  48455. resolveOccludedAsync( renderContext ) {
  48456. const renderContextData = this.get( renderContext );
  48457. // handle occlusion query results
  48458. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  48459. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  48460. const occluded = new WeakSet();
  48461. const { gl } = this;
  48462. renderContextData.currentOcclusionQueryObjects = null;
  48463. renderContextData.currentOcclusionQueries = null;
  48464. const check = () => {
  48465. let completed = 0;
  48466. // check all queries and requeue as appropriate
  48467. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  48468. const query = currentOcclusionQueries[ i ];
  48469. if ( query === null ) continue;
  48470. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  48471. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  48472. currentOcclusionQueries[ i ] = null;
  48473. gl.deleteQuery( query );
  48474. completed ++;
  48475. }
  48476. }
  48477. if ( completed < currentOcclusionQueries.length ) {
  48478. requestAnimationFrame( check );
  48479. } else {
  48480. renderContextData.occluded = occluded;
  48481. }
  48482. };
  48483. check();
  48484. }
  48485. }
  48486. /**
  48487. * Returns `true` if the given 3D object is fully occluded by other
  48488. * 3D objects in the scene.
  48489. *
  48490. * @param {RenderContext} renderContext - The render context.
  48491. * @param {Object3D} object - The 3D object to test.
  48492. * @return {boolean} Whether the 3D object is fully occluded or not.
  48493. */
  48494. isOccluded( renderContext, object ) {
  48495. const renderContextData = this.get( renderContext );
  48496. return renderContextData.occluded && renderContextData.occluded.has( object );
  48497. }
  48498. /**
  48499. * Updates the viewport with the values from the given render context.
  48500. *
  48501. * @param {RenderContext} renderContext - The render context.
  48502. */
  48503. updateViewport( renderContext ) {
  48504. const { state } = this;
  48505. const { x, y, width, height } = renderContext.viewportValue;
  48506. state.viewport( x, renderContext.height - height - y, width, height );
  48507. }
  48508. /**
  48509. * Defines the scissor test.
  48510. *
  48511. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  48512. */
  48513. setScissorTest( boolean ) {
  48514. const state = this.state;
  48515. state.setScissorTest( boolean );
  48516. }
  48517. /**
  48518. * Returns the clear color and alpha into a single
  48519. * color object.
  48520. *
  48521. * @return {Color4} The clear color.
  48522. */
  48523. getClearColor() {
  48524. const clearColor = super.getClearColor();
  48525. // Since the canvas is always created with alpha: true,
  48526. // WebGL must always premultiply the clear color.
  48527. clearColor.r *= clearColor.a;
  48528. clearColor.g *= clearColor.a;
  48529. clearColor.b *= clearColor.a;
  48530. return clearColor;
  48531. }
  48532. /**
  48533. * Performs a clear operation.
  48534. *
  48535. * @param {boolean} color - Whether the color buffer should be cleared or not.
  48536. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  48537. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  48538. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  48539. * @param {boolean} [setFrameBuffer=true] - Controls whether the intermediate framebuffer should be set or not.
  48540. * @param {boolean} [resolveRenderTarget=true] - Controls whether an active render target should be resolved
  48541. * or not. Only relevant for explicit clears.
  48542. */
  48543. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true, resolveRenderTarget = true ) {
  48544. const { gl, renderer } = this;
  48545. if ( descriptor === null ) {
  48546. const clearColor = this.getClearColor();
  48547. descriptor = {
  48548. textures: null,
  48549. clearColorValue: clearColor
  48550. };
  48551. }
  48552. //
  48553. let clear = 0;
  48554. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  48555. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  48556. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  48557. if ( clear !== 0 ) {
  48558. let clearColor;
  48559. if ( descriptor.clearColorValue ) {
  48560. clearColor = descriptor.clearColorValue;
  48561. } else {
  48562. clearColor = this.getClearColor();
  48563. }
  48564. const clearDepth = renderer.getClearDepth();
  48565. const clearStencil = renderer.getClearStencil();
  48566. if ( depth ) this.state.setDepthMask( true );
  48567. if ( descriptor.textures === null ) {
  48568. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  48569. gl.clear( clear );
  48570. } else {
  48571. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  48572. if ( color ) {
  48573. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  48574. if ( i === 0 ) {
  48575. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  48576. } else {
  48577. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  48578. }
  48579. }
  48580. }
  48581. if ( depth && stencil ) {
  48582. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  48583. } else if ( depth ) {
  48584. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  48585. } else if ( stencil ) {
  48586. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  48587. }
  48588. if ( setFrameBuffer && resolveRenderTarget ) this._resolveRenderTarget( descriptor );
  48589. }
  48590. }
  48591. }
  48592. /**
  48593. * This method is executed at the beginning of a compute call and
  48594. * prepares the state for upcoming compute tasks.
  48595. *
  48596. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  48597. */
  48598. beginCompute( computeGroup ) {
  48599. const { state, gl } = this;
  48600. //
  48601. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  48602. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  48603. }
  48604. /**
  48605. * Executes a compute command for the given compute node.
  48606. *
  48607. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  48608. * @param {Node} computeNode - The compute node.
  48609. * @param {Array<BindGroup>} bindings - The bindings.
  48610. * @param {ComputePipeline} pipeline - The compute pipeline.
  48611. * @param {?number} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  48612. */
  48613. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  48614. const { state, gl } = this;
  48615. if ( this.discard === false ) {
  48616. // required here to handle async behaviour of render.compute()
  48617. gl.enable( gl.RASTERIZER_DISCARD );
  48618. this.discard = true;
  48619. }
  48620. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  48621. const vaoKey = this._getVaoKey( attributes );
  48622. const vaoGPU = this.vaoCache[ vaoKey ];
  48623. if ( vaoGPU === undefined ) {
  48624. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  48625. } else {
  48626. state.setVertexState( vaoGPU );
  48627. }
  48628. state.useProgram( programGPU );
  48629. this._bindUniforms( bindings );
  48630. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  48631. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  48632. gl.beginTransformFeedback( gl.POINTS );
  48633. count = ( count !== null ) ? count : computeNode.count;
  48634. if ( Array.isArray( count ) ) {
  48635. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  48636. count = count[ 0 ];
  48637. } else if ( count && typeof count === 'object' && count.isIndirectStorageBufferAttribute ) {
  48638. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute' );
  48639. count = computeNode.count;
  48640. }
  48641. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  48642. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  48643. } else {
  48644. gl.drawArrays( gl.POINTS, 0, count );
  48645. }
  48646. gl.endTransformFeedback();
  48647. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  48648. // switch active buffers
  48649. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  48650. const dualAttributeData = transformBuffers[ i ];
  48651. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  48652. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  48653. }
  48654. dualAttributeData.switchBuffers();
  48655. }
  48656. }
  48657. /**
  48658. * This method is executed at the end of a compute call and
  48659. * finalizes work after compute tasks.
  48660. *
  48661. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  48662. */
  48663. finishCompute( computeGroup ) {
  48664. const gl = this.gl;
  48665. this.discard = false;
  48666. gl.disable( gl.RASTERIZER_DISCARD );
  48667. this.prepareTimestampBuffer( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  48668. if ( this._currentContext ) {
  48669. this._setFramebuffer( this._currentContext );
  48670. }
  48671. }
  48672. /**
  48673. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  48674. *
  48675. * @param {RenderContext} renderContext - The render context.
  48676. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  48677. *
  48678. * @private
  48679. */
  48680. _isRenderCameraDepthArray( renderContext ) {
  48681. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  48682. }
  48683. /**
  48684. * Executes a draw command for the given render object.
  48685. *
  48686. * @param {RenderObject} renderObject - The render object to draw.
  48687. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  48688. */
  48689. draw( renderObject/*, info*/ ) {
  48690. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  48691. const { programGPU } = this.get( pipeline );
  48692. const { gl, state } = this;
  48693. const contextData = this.get( context );
  48694. const drawParams = renderObject.getDrawParameters();
  48695. if ( drawParams === null ) return;
  48696. //
  48697. this._bindUniforms( renderObject.getBindings() );
  48698. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  48699. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  48700. if ( context.textures !== null && context.textures.length > 1 ) {
  48701. state.setMRTBlending( context.textures );
  48702. }
  48703. state.useProgram( programGPU );
  48704. // vertex state
  48705. const attributes = renderObject.getAttributes();
  48706. const attributesData = this.get( attributes );
  48707. let vaoGPU = attributesData.vaoGPU;
  48708. if ( vaoGPU === undefined ) {
  48709. const vaoKey = this._getVaoKey( attributes );
  48710. vaoGPU = this.vaoCache[ vaoKey ];
  48711. if ( vaoGPU === undefined ) {
  48712. vaoGPU = this._createVao( attributes );
  48713. this.vaoCache[ vaoKey ] = vaoGPU;
  48714. attributesData.vaoGPU = vaoGPU;
  48715. }
  48716. }
  48717. const index = renderObject.getIndex();
  48718. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  48719. state.setVertexState( vaoGPU, indexGPU );
  48720. //
  48721. const lastObject = contextData.lastOcclusionObject;
  48722. if ( lastObject !== object && lastObject !== undefined ) {
  48723. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  48724. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  48725. contextData.occlusionQueryIndex ++;
  48726. }
  48727. if ( object.occlusionTest === true ) {
  48728. const query = gl.createQuery();
  48729. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  48730. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  48731. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  48732. }
  48733. contextData.lastOcclusionObject = object;
  48734. }
  48735. //
  48736. const renderer = this.bufferRenderer;
  48737. if ( object.isPoints ) renderer.mode = gl.POINTS;
  48738. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  48739. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  48740. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  48741. else {
  48742. if ( material.wireframe === true ) {
  48743. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  48744. renderer.mode = gl.LINES;
  48745. } else {
  48746. renderer.mode = gl.TRIANGLES;
  48747. }
  48748. }
  48749. //
  48750. const { vertexCount, instanceCount } = drawParams;
  48751. let { firstVertex } = drawParams;
  48752. renderer.object = object;
  48753. if ( index !== null ) {
  48754. firstVertex *= index.array.BYTES_PER_ELEMENT;
  48755. const indexData = this.get( index );
  48756. renderer.index = index.count;
  48757. renderer.type = indexData.type;
  48758. } else {
  48759. renderer.index = 0;
  48760. }
  48761. const draw = () => {
  48762. if ( object.isBatchedMesh ) {
  48763. if ( object._multiDrawInstances !== null ) {
  48764. // @deprecated, r174
  48765. warnOnce( 'WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  48766. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  48767. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  48768. warnOnce( 'WebGLBackend: WEBGL_multi_draw not supported.' );
  48769. } else {
  48770. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  48771. }
  48772. } else if ( instanceCount > 1 ) {
  48773. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  48774. } else {
  48775. renderer.render( firstVertex, vertexCount );
  48776. }
  48777. };
  48778. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  48779. const cameraData = this.get( renderObject.camera );
  48780. const cameras = renderObject.camera.cameras;
  48781. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  48782. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  48783. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  48784. const indexesGPU = [];
  48785. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  48786. const bufferGPU = gl.createBuffer();
  48787. data[ 0 ] = i;
  48788. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  48789. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  48790. indexesGPU.push( bufferGPU );
  48791. }
  48792. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  48793. }
  48794. const cameraIndexData = this.get( cameraIndex );
  48795. const pixelRatio = this.renderer.getPixelRatio();
  48796. const renderTarget = this._currentContext.renderTarget;
  48797. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  48798. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  48799. if ( isRenderCameraDepthArray ) {
  48800. // Clear the depth texture
  48801. const textureData = this.get( renderTarget.depthTexture );
  48802. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  48803. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  48804. const { stencilBuffer } = renderTarget;
  48805. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  48806. this.renderer._activeCubeFace = i;
  48807. this._currentContext.activeCubeFace = i;
  48808. this._setFramebuffer( this._currentContext );
  48809. this.clear( false, true, stencilBuffer, this._currentContext, false, false );
  48810. }
  48811. this.renderer._activeCubeFace = prevActiveCubeFace;
  48812. this._currentContext.activeCubeFace = prevActiveCubeFace;
  48813. }
  48814. }
  48815. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  48816. const subCamera = cameras[ i ];
  48817. if ( object.layers.test( subCamera.layers ) ) {
  48818. if ( isRenderCameraDepthArray ) {
  48819. // Update the active layer
  48820. this.renderer._activeCubeFace = i;
  48821. this._currentContext.activeCubeFace = i;
  48822. this._setFramebuffer( this._currentContext );
  48823. }
  48824. const vp = subCamera.viewport;
  48825. if ( vp !== undefined ) {
  48826. const x = vp.x * pixelRatio;
  48827. const y = vp.y * pixelRatio;
  48828. const width = vp.width * pixelRatio;
  48829. const height = vp.height * pixelRatio;
  48830. state.viewport(
  48831. Math.floor( x ),
  48832. Math.floor( renderObject.context.height - height - y ),
  48833. Math.floor( width ),
  48834. Math.floor( height )
  48835. );
  48836. }
  48837. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  48838. draw();
  48839. }
  48840. this._currentContext.activeCubeFace = prevActiveCubeFace;
  48841. this.renderer._activeCubeFace = prevActiveCubeFace;
  48842. }
  48843. } else {
  48844. draw();
  48845. }
  48846. }
  48847. /**
  48848. * Explain why always null is returned.
  48849. *
  48850. * @param {RenderObject} renderObject - The render object.
  48851. * @return {boolean} Whether the render pipeline requires an update or not.
  48852. */
  48853. needsRenderUpdate( /*renderObject*/ ) {
  48854. return false;
  48855. }
  48856. /**
  48857. * Explain why no cache key is computed.
  48858. *
  48859. * @param {RenderObject} renderObject - The render object.
  48860. * @return {string} The cache key.
  48861. */
  48862. getRenderCacheKey( /*renderObject*/ ) {
  48863. return '';
  48864. }
  48865. // textures
  48866. /**
  48867. * Creates a default texture for the given texture that can be used
  48868. * as a placeholder until the actual texture is ready for usage.
  48869. *
  48870. * @param {Texture} texture - The texture to create a default texture for.
  48871. */
  48872. createDefaultTexture( texture ) {
  48873. this.textureUtils.createDefaultTexture( texture );
  48874. }
  48875. /**
  48876. * Defines a texture on the GPU for the given texture object.
  48877. *
  48878. * @param {Texture} texture - The texture.
  48879. * @param {Object} [options={}] - Optional configuration parameter.
  48880. */
  48881. createTexture( texture, options ) {
  48882. this.textureUtils.createTexture( texture, options );
  48883. }
  48884. /**
  48885. * Uploads the updated texture data to the GPU.
  48886. *
  48887. * @param {Texture} texture - The texture.
  48888. * @param {Object} [options={}] - Optional configuration parameter.
  48889. */
  48890. updateTexture( texture, options ) {
  48891. this.textureUtils.updateTexture( texture, options );
  48892. }
  48893. /**
  48894. * Generates mipmaps for the given texture.
  48895. *
  48896. * @param {Texture} texture - The texture.
  48897. */
  48898. generateMipmaps( texture ) {
  48899. this.textureUtils.generateMipmaps( texture );
  48900. }
  48901. /**
  48902. * Destroys the GPU data for the given texture object.
  48903. *
  48904. * @param {Texture} texture - The texture.
  48905. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  48906. */
  48907. destroyTexture( texture, isDefaultTexture = false ) {
  48908. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  48909. }
  48910. /**
  48911. * Returns texture data as a typed array.
  48912. *
  48913. * @async
  48914. * @param {Texture} texture - The texture to copy.
  48915. * @param {number} x - The x coordinate of the copy origin.
  48916. * @param {number} y - The y coordinate of the copy origin.
  48917. * @param {number} width - The width of the copy.
  48918. * @param {number} height - The height of the copy.
  48919. * @param {number} faceIndex - The face index.
  48920. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  48921. */
  48922. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  48923. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  48924. }
  48925. /**
  48926. * This method does nothing since WebGL 2 has no concept of samplers.
  48927. *
  48928. * @param {Texture} texture - The texture to update the sampler for.
  48929. * @return {string} The current sampler key.
  48930. */
  48931. updateSampler( /*texture*/ ) {
  48932. return '';
  48933. }
  48934. // node builder
  48935. /**
  48936. * Returns a node builder for the given render object.
  48937. *
  48938. * @param {RenderObject} object - The render object.
  48939. * @param {Renderer} renderer - The renderer.
  48940. * @return {GLSLNodeBuilder} The node builder.
  48941. */
  48942. createNodeBuilder( object, renderer ) {
  48943. return new GLSLNodeBuilder( object, renderer );
  48944. }
  48945. // program
  48946. /**
  48947. * Creates a shader program from the given programmable stage.
  48948. *
  48949. * @param {ProgrammableStage} program - The programmable stage.
  48950. */
  48951. createProgram( program ) {
  48952. const gl = this.gl;
  48953. const { stage, code } = program;
  48954. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  48955. gl.shaderSource( shader, code );
  48956. gl.compileShader( shader );
  48957. this.set( program, {
  48958. shaderGPU: shader
  48959. } );
  48960. }
  48961. /**
  48962. * Destroys the shader program of the given programmable stage.
  48963. *
  48964. * @param {ProgrammableStage} program - The programmable stage.
  48965. */
  48966. destroyProgram( program ) {
  48967. this.delete( program );
  48968. }
  48969. /**
  48970. * Creates a render pipeline for the given render object.
  48971. *
  48972. * @param {RenderObject} renderObject - The render object.
  48973. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  48974. */
  48975. createRenderPipeline( renderObject, promises ) {
  48976. const gl = this.gl;
  48977. const pipeline = renderObject.pipeline;
  48978. // Program
  48979. const { fragmentProgram, vertexProgram } = pipeline;
  48980. const programGPU = gl.createProgram();
  48981. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  48982. const vertexShader = this.get( vertexProgram ).shaderGPU;
  48983. gl.attachShader( programGPU, fragmentShader );
  48984. gl.attachShader( programGPU, vertexShader );
  48985. gl.linkProgram( programGPU );
  48986. this.set( pipeline, {
  48987. programGPU,
  48988. fragmentShader,
  48989. vertexShader
  48990. } );
  48991. if ( promises !== null && this.parallel ) {
  48992. const p = new Promise( ( resolve /*, reject*/ ) => {
  48993. const parallel = this.parallel;
  48994. const checkStatus = () => {
  48995. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  48996. this._completeCompile( renderObject, pipeline );
  48997. resolve();
  48998. } else {
  48999. requestAnimationFrame( checkStatus );
  49000. }
  49001. };
  49002. checkStatus();
  49003. } );
  49004. promises.push( p );
  49005. return;
  49006. }
  49007. this._completeCompile( renderObject, pipeline );
  49008. }
  49009. /**
  49010. * Formats the source code of error messages.
  49011. *
  49012. * @private
  49013. * @param {string} string - The code.
  49014. * @param {number} errorLine - The error line.
  49015. * @return {string} The formatted code.
  49016. */
  49017. _handleSource( string, errorLine ) {
  49018. const lines = string.split( '\n' );
  49019. const lines2 = [];
  49020. const from = Math.max( errorLine - 6, 0 );
  49021. const to = Math.min( errorLine + 6, lines.length );
  49022. for ( let i = from; i < to; i ++ ) {
  49023. const line = i + 1;
  49024. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  49025. }
  49026. return lines2.join( '\n' );
  49027. }
  49028. /**
  49029. * Gets the shader compilation errors from the info log.
  49030. *
  49031. * @private
  49032. * @param {WebGL2RenderingContext} gl - The rendering context.
  49033. * @param {WebGLShader} shader - The WebGL shader object.
  49034. * @param {string} type - The shader type.
  49035. * @return {string} The shader errors.
  49036. */
  49037. _getShaderErrors( gl, shader, type ) {
  49038. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  49039. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  49040. const errors = shaderInfoLog.trim();
  49041. if ( status && errors === '' ) return '';
  49042. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  49043. if ( errorMatches ) {
  49044. const errorLine = parseInt( errorMatches[ 1 ] );
  49045. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  49046. } else {
  49047. return errors;
  49048. }
  49049. }
  49050. /**
  49051. * Logs shader compilation errors.
  49052. *
  49053. * @private
  49054. * @param {WebGLProgram} programGPU - The WebGL program.
  49055. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  49056. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  49057. */
  49058. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  49059. if ( this.renderer.debug.checkShaderErrors ) {
  49060. const gl = this.gl;
  49061. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  49062. const programLog = programInfoLog.trim();
  49063. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  49064. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  49065. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  49066. } else {
  49067. // default error reporting
  49068. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  49069. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  49070. error(
  49071. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  49072. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  49073. 'Program Info Log: ' + programLog + '\n' +
  49074. vertexErrors + '\n' +
  49075. fragmentErrors
  49076. );
  49077. }
  49078. } else if ( programLog !== '' ) {
  49079. warn( 'WebGLProgram: Program Info Log:', programLog );
  49080. }
  49081. }
  49082. }
  49083. /**
  49084. * Completes the shader program setup for the given render object.
  49085. *
  49086. * @private
  49087. * @param {RenderObject} renderObject - The render object.
  49088. * @param {RenderPipeline} pipeline - The render pipeline.
  49089. */
  49090. _completeCompile( renderObject, pipeline ) {
  49091. const { state, gl } = this;
  49092. const pipelineData = this.get( pipeline );
  49093. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  49094. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  49095. this._logProgramError( programGPU, fragmentShader, vertexShader );
  49096. }
  49097. state.useProgram( programGPU );
  49098. // Bindings
  49099. const bindings = renderObject.getBindings();
  49100. this._setupBindings( bindings, programGPU );
  49101. //
  49102. this.set( pipeline, {
  49103. programGPU
  49104. } );
  49105. }
  49106. /**
  49107. * Creates a compute pipeline for the given compute node.
  49108. *
  49109. * @param {ComputePipeline} computePipeline - The compute pipeline.
  49110. * @param {Array<BindGroup>} bindings - The bindings.
  49111. */
  49112. createComputePipeline( computePipeline, bindings ) {
  49113. const { state, gl } = this;
  49114. // Program
  49115. const fragmentProgram = {
  49116. stage: 'fragment',
  49117. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  49118. };
  49119. this.createProgram( fragmentProgram );
  49120. const { computeProgram } = computePipeline;
  49121. const programGPU = gl.createProgram();
  49122. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  49123. const vertexShader = this.get( computeProgram ).shaderGPU;
  49124. const transforms = computeProgram.transforms;
  49125. const transformVaryingNames = [];
  49126. const transformAttributeNodes = [];
  49127. for ( let i = 0; i < transforms.length; i ++ ) {
  49128. const transform = transforms[ i ];
  49129. transformVaryingNames.push( transform.varyingName );
  49130. transformAttributeNodes.push( transform.attributeNode );
  49131. }
  49132. gl.attachShader( programGPU, fragmentShader );
  49133. gl.attachShader( programGPU, vertexShader );
  49134. gl.transformFeedbackVaryings(
  49135. programGPU,
  49136. transformVaryingNames,
  49137. gl.SEPARATE_ATTRIBS
  49138. );
  49139. gl.linkProgram( programGPU );
  49140. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  49141. this._logProgramError( programGPU, fragmentShader, vertexShader );
  49142. }
  49143. state.useProgram( programGPU );
  49144. // Bindings
  49145. this._setupBindings( bindings, programGPU );
  49146. const attributeNodes = computeProgram.attributes;
  49147. const attributes = [];
  49148. const transformBuffers = [];
  49149. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  49150. const attribute = attributeNodes[ i ].node.attribute;
  49151. attributes.push( attribute );
  49152. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49153. }
  49154. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  49155. const attribute = transformAttributeNodes[ i ].attribute;
  49156. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49157. const attributeData = this.get( attribute );
  49158. transformBuffers.push( attributeData );
  49159. }
  49160. //
  49161. this.set( computePipeline, {
  49162. programGPU,
  49163. transformBuffers,
  49164. attributes
  49165. } );
  49166. }
  49167. /**
  49168. * Creates bindings from the given bind group definition.
  49169. *
  49170. * @param {BindGroup} bindGroup - The bind group.
  49171. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49172. * @param {number} cacheIndex - The cache index.
  49173. * @param {number} version - The version.
  49174. */
  49175. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  49176. if ( this._knownBindings.has( bindings ) === false ) {
  49177. this._knownBindings.add( bindings );
  49178. let uniformBuffers = 0;
  49179. let textures = 0;
  49180. for ( const bindGroup of bindings ) {
  49181. this.set( bindGroup, {
  49182. textures: textures,
  49183. uniformBuffers: uniformBuffers
  49184. } );
  49185. for ( const binding of bindGroup.bindings ) {
  49186. if ( binding.isUniformBuffer ) uniformBuffers ++;
  49187. if ( binding.isSampledTexture ) textures ++;
  49188. }
  49189. }
  49190. }
  49191. this.updateBindings( bindGroup, bindings );
  49192. }
  49193. /**
  49194. * Updates the given bind group definition.
  49195. *
  49196. * @param {BindGroup} bindGroup - The bind group.
  49197. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49198. * @param {number} cacheIndex - The cache index.
  49199. * @param {number} version - The version.
  49200. */
  49201. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  49202. const { gl } = this;
  49203. const bindGroupData = this.get( bindGroup );
  49204. let i = bindGroupData.uniformBuffers;
  49205. let t = bindGroupData.textures;
  49206. for ( const binding of bindGroup.bindings ) {
  49207. const map = this.get( binding );
  49208. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  49209. const array = binding.buffer;
  49210. let { bufferGPU } = this.get( array );
  49211. if ( bufferGPU === undefined ) {
  49212. // create
  49213. bufferGPU = gl.createBuffer();
  49214. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49215. gl.bufferData( gl.UNIFORM_BUFFER, array.byteLength, gl.DYNAMIC_DRAW );
  49216. this.set( array, { bufferGPU } );
  49217. } else {
  49218. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49219. }
  49220. // update
  49221. const updateRanges = binding.updateRanges;
  49222. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49223. if ( updateRanges.length === 0 ) {
  49224. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  49225. } else {
  49226. const isTyped = isTypedArray( array );
  49227. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  49228. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49229. const range = updateRanges[ i ];
  49230. const dataOffset = range.start * byteOffsetFactor;
  49231. const size = range.count * byteOffsetFactor;
  49232. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  49233. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  49234. }
  49235. }
  49236. map.index = i ++;
  49237. map.bufferGPU = bufferGPU;
  49238. this.set( binding, map );
  49239. } else if ( binding.isSampledTexture ) {
  49240. const { textureGPU, glTextureType } = this.get( binding.texture );
  49241. map.index = t ++;
  49242. map.textureGPU = textureGPU;
  49243. map.glTextureType = glTextureType;
  49244. this.set( binding, map );
  49245. }
  49246. }
  49247. }
  49248. /**
  49249. * Updates a buffer binding.
  49250. *
  49251. * @param {Buffer} binding - The buffer binding to update.
  49252. */
  49253. updateBinding( binding ) {
  49254. const gl = this.gl;
  49255. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  49256. const bindingData = this.get( binding );
  49257. const bufferGPU = bindingData.bufferGPU;
  49258. const array = binding.buffer;
  49259. const updateRanges = binding.updateRanges;
  49260. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49261. if ( updateRanges.length === 0 ) {
  49262. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  49263. } else {
  49264. const isTyped = isTypedArray( array );
  49265. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  49266. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49267. const range = updateRanges[ i ];
  49268. const dataOffset = range.start * byteOffsetFactor;
  49269. const size = range.count * byteOffsetFactor;
  49270. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  49271. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  49272. }
  49273. }
  49274. }
  49275. }
  49276. // attributes
  49277. /**
  49278. * Creates the GPU buffer of an indexed shader attribute.
  49279. *
  49280. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  49281. */
  49282. createIndexAttribute( attribute ) {
  49283. const gl = this.gl;
  49284. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  49285. }
  49286. /**
  49287. * Creates the GPU buffer of a shader attribute.
  49288. *
  49289. * @param {BufferAttribute} attribute - The buffer attribute.
  49290. */
  49291. createAttribute( attribute ) {
  49292. if ( this.has( attribute ) ) return;
  49293. const gl = this.gl;
  49294. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49295. }
  49296. /**
  49297. * Creates the GPU buffer of a storage attribute.
  49298. *
  49299. * @param {BufferAttribute} attribute - The buffer attribute.
  49300. */
  49301. createStorageAttribute( attribute ) {
  49302. if ( this.has( attribute ) ) return;
  49303. const gl = this.gl;
  49304. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49305. }
  49306. /**
  49307. * Updates the GPU buffer of a shader attribute.
  49308. *
  49309. * @param {BufferAttribute} attribute - The buffer attribute to update.
  49310. */
  49311. updateAttribute( attribute ) {
  49312. this.attributeUtils.updateAttribute( attribute );
  49313. }
  49314. /**
  49315. * Destroys the GPU buffer of a shader attribute.
  49316. *
  49317. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  49318. */
  49319. destroyAttribute( attribute ) {
  49320. this.attributeUtils.destroyAttribute( attribute );
  49321. }
  49322. /**
  49323. * Checks if the given feature is supported by the backend.
  49324. *
  49325. * @param {string} name - The feature's name.
  49326. * @return {boolean} Whether the feature is supported or not.
  49327. */
  49328. hasFeature( name ) {
  49329. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  49330. const extensions = this.extensions;
  49331. for ( let i = 0; i < keysMatching.length; i ++ ) {
  49332. if ( extensions.has( keysMatching[ i ] ) ) return true;
  49333. }
  49334. return false;
  49335. }
  49336. /**
  49337. * Returns the maximum anisotropy texture filtering value.
  49338. *
  49339. * @return {number} The maximum anisotropy texture filtering value.
  49340. */
  49341. getMaxAnisotropy() {
  49342. return this.capabilities.getMaxAnisotropy();
  49343. }
  49344. /**
  49345. * Copies data of the given source texture to the given destination texture.
  49346. *
  49347. * @param {Texture} srcTexture - The source texture.
  49348. * @param {Texture} dstTexture - The destination texture.
  49349. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  49350. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  49351. * @param {number} [srcLevel=0] - The source mip level to copy from.
  49352. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  49353. */
  49354. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  49355. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  49356. }
  49357. /**
  49358. * Copies the current bound framebuffer to the given texture.
  49359. *
  49360. * @param {Texture} texture - The destination texture.
  49361. * @param {RenderContext} renderContext - The render context.
  49362. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  49363. */
  49364. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  49365. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  49366. }
  49367. /**
  49368. * Configures the active framebuffer from the given render context.
  49369. *
  49370. * @private
  49371. * @param {RenderContext} descriptor - The render context.
  49372. */
  49373. _setFramebuffer( descriptor ) {
  49374. const { gl, state } = this;
  49375. let currentFrameBuffer = null;
  49376. if ( descriptor.textures !== null ) {
  49377. const renderTarget = descriptor.renderTarget;
  49378. const renderTargetContextData = this.get( renderTarget );
  49379. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  49380. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  49381. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  49382. const isRenderTargetArray = renderTarget.depth > 1;
  49383. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  49384. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  49385. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  49386. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  49387. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  49388. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  49389. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  49390. const cacheKey = getCacheKey( descriptor );
  49391. let fb;
  49392. if ( isCube ) {
  49393. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  49394. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  49395. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  49396. fb = this._xrFramebuffer;
  49397. } else {
  49398. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  49399. fb = renderTargetContextData.framebuffers[ cacheKey ];
  49400. }
  49401. if ( fb === undefined ) {
  49402. fb = gl.createFramebuffer();
  49403. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  49404. const textures = descriptor.textures;
  49405. const depthInvalidationArray = [];
  49406. if ( isCube ) {
  49407. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  49408. const { textureGPU } = this.get( textures[ 0 ] );
  49409. const cubeFace = this.renderer._activeCubeFace;
  49410. const mipLevel = this.renderer._activeMipmapLevel;
  49411. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, mipLevel );
  49412. } else {
  49413. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  49414. for ( let i = 0; i < textures.length; i ++ ) {
  49415. const texture = textures[ i ];
  49416. const textureData = this.get( texture );
  49417. textureData.renderTarget = descriptor.renderTarget;
  49418. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  49419. const attachment = gl.COLOR_ATTACHMENT0 + i;
  49420. if ( renderTarget.multiview ) {
  49421. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  49422. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  49423. const layer = this.renderer._activeCubeFace;
  49424. const mipLevel = this.renderer._activeMipmapLevel;
  49425. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, mipLevel, layer );
  49426. } else {
  49427. if ( useMultisampledRTT ) {
  49428. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49429. } else {
  49430. const mipLevel = this.renderer._activeMipmapLevel;
  49431. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, mipLevel );
  49432. }
  49433. }
  49434. }
  49435. }
  49436. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49437. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  49438. const renderbuffer = gl.createRenderbuffer();
  49439. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  49440. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  49441. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  49442. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  49443. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  49444. } else {
  49445. if ( descriptor.depthTexture !== null ) {
  49446. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  49447. const textureData = this.get( descriptor.depthTexture );
  49448. textureData.renderTarget = descriptor.renderTarget;
  49449. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  49450. if ( renderTarget.multiview ) {
  49451. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  49452. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  49453. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49454. } else {
  49455. if ( descriptor.depthTexture.isArrayTexture ) {
  49456. const layer = this.renderer._activeCubeFace;
  49457. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  49458. } else {
  49459. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  49460. }
  49461. }
  49462. }
  49463. }
  49464. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  49465. } else {
  49466. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  49467. if ( isRenderCameraDepthArray ) {
  49468. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  49469. const layer = this.renderer._activeCubeFace;
  49470. const depthData = this.get( descriptor.depthTexture );
  49471. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49472. gl.framebufferTextureLayer(
  49473. gl.FRAMEBUFFER,
  49474. depthStyle,
  49475. depthData.textureGPU,
  49476. 0,
  49477. layer
  49478. );
  49479. }
  49480. // rebind external XR textures
  49481. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  49482. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  49483. // rebind color
  49484. const textureData = this.get( descriptor.textures[ 0 ] );
  49485. if ( renderTarget.multiview ) {
  49486. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  49487. } else if ( useMultisampledRTT ) {
  49488. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49489. } else {
  49490. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  49491. }
  49492. // rebind depth
  49493. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49494. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  49495. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  49496. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  49497. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  49498. } else {
  49499. const textureData = this.get( descriptor.depthTexture );
  49500. if ( renderTarget.multiview ) {
  49501. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  49502. } else if ( useMultisampledRTT ) {
  49503. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49504. } else {
  49505. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  49506. }
  49507. }
  49508. }
  49509. }
  49510. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  49511. if ( msaaFb === undefined ) {
  49512. const invalidationArray = [];
  49513. msaaFb = gl.createFramebuffer();
  49514. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  49515. const msaaRenderbuffers = [];
  49516. const textures = descriptor.textures;
  49517. for ( let i = 0; i < textures.length; i ++ ) {
  49518. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  49519. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  49520. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  49521. const texture = descriptor.textures[ i ];
  49522. const textureData = this.get( texture );
  49523. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  49524. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  49525. }
  49526. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  49527. renderTargetContextData.msaaFrameBuffer = msaaFb;
  49528. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  49529. if ( depthBuffer && depthRenderbuffer === undefined ) {
  49530. depthRenderbuffer = gl.createRenderbuffer();
  49531. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  49532. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  49533. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49534. invalidationArray.push( depthStyle );
  49535. }
  49536. renderTargetContextData.invalidationArray = invalidationArray;
  49537. }
  49538. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  49539. } else {
  49540. currentFrameBuffer = fb;
  49541. }
  49542. state.drawBuffers( descriptor, fb );
  49543. }
  49544. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  49545. }
  49546. /**
  49547. * Computes the VAO key for the given index and attributes.
  49548. *
  49549. * @private
  49550. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  49551. * @return {string} The VAO key.
  49552. */
  49553. _getVaoKey( attributes ) {
  49554. let key = '';
  49555. for ( let i = 0; i < attributes.length; i ++ ) {
  49556. const attributeData = this.get( attributes[ i ] );
  49557. key += ':' + attributeData.id;
  49558. }
  49559. return key;
  49560. }
  49561. /**
  49562. * Creates a VAO from the index and attributes.
  49563. *
  49564. * @private
  49565. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  49566. * @return {Object} The VAO data.
  49567. */
  49568. _createVao( attributes ) {
  49569. const { gl } = this;
  49570. const vaoGPU = gl.createVertexArray();
  49571. gl.bindVertexArray( vaoGPU );
  49572. for ( let i = 0; i < attributes.length; i ++ ) {
  49573. const attribute = attributes[ i ];
  49574. const attributeData = this.get( attribute );
  49575. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  49576. gl.enableVertexAttribArray( i );
  49577. let stride, offset;
  49578. if ( attribute.isInterleavedBufferAttribute === true ) {
  49579. stride = attribute.data.stride * attributeData.bytesPerElement;
  49580. offset = attribute.offset * attributeData.bytesPerElement;
  49581. } else {
  49582. stride = 0;
  49583. offset = 0;
  49584. }
  49585. if ( attributeData.isInteger ) {
  49586. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  49587. } else {
  49588. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  49589. }
  49590. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  49591. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  49592. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  49593. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  49594. }
  49595. }
  49596. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  49597. return vaoGPU;
  49598. }
  49599. /**
  49600. * Creates a transform feedback from the given transform buffers.
  49601. *
  49602. * @private
  49603. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  49604. * @return {WebGLTransformFeedback} The transform feedback.
  49605. */
  49606. _getTransformFeedback( transformBuffers ) {
  49607. let key = '';
  49608. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  49609. key += ':' + transformBuffers[ i ].id;
  49610. }
  49611. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  49612. if ( transformFeedbackGPU !== undefined ) {
  49613. return transformFeedbackGPU;
  49614. }
  49615. const { gl } = this;
  49616. transformFeedbackGPU = gl.createTransformFeedback();
  49617. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  49618. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  49619. const attributeData = transformBuffers[ i ];
  49620. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  49621. }
  49622. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  49623. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  49624. return transformFeedbackGPU;
  49625. }
  49626. /**
  49627. * Setups the given bindings.
  49628. *
  49629. * @private
  49630. * @param {Array<BindGroup>} bindings - The bindings.
  49631. * @param {WebGLProgram} programGPU - The WebGL program.
  49632. */
  49633. _setupBindings( bindings, programGPU ) {
  49634. const gl = this.gl;
  49635. for ( const bindGroup of bindings ) {
  49636. for ( const binding of bindGroup.bindings ) {
  49637. const bindingData = this.get( binding );
  49638. const index = bindingData.index;
  49639. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  49640. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  49641. gl.uniformBlockBinding( programGPU, location, index );
  49642. } else if ( binding.isSampledTexture ) {
  49643. const location = gl.getUniformLocation( programGPU, binding.name );
  49644. gl.uniform1i( location, index );
  49645. }
  49646. }
  49647. }
  49648. }
  49649. /**
  49650. * Binds the given uniforms.
  49651. *
  49652. * @private
  49653. * @param {Array<BindGroup>} bindings - The bindings.
  49654. */
  49655. _bindUniforms( bindings ) {
  49656. const { gl, state } = this;
  49657. for ( const bindGroup of bindings ) {
  49658. for ( const binding of bindGroup.bindings ) {
  49659. const bindingData = this.get( binding );
  49660. const index = bindingData.index;
  49661. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  49662. // TODO USE bindBufferRange to group multiple uniform buffers
  49663. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  49664. } else if ( binding.isSampledTexture ) {
  49665. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  49666. }
  49667. }
  49668. }
  49669. }
  49670. /**
  49671. * The method ensures multisampled render targets are resolved.
  49672. *
  49673. * @private
  49674. * @param {RenderContext} renderContext - The render context.
  49675. */
  49676. _resolveRenderTarget( renderContext ) {
  49677. const { gl, state } = this;
  49678. const renderTarget = renderContext.renderTarget;
  49679. if ( renderContext.textures !== null && renderTarget ) {
  49680. const renderTargetContextData = this.get( renderTarget );
  49681. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  49682. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  49683. let mask = gl.COLOR_BUFFER_BIT;
  49684. if ( renderTarget.resolveDepthBuffer ) {
  49685. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  49686. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  49687. }
  49688. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  49689. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  49690. const textures = renderContext.textures;
  49691. const isMRT = textures.length > 1;
  49692. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  49693. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  49694. if ( isMRT ) {
  49695. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  49696. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  49697. for ( let i = 0; i < textures.length; i ++ ) {
  49698. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  49699. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  49700. }
  49701. }
  49702. for ( let i = 0; i < textures.length; i ++ ) {
  49703. if ( isMRT ) {
  49704. // configure attachment for resolve
  49705. const { textureGPU } = this.get( textures[ i ] );
  49706. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  49707. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  49708. }
  49709. if ( renderContext.scissor ) {
  49710. const { x, y, width, height } = renderContext.scissorValue;
  49711. const viewY = renderContext.height - height - y;
  49712. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  49713. } else {
  49714. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  49715. }
  49716. }
  49717. if ( isMRT ) {
  49718. // restore attachments
  49719. for ( let i = 0; i < textures.length; i ++ ) {
  49720. const { textureGPU } = this.get( textures[ i ] );
  49721. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  49722. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  49723. }
  49724. }
  49725. if ( this._supportsInvalidateFramebuffer === true ) {
  49726. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  49727. }
  49728. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  49729. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  49730. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  49731. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  49732. }
  49733. }
  49734. }
  49735. /**
  49736. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  49737. * should be used when MSAA is enabled.
  49738. *
  49739. * @private
  49740. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  49741. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  49742. */
  49743. _useMultisampledExtension( renderTarget ) {
  49744. if ( renderTarget.multiview === true ) {
  49745. return true;
  49746. }
  49747. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  49748. }
  49749. /**
  49750. * Frees internal resources.
  49751. */
  49752. dispose() {
  49753. if ( this.textureUtils !== null ) this.textureUtils.dispose();
  49754. const extension = this.extensions.get( 'WEBGL_lose_context' );
  49755. if ( extension ) extension.loseContext();
  49756. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  49757. }
  49758. }
  49759. const GPUPrimitiveTopology = {
  49760. PointList: 'point-list',
  49761. LineList: 'line-list',
  49762. LineStrip: 'line-strip',
  49763. TriangleList: 'triangle-list',
  49764. TriangleStrip: 'triangle-strip',
  49765. };
  49766. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  49767. const GPUCompareFunction = {
  49768. Never: 'never',
  49769. Less: 'less',
  49770. Equal: 'equal',
  49771. LessEqual: 'less-equal',
  49772. Greater: 'greater',
  49773. NotEqual: 'not-equal',
  49774. GreaterEqual: 'greater-equal',
  49775. Always: 'always'
  49776. };
  49777. const GPUStoreOp = {
  49778. Store: 'store'};
  49779. const GPULoadOp = {
  49780. Load: 'load',
  49781. Clear: 'clear'
  49782. };
  49783. const GPUFrontFace = {
  49784. CCW: 'ccw',
  49785. CW: 'cw'
  49786. };
  49787. const GPUCullMode = {
  49788. None: 'none',
  49789. Back: 'back'
  49790. };
  49791. const GPUIndexFormat = {
  49792. Uint16: 'uint16',
  49793. Uint32: 'uint32'
  49794. };
  49795. const GPUTextureFormat = {
  49796. // 8-bit formats
  49797. R8Unorm: 'r8unorm',
  49798. R8Snorm: 'r8snorm',
  49799. R8Uint: 'r8uint',
  49800. R8Sint: 'r8sint',
  49801. // 16-bit formats
  49802. R16Uint: 'r16uint',
  49803. R16Sint: 'r16sint',
  49804. R16Float: 'r16float',
  49805. RG8Unorm: 'rg8unorm',
  49806. RG8Snorm: 'rg8snorm',
  49807. RG8Uint: 'rg8uint',
  49808. RG8Sint: 'rg8sint',
  49809. // 32-bit formats
  49810. R32Uint: 'r32uint',
  49811. R32Sint: 'r32sint',
  49812. R32Float: 'r32float',
  49813. RG16Uint: 'rg16uint',
  49814. RG16Sint: 'rg16sint',
  49815. RG16Float: 'rg16float',
  49816. RGBA8Unorm: 'rgba8unorm',
  49817. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  49818. RGBA8Snorm: 'rgba8snorm',
  49819. RGBA8Uint: 'rgba8uint',
  49820. RGBA8Sint: 'rgba8sint',
  49821. BGRA8Unorm: 'bgra8unorm',
  49822. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  49823. // Packed 32-bit formats
  49824. RGB9E5UFloat: 'rgb9e5ufloat',
  49825. RGB10A2Unorm: 'rgb10a2unorm',
  49826. RG11B10UFloat: 'rg11b10ufloat',
  49827. // 64-bit formats
  49828. RG32Uint: 'rg32uint',
  49829. RG32Sint: 'rg32sint',
  49830. RG32Float: 'rg32float',
  49831. RGBA16Uint: 'rgba16uint',
  49832. RGBA16Sint: 'rgba16sint',
  49833. RGBA16Float: 'rgba16float',
  49834. // 128-bit formats
  49835. RGBA32Uint: 'rgba32uint',
  49836. RGBA32Sint: 'rgba32sint',
  49837. RGBA32Float: 'rgba32float',
  49838. Depth16Unorm: 'depth16unorm',
  49839. Depth24Plus: 'depth24plus',
  49840. Depth24PlusStencil8: 'depth24plus-stencil8',
  49841. Depth32Float: 'depth32float',
  49842. // 'depth32float-stencil8' extension
  49843. Depth32FloatStencil8: 'depth32float-stencil8',
  49844. // BC compressed formats usable if 'texture-compression-bc' is both
  49845. // supported by the device/user agent and enabled in requestDevice.
  49846. BC1RGBAUnorm: 'bc1-rgba-unorm',
  49847. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  49848. BC2RGBAUnorm: 'bc2-rgba-unorm',
  49849. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  49850. BC3RGBAUnorm: 'bc3-rgba-unorm',
  49851. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  49852. BC4RUnorm: 'bc4-r-unorm',
  49853. BC4RSnorm: 'bc4-r-snorm',
  49854. BC5RGUnorm: 'bc5-rg-unorm',
  49855. BC5RGSnorm: 'bc5-rg-snorm',
  49856. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  49857. BC6HRGBFloat: 'bc6h-rgb-float',
  49858. BC7RGBAUnorm: 'bc7-rgba-unorm',
  49859. BC7RGBAUnormSRGB: 'bc7-rgba-unorm-srgb',
  49860. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  49861. // supported by the device/user agent and enabled in requestDevice.
  49862. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  49863. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  49864. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  49865. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  49866. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  49867. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  49868. EACR11Unorm: 'eac-r11unorm',
  49869. EACR11Snorm: 'eac-r11snorm',
  49870. EACRG11Unorm: 'eac-rg11unorm',
  49871. EACRG11Snorm: 'eac-rg11snorm',
  49872. // ASTC compressed formats usable if 'texture-compression-astc' is both
  49873. // supported by the device/user agent and enabled in requestDevice.
  49874. ASTC4x4Unorm: 'astc-4x4-unorm',
  49875. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  49876. ASTC5x4Unorm: 'astc-5x4-unorm',
  49877. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  49878. ASTC5x5Unorm: 'astc-5x5-unorm',
  49879. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  49880. ASTC6x5Unorm: 'astc-6x5-unorm',
  49881. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  49882. ASTC6x6Unorm: 'astc-6x6-unorm',
  49883. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  49884. ASTC8x5Unorm: 'astc-8x5-unorm',
  49885. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  49886. ASTC8x6Unorm: 'astc-8x6-unorm',
  49887. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  49888. ASTC8x8Unorm: 'astc-8x8-unorm',
  49889. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  49890. ASTC10x5Unorm: 'astc-10x5-unorm',
  49891. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  49892. ASTC10x6Unorm: 'astc-10x6-unorm',
  49893. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  49894. ASTC10x8Unorm: 'astc-10x8-unorm',
  49895. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  49896. ASTC10x10Unorm: 'astc-10x10-unorm',
  49897. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  49898. ASTC12x10Unorm: 'astc-12x10-unorm',
  49899. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  49900. ASTC12x12Unorm: 'astc-12x12-unorm',
  49901. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  49902. };
  49903. const GPUAddressMode = {
  49904. ClampToEdge: 'clamp-to-edge',
  49905. Repeat: 'repeat',
  49906. MirrorRepeat: 'mirror-repeat'
  49907. };
  49908. const GPUFilterMode = {
  49909. Linear: 'linear',
  49910. Nearest: 'nearest'
  49911. };
  49912. const GPUBlendFactor = {
  49913. Zero: 'zero',
  49914. One: 'one',
  49915. Src: 'src',
  49916. OneMinusSrc: 'one-minus-src',
  49917. SrcAlpha: 'src-alpha',
  49918. OneMinusSrcAlpha: 'one-minus-src-alpha',
  49919. Dst: 'dst',
  49920. OneMinusDst: 'one-minus-dst',
  49921. DstAlpha: 'dst-alpha',
  49922. OneMinusDstAlpha: 'one-minus-dst-alpha',
  49923. SrcAlphaSaturated: 'src-alpha-saturated',
  49924. Constant: 'constant',
  49925. OneMinusConstant: 'one-minus-constant'
  49926. };
  49927. const GPUBlendOperation = {
  49928. Add: 'add',
  49929. Subtract: 'subtract',
  49930. ReverseSubtract: 'reverse-subtract',
  49931. Min: 'min',
  49932. Max: 'max'
  49933. };
  49934. const GPUColorWriteFlags = {
  49935. None: 0,
  49936. All: 0xF
  49937. };
  49938. const GPUStencilOperation = {
  49939. Keep: 'keep',
  49940. Zero: 'zero',
  49941. Replace: 'replace',
  49942. Invert: 'invert',
  49943. IncrementClamp: 'increment-clamp',
  49944. DecrementClamp: 'decrement-clamp',
  49945. IncrementWrap: 'increment-wrap',
  49946. DecrementWrap: 'decrement-wrap'
  49947. };
  49948. const GPUBufferBindingType = {
  49949. Storage: 'storage',
  49950. ReadOnlyStorage: 'read-only-storage'
  49951. };
  49952. const GPUStorageTextureAccess = {
  49953. WriteOnly: 'write-only',
  49954. ReadOnly: 'read-only',
  49955. ReadWrite: 'read-write',
  49956. };
  49957. const GPUSamplerBindingType = {
  49958. NonFiltering: 'non-filtering',
  49959. Comparison: 'comparison'
  49960. };
  49961. const GPUTextureSampleType = {
  49962. Float: 'float',
  49963. UnfilterableFloat: 'unfilterable-float',
  49964. Depth: 'depth',
  49965. SInt: 'sint',
  49966. UInt: 'uint'
  49967. };
  49968. const GPUTextureDimension = {
  49969. TwoD: '2d',
  49970. ThreeD: '3d'
  49971. };
  49972. const GPUTextureViewDimension = {
  49973. TwoD: '2d',
  49974. TwoDArray: '2d-array',
  49975. Cube: 'cube',
  49976. ThreeD: '3d'
  49977. };
  49978. const GPUTextureAspect = {
  49979. All: 'all'};
  49980. const GPUInputStepMode = {
  49981. Vertex: 'vertex',
  49982. Instance: 'instance'
  49983. };
  49984. const GPUFeatureName = {
  49985. CoreFeaturesAndLimits: 'core-features-and-limits',
  49986. DepthClipControl: 'depth-clip-control',
  49987. Depth32FloatStencil8: 'depth32float-stencil8',
  49988. TextureCompressionBC: 'texture-compression-bc',
  49989. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  49990. TextureCompressionETC2: 'texture-compression-etc2',
  49991. TextureCompressionASTC: 'texture-compression-astc',
  49992. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  49993. TimestampQuery: 'timestamp-query',
  49994. IndirectFirstInstance: 'indirect-first-instance',
  49995. ShaderF16: 'shader-f16',
  49996. RG11B10UFloat: 'rg11b10ufloat-renderable',
  49997. BGRA8UNormStorage: 'bgra8unorm-storage',
  49998. Float32Filterable: 'float32-filterable',
  49999. Float32Blendable: 'float32-blendable',
  50000. ClipDistances: 'clip-distances',
  50001. DualSourceBlending: 'dual-source-blending',
  50002. Subgroups: 'subgroups',
  50003. TextureFormatsTier1: 'texture-formats-tier1',
  50004. TextureFormatsTier2: 'texture-formats-tier2'
  50005. };
  50006. const GPUFeatureMap = {
  50007. 'texture-compression-s3tc': 'texture-compression-bc',
  50008. 'texture-compression-etc1': 'texture-compression-etc2'
  50009. };
  50010. /**
  50011. * A special form of sampler binding type.
  50012. * It's texture value is managed by a node object.
  50013. *
  50014. * @private
  50015. * @augments Sampler
  50016. */
  50017. class NodeSampler extends Sampler {
  50018. /**
  50019. * Constructs a new node-based sampler.
  50020. *
  50021. * @param {string} name - The samplers's name.
  50022. * @param {TextureNode} textureNode - The texture node.
  50023. * @param {UniformGroupNode} groupNode - The uniform group node.
  50024. */
  50025. constructor( name, textureNode, groupNode ) {
  50026. super( name, textureNode ? textureNode.value : null );
  50027. /**
  50028. * The texture node.
  50029. *
  50030. * @type {TextureNode}
  50031. */
  50032. this.textureNode = textureNode;
  50033. /**
  50034. * The uniform group node.
  50035. *
  50036. * @type {UniformGroupNode}
  50037. */
  50038. this.groupNode = groupNode;
  50039. }
  50040. /**
  50041. * Updates the texture value of this sampler.
  50042. *
  50043. * @return {boolean} Whether the sampler needs an update or not.
  50044. */
  50045. update() {
  50046. const { textureNode } = this;
  50047. if ( this.texture !== textureNode.value ) {
  50048. this.texture = textureNode.value;
  50049. return true;
  50050. }
  50051. return super.update();
  50052. }
  50053. }
  50054. /**
  50055. * Represents a storage buffer binding type.
  50056. *
  50057. * @private
  50058. * @augments Buffer
  50059. */
  50060. class StorageBuffer extends Buffer {
  50061. /**
  50062. * Constructs a new uniform buffer.
  50063. *
  50064. * @param {string} name - The buffer's name.
  50065. * @param {BufferAttribute} attribute - The buffer attribute.
  50066. */
  50067. constructor( name, attribute ) {
  50068. super( name, attribute ? attribute.array : null );
  50069. /**
  50070. * This flag can be used for type testing.
  50071. *
  50072. * @type {BufferAttribute}
  50073. */
  50074. this.attribute = attribute;
  50075. /**
  50076. * This flag can be used for type testing.
  50077. *
  50078. * @type {boolean}
  50079. * @readonly
  50080. * @default true
  50081. */
  50082. this.isStorageBuffer = true;
  50083. }
  50084. }
  50085. let _id = 0;
  50086. /**
  50087. * A special form of storage buffer binding type.
  50088. * It's buffer value is managed by a node object.
  50089. *
  50090. * @private
  50091. * @augments StorageBuffer
  50092. */
  50093. class NodeStorageBuffer extends StorageBuffer {
  50094. /**
  50095. * Constructs a new node-based storage buffer.
  50096. *
  50097. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  50098. * @param {UniformGroupNode} groupNode - The uniform group node.
  50099. */
  50100. constructor( nodeUniform, groupNode ) {
  50101. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  50102. /**
  50103. * The node uniform.
  50104. *
  50105. * @type {StorageBufferNode}
  50106. */
  50107. this.nodeUniform = nodeUniform;
  50108. /**
  50109. * The access type.
  50110. *
  50111. * @type {string}
  50112. */
  50113. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  50114. /**
  50115. * The uniform group node.
  50116. *
  50117. * @type {UniformGroupNode}
  50118. */
  50119. this.groupNode = groupNode;
  50120. }
  50121. /**
  50122. * The storage buffer.
  50123. *
  50124. * @type {BufferAttribute}
  50125. */
  50126. get buffer() {
  50127. return this.nodeUniform.value;
  50128. }
  50129. }
  50130. /**
  50131. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  50132. *
  50133. * @private
  50134. */
  50135. class WebGPUTexturePassUtils extends DataMap {
  50136. /**
  50137. * Constructs a new utility object.
  50138. *
  50139. * @param {GPUDevice} device - The WebGPU device.
  50140. */
  50141. constructor( device ) {
  50142. super();
  50143. /**
  50144. * The WebGPU device.
  50145. *
  50146. * @type {GPUDevice}
  50147. */
  50148. this.device = device;
  50149. const mipmapVertexSource = `
  50150. struct VarysStruct {
  50151. @builtin( position ) Position: vec4<f32>,
  50152. @location( 0 ) vTex : vec2<f32>
  50153. };
  50154. @vertex
  50155. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  50156. var Varys : VarysStruct;
  50157. var pos = array< vec2<f32>, 4 >(
  50158. vec2<f32>( -1.0, 1.0 ),
  50159. vec2<f32>( 1.0, 1.0 ),
  50160. vec2<f32>( -1.0, -1.0 ),
  50161. vec2<f32>( 1.0, -1.0 )
  50162. );
  50163. var tex = array< vec2<f32>, 4 >(
  50164. vec2<f32>( 0.0, 0.0 ),
  50165. vec2<f32>( 1.0, 0.0 ),
  50166. vec2<f32>( 0.0, 1.0 ),
  50167. vec2<f32>( 1.0, 1.0 )
  50168. );
  50169. Varys.vTex = tex[ vertexIndex ];
  50170. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  50171. return Varys;
  50172. }
  50173. `;
  50174. const mipmapFragmentSource = `
  50175. @group( 0 ) @binding( 0 )
  50176. var imgSampler : sampler;
  50177. @group( 0 ) @binding( 1 )
  50178. var img : texture_2d<f32>;
  50179. @fragment
  50180. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  50181. return textureSample( img, imgSampler, vTex );
  50182. }
  50183. `;
  50184. const flipYFragmentSource = `
  50185. @group( 0 ) @binding( 0 )
  50186. var imgSampler : sampler;
  50187. @group( 0 ) @binding( 1 )
  50188. var img : texture_2d<f32>;
  50189. @fragment
  50190. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  50191. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  50192. }
  50193. `;
  50194. /**
  50195. * The mipmap GPU sampler.
  50196. *
  50197. * @type {GPUSampler}
  50198. */
  50199. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  50200. /**
  50201. * The flipY GPU sampler.
  50202. *
  50203. * @type {GPUSampler}
  50204. */
  50205. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  50206. /**
  50207. * A cache for GPU render pipelines used for copy/transfer passes.
  50208. * Every texture format requires a unique pipeline.
  50209. *
  50210. * @type {Object<string,GPURenderPipeline>}
  50211. */
  50212. this.transferPipelines = {};
  50213. /**
  50214. * A cache for GPU render pipelines used for flipY passes.
  50215. * Every texture format requires a unique pipeline.
  50216. *
  50217. * @type {Object<string,GPURenderPipeline>}
  50218. */
  50219. this.flipYPipelines = {};
  50220. /**
  50221. * The mipmap vertex shader module.
  50222. *
  50223. * @type {GPUShaderModule}
  50224. */
  50225. this.mipmapVertexShaderModule = device.createShaderModule( {
  50226. label: 'mipmapVertex',
  50227. code: mipmapVertexSource
  50228. } );
  50229. /**
  50230. * The mipmap fragment shader module.
  50231. *
  50232. * @type {GPUShaderModule}
  50233. */
  50234. this.mipmapFragmentShaderModule = device.createShaderModule( {
  50235. label: 'mipmapFragment',
  50236. code: mipmapFragmentSource
  50237. } );
  50238. /**
  50239. * The flipY fragment shader module.
  50240. *
  50241. * @type {GPUShaderModule}
  50242. */
  50243. this.flipYFragmentShaderModule = device.createShaderModule( {
  50244. label: 'flipYFragment',
  50245. code: flipYFragmentSource
  50246. } );
  50247. }
  50248. /**
  50249. * Returns a render pipeline for the internal copy render pass. The pass
  50250. * requires a unique render pipeline for each texture format.
  50251. *
  50252. * @param {string} format - The GPU texture format
  50253. * @return {GPURenderPipeline} The GPU render pipeline.
  50254. */
  50255. getTransferPipeline( format ) {
  50256. let pipeline = this.transferPipelines[ format ];
  50257. if ( pipeline === undefined ) {
  50258. pipeline = this.device.createRenderPipeline( {
  50259. label: `mipmap-${ format }`,
  50260. vertex: {
  50261. module: this.mipmapVertexShaderModule,
  50262. entryPoint: 'main'
  50263. },
  50264. fragment: {
  50265. module: this.mipmapFragmentShaderModule,
  50266. entryPoint: 'main',
  50267. targets: [ { format } ]
  50268. },
  50269. primitive: {
  50270. topology: GPUPrimitiveTopology.TriangleStrip,
  50271. stripIndexFormat: GPUIndexFormat.Uint32
  50272. },
  50273. layout: 'auto'
  50274. } );
  50275. this.transferPipelines[ format ] = pipeline;
  50276. }
  50277. return pipeline;
  50278. }
  50279. /**
  50280. * Returns a render pipeline for the flipY render pass. The pass
  50281. * requires a unique render pipeline for each texture format.
  50282. *
  50283. * @param {string} format - The GPU texture format
  50284. * @return {GPURenderPipeline} The GPU render pipeline.
  50285. */
  50286. getFlipYPipeline( format ) {
  50287. let pipeline = this.flipYPipelines[ format ];
  50288. if ( pipeline === undefined ) {
  50289. pipeline = this.device.createRenderPipeline( {
  50290. label: `flipY-${ format }`,
  50291. vertex: {
  50292. module: this.mipmapVertexShaderModule,
  50293. entryPoint: 'main'
  50294. },
  50295. fragment: {
  50296. module: this.flipYFragmentShaderModule,
  50297. entryPoint: 'main',
  50298. targets: [ { format } ]
  50299. },
  50300. primitive: {
  50301. topology: GPUPrimitiveTopology.TriangleStrip,
  50302. stripIndexFormat: GPUIndexFormat.Uint32
  50303. },
  50304. layout: 'auto'
  50305. } );
  50306. this.flipYPipelines[ format ] = pipeline;
  50307. }
  50308. return pipeline;
  50309. }
  50310. /**
  50311. * Flip the contents of the given GPU texture along its vertical axis.
  50312. *
  50313. * @param {GPUTexture} textureGPU - The GPU texture object.
  50314. * @param {Object} textureGPUDescriptor - The texture descriptor.
  50315. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  50316. */
  50317. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  50318. const format = textureGPUDescriptor.format;
  50319. const { width, height } = textureGPUDescriptor.size;
  50320. const transferPipeline = this.getTransferPipeline( format );
  50321. const flipYPipeline = this.getFlipYPipeline( format );
  50322. const tempTexture = this.device.createTexture( {
  50323. size: { width, height, depthOrArrayLayers: 1 },
  50324. format,
  50325. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  50326. } );
  50327. const srcView = textureGPU.createView( {
  50328. baseMipLevel: 0,
  50329. mipLevelCount: 1,
  50330. dimension: GPUTextureViewDimension.TwoD,
  50331. baseArrayLayer
  50332. } );
  50333. const dstView = tempTexture.createView( {
  50334. baseMipLevel: 0,
  50335. mipLevelCount: 1,
  50336. dimension: GPUTextureViewDimension.TwoD,
  50337. baseArrayLayer: 0
  50338. } );
  50339. const commandEncoder = this.device.createCommandEncoder( {} );
  50340. const pass = ( pipeline, sourceView, destinationView ) => {
  50341. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  50342. const bindGroup = this.device.createBindGroup( {
  50343. layout: bindGroupLayout,
  50344. entries: [ {
  50345. binding: 0,
  50346. resource: this.flipYSampler
  50347. }, {
  50348. binding: 1,
  50349. resource: sourceView
  50350. } ]
  50351. } );
  50352. const passEncoder = commandEncoder.beginRenderPass( {
  50353. colorAttachments: [ {
  50354. view: destinationView,
  50355. loadOp: GPULoadOp.Clear,
  50356. storeOp: GPUStoreOp.Store,
  50357. clearValue: [ 0, 0, 0, 0 ]
  50358. } ]
  50359. } );
  50360. passEncoder.setPipeline( pipeline );
  50361. passEncoder.setBindGroup( 0, bindGroup );
  50362. passEncoder.draw( 4, 1, 0, 0 );
  50363. passEncoder.end();
  50364. };
  50365. pass( transferPipeline, srcView, dstView );
  50366. pass( flipYPipeline, dstView, srcView );
  50367. this.device.queue.submit( [ commandEncoder.finish() ] );
  50368. tempTexture.destroy();
  50369. }
  50370. /**
  50371. * Generates mipmaps for the given GPU texture.
  50372. *
  50373. * @param {GPUTexture} textureGPU - The GPU texture object.
  50374. * @param {Object} textureGPUDescriptor - The texture descriptor.
  50375. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  50376. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  50377. */
  50378. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0, encoder = null ) {
  50379. const textureData = this.get( textureGPU );
  50380. if ( textureData.layers === undefined ) {
  50381. textureData.layers = [];
  50382. }
  50383. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  50384. const commandEncoder = encoder || this.device.createCommandEncoder( { label: 'mipmapEncoder' } );
  50385. this._mipmapRunBundles( commandEncoder, passes );
  50386. if ( encoder === null ) this.device.queue.submit( [ commandEncoder.finish() ] );
  50387. textureData.layers[ baseArrayLayer ] = passes;
  50388. }
  50389. /**
  50390. * Since multiple copy render passes are required to generate mipmaps, the passes
  50391. * are managed as render bundles to improve performance.
  50392. *
  50393. * @param {GPUTexture} textureGPU - The GPU texture object.
  50394. * @param {Object} textureGPUDescriptor - The texture descriptor.
  50395. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  50396. * @return {Array<Object>} An array of render bundles.
  50397. */
  50398. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  50399. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  50400. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  50401. let srcView = textureGPU.createView( {
  50402. baseMipLevel: 0,
  50403. mipLevelCount: 1,
  50404. dimension: GPUTextureViewDimension.TwoD,
  50405. baseArrayLayer
  50406. } );
  50407. const passes = [];
  50408. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  50409. const bindGroup = this.device.createBindGroup( {
  50410. layout: bindGroupLayout,
  50411. entries: [ {
  50412. binding: 0,
  50413. resource: this.mipmapSampler
  50414. }, {
  50415. binding: 1,
  50416. resource: srcView
  50417. } ]
  50418. } );
  50419. const dstView = textureGPU.createView( {
  50420. baseMipLevel: i,
  50421. mipLevelCount: 1,
  50422. dimension: GPUTextureViewDimension.TwoD,
  50423. baseArrayLayer
  50424. } );
  50425. const passDescriptor = {
  50426. colorAttachments: [ {
  50427. view: dstView,
  50428. loadOp: GPULoadOp.Clear,
  50429. storeOp: GPUStoreOp.Store,
  50430. clearValue: [ 0, 0, 0, 0 ]
  50431. } ]
  50432. };
  50433. const passEncoder = this.device.createRenderBundleEncoder( {
  50434. colorFormats: [ textureGPUDescriptor.format ]
  50435. } );
  50436. passEncoder.setPipeline( pipeline );
  50437. passEncoder.setBindGroup( 0, bindGroup );
  50438. passEncoder.draw( 4, 1, 0, 0 );
  50439. passes.push( {
  50440. renderBundles: [ passEncoder.finish() ],
  50441. passDescriptor
  50442. } );
  50443. srcView = dstView;
  50444. }
  50445. return passes;
  50446. }
  50447. /**
  50448. * Executes the render bundles.
  50449. *
  50450. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  50451. * @param {Array<Object>} passes - An array of render bundles.
  50452. */
  50453. _mipmapRunBundles( commandEncoder, passes ) {
  50454. const levels = passes.length;
  50455. for ( let i = 0; i < levels; i ++ ) {
  50456. const pass = passes[ i ];
  50457. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  50458. passEncoder.executeBundles( pass.renderBundles );
  50459. passEncoder.end();
  50460. }
  50461. }
  50462. }
  50463. const _compareToWebGPU = {
  50464. [ NeverCompare ]: 'never',
  50465. [ LessCompare ]: 'less',
  50466. [ EqualCompare ]: 'equal',
  50467. [ LessEqualCompare ]: 'less-equal',
  50468. [ GreaterCompare ]: 'greater',
  50469. [ GreaterEqualCompare ]: 'greater-equal',
  50470. [ AlwaysCompare ]: 'always',
  50471. [ NotEqualCompare ]: 'not-equal'
  50472. };
  50473. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  50474. /**
  50475. * A WebGPU backend utility module for managing textures.
  50476. *
  50477. * @private
  50478. */
  50479. class WebGPUTextureUtils {
  50480. /**
  50481. * Constructs a new utility object.
  50482. *
  50483. * @param {WebGPUBackend} backend - The WebGPU backend.
  50484. */
  50485. constructor( backend ) {
  50486. /**
  50487. * A reference to the WebGPU backend.
  50488. *
  50489. * @type {WebGPUBackend}
  50490. */
  50491. this.backend = backend;
  50492. /**
  50493. * A reference to the pass utils.
  50494. *
  50495. * @type {?WebGPUTexturePassUtils}
  50496. * @default null
  50497. */
  50498. this._passUtils = null;
  50499. /**
  50500. * A dictionary for managing default textures. The key
  50501. * is the texture format, the value the texture object.
  50502. *
  50503. * @type {Object<string,Texture>}
  50504. */
  50505. this.defaultTexture = {};
  50506. /**
  50507. * A dictionary for managing default cube textures. The key
  50508. * is the texture format, the value the texture object.
  50509. *
  50510. * @type {Object<string,CubeTexture>}
  50511. */
  50512. this.defaultCubeTexture = {};
  50513. /**
  50514. * A default video frame.
  50515. *
  50516. * @type {?VideoFrame}
  50517. * @default null
  50518. */
  50519. this.defaultVideoFrame = null;
  50520. /**
  50521. * A cache of shared texture samplers.
  50522. *
  50523. * @type {Map<string, Object>}
  50524. */
  50525. this._samplerCache = new Map();
  50526. }
  50527. /**
  50528. * Creates a GPU sampler for the given texture.
  50529. *
  50530. * @param {Texture} texture - The texture to create the sampler for.
  50531. * @return {string} The current sampler key.
  50532. */
  50533. updateSampler( texture ) {
  50534. const backend = this.backend;
  50535. const samplerKey = texture.minFilter + '-' + texture.magFilter + '-' +
  50536. texture.wrapS + '-' + texture.wrapT + '-' + ( texture.wrapR || '0' ) + '-' +
  50537. texture.anisotropy + '-' + ( texture.compareFunction || 0 );
  50538. let samplerData = this._samplerCache.get( samplerKey );
  50539. if ( samplerData === undefined ) {
  50540. const samplerDescriptorGPU = {
  50541. addressModeU: this._convertAddressMode( texture.wrapS ),
  50542. addressModeV: this._convertAddressMode( texture.wrapT ),
  50543. addressModeW: this._convertAddressMode( texture.wrapR ),
  50544. magFilter: this._convertFilterMode( texture.magFilter ),
  50545. minFilter: this._convertFilterMode( texture.minFilter ),
  50546. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  50547. maxAnisotropy: 1
  50548. };
  50549. // anisotropy can only be used when all filter modes are set to linear.
  50550. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  50551. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  50552. }
  50553. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  50554. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  50555. }
  50556. const sampler = backend.device.createSampler( samplerDescriptorGPU );
  50557. samplerData = { sampler, usedTimes: 0 };
  50558. this._samplerCache.set( samplerKey, samplerData );
  50559. }
  50560. const textureData = backend.get( texture );
  50561. if ( textureData.sampler !== samplerData.sampler ) {
  50562. // check if previous sampler is unused so it can be deleted
  50563. if ( textureData.sampler !== undefined ) {
  50564. const oldSamplerData = this._samplerCache.get( textureData.samplerKey );
  50565. oldSamplerData.usedTimes --;
  50566. if ( oldSamplerData.usedTimes === 0 ) {
  50567. this._samplerCache.delete( textureData.samplerKey );
  50568. }
  50569. }
  50570. // update to new sampler data
  50571. textureData.samplerKey = samplerKey;
  50572. textureData.sampler = samplerData.sampler;
  50573. samplerData.usedTimes ++;
  50574. }
  50575. return samplerKey;
  50576. }
  50577. /**
  50578. * Creates a default texture for the given texture that can be used
  50579. * as a placeholder until the actual texture is ready for usage.
  50580. *
  50581. * @param {Texture} texture - The texture to create a default texture for.
  50582. */
  50583. createDefaultTexture( texture ) {
  50584. let textureGPU;
  50585. const format = getFormat( texture );
  50586. if ( texture.isCubeTexture ) {
  50587. textureGPU = this._getDefaultCubeTextureGPU( format );
  50588. } else {
  50589. textureGPU = this._getDefaultTextureGPU( format );
  50590. }
  50591. this.backend.get( texture ).texture = textureGPU;
  50592. }
  50593. /**
  50594. * Defines a texture on the GPU for the given texture object.
  50595. *
  50596. * @param {Texture} texture - The texture.
  50597. * @param {Object} [options={}] - Optional configuration parameter.
  50598. */
  50599. createTexture( texture, options = {} ) {
  50600. const backend = this.backend;
  50601. const textureData = backend.get( texture );
  50602. if ( textureData.initialized ) {
  50603. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  50604. }
  50605. if ( texture.isExternalTexture ) {
  50606. textureData.texture = texture.sourceTexture;
  50607. textureData.initialized = true;
  50608. return;
  50609. }
  50610. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  50611. if ( options.levels === undefined ) options.levels = 1;
  50612. if ( options.depth === undefined ) options.depth = 1;
  50613. const { width, height, depth, levels } = options;
  50614. if ( texture.isFramebufferTexture ) {
  50615. if ( options.renderTarget ) {
  50616. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  50617. } else {
  50618. options.format = this.backend.utils.getPreferredCanvasFormat();
  50619. }
  50620. }
  50621. const dimension = this._getDimension( texture );
  50622. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  50623. textureData.format = format;
  50624. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  50625. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  50626. if ( texture.isStorageTexture === true ) {
  50627. usage |= GPUTextureUsage.STORAGE_BINDING;
  50628. }
  50629. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true && format !== GPUTextureFormat.RGB9E5UFloat ) {
  50630. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  50631. }
  50632. const textureDescriptorGPU = {
  50633. label: texture.name,
  50634. size: {
  50635. width: width,
  50636. height: height,
  50637. depthOrArrayLayers: depth,
  50638. },
  50639. mipLevelCount: levels,
  50640. sampleCount: primarySamples,
  50641. dimension: dimension,
  50642. format: format,
  50643. usage: usage
  50644. };
  50645. // texture creation
  50646. if ( format === undefined ) {
  50647. warn( 'WebGPURenderer: Texture format not supported.' );
  50648. this.createDefaultTexture( texture );
  50649. return;
  50650. }
  50651. if ( texture.isCubeTexture ) {
  50652. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  50653. }
  50654. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  50655. if ( isMSAA ) {
  50656. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  50657. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  50658. msaaTextureDescriptorGPU.sampleCount = samples;
  50659. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  50660. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  50661. }
  50662. textureData.initialized = true;
  50663. textureData.textureDescriptorGPU = textureDescriptorGPU;
  50664. }
  50665. /**
  50666. * Destroys the GPU data for the given texture object.
  50667. *
  50668. * @param {Texture} texture - The texture.
  50669. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  50670. */
  50671. destroyTexture( texture, isDefaultTexture = false ) {
  50672. const backend = this.backend;
  50673. const textureData = backend.get( texture );
  50674. if ( textureData.texture !== undefined && isDefaultTexture === false ) textureData.texture.destroy();
  50675. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  50676. backend.delete( texture );
  50677. }
  50678. /**
  50679. * Generates mipmaps for the given texture.
  50680. *
  50681. * @param {Texture} texture - The texture.
  50682. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  50683. */
  50684. generateMipmaps( texture, encoder = null ) {
  50685. const textureData = this.backend.get( texture );
  50686. if ( texture.isCubeTexture ) {
  50687. for ( let i = 0; i < 6; i ++ ) {
  50688. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i, encoder );
  50689. }
  50690. } else {
  50691. const depth = texture.image.depth || 1;
  50692. for ( let i = 0; i < depth; i ++ ) {
  50693. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i, encoder );
  50694. }
  50695. }
  50696. }
  50697. /**
  50698. * Returns the color buffer representing the color
  50699. * attachment of the default framebuffer.
  50700. *
  50701. * @return {GPUTexture} The color buffer.
  50702. */
  50703. getColorBuffer() {
  50704. const backend = this.backend;
  50705. const canvasTarget = backend.renderer.getCanvasTarget();
  50706. const { width, height } = backend.getDrawingBufferSize();
  50707. const samples = backend.renderer.currentSamples;
  50708. const colorTexture = canvasTarget.colorTexture;
  50709. const colorTextureData = backend.get( colorTexture );
  50710. if ( colorTexture.width === width && colorTexture.height === height && colorTexture.samples === samples ) {
  50711. return colorTextureData.texture;
  50712. }
  50713. // recreate
  50714. let colorBuffer = colorTextureData.texture;
  50715. if ( colorBuffer ) colorBuffer.destroy();
  50716. colorBuffer = backend.device.createTexture( {
  50717. label: 'colorBuffer',
  50718. size: {
  50719. width: width,
  50720. height: height,
  50721. depthOrArrayLayers: 1
  50722. },
  50723. sampleCount: backend.utils.getSampleCount( backend.renderer.currentSamples ),
  50724. format: backend.utils.getPreferredCanvasFormat(),
  50725. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  50726. } );
  50727. //
  50728. colorTexture.source.width = width;
  50729. colorTexture.source.height = height;
  50730. colorTexture.samples = samples;
  50731. colorTextureData.texture = colorBuffer;
  50732. return colorBuffer;
  50733. }
  50734. /**
  50735. * Returns the depth buffer representing the depth
  50736. * attachment of the default framebuffer.
  50737. *
  50738. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  50739. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  50740. * @return {GPUTexture} The depth buffer.
  50741. */
  50742. getDepthBuffer( depth = true, stencil = false ) {
  50743. const backend = this.backend;
  50744. const canvasTarget = backend.renderer.getCanvasTarget();
  50745. const { width, height } = backend.getDrawingBufferSize();
  50746. const samples = backend.renderer.currentSamples;
  50747. const depthTexture = canvasTarget.depthTexture;
  50748. if ( depthTexture.width === width &&
  50749. depthTexture.height === height &&
  50750. depthTexture.samples === samples &&
  50751. depthTexture.depth === depth &&
  50752. depthTexture.stencil === stencil ) {
  50753. return backend.get( depthTexture ).texture;
  50754. }
  50755. //
  50756. const depthTextureGPU = backend.get( depthTexture ).texture;
  50757. let format, type;
  50758. if ( stencil ) {
  50759. format = DepthStencilFormat;
  50760. type = UnsignedInt248Type;
  50761. } else if ( depth ) {
  50762. format = DepthFormat;
  50763. type = UnsignedIntType;
  50764. }
  50765. if ( depthTextureGPU !== undefined ) {
  50766. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type && depthTexture.samples === samples ) {
  50767. return depthTextureGPU;
  50768. }
  50769. this.destroyTexture( depthTexture );
  50770. }
  50771. // recreate
  50772. depthTexture.name = 'depthBuffer';
  50773. depthTexture.format = format;
  50774. depthTexture.type = type;
  50775. depthTexture.image.width = width;
  50776. depthTexture.image.height = height;
  50777. depthTexture.samples = samples;
  50778. this.createTexture( depthTexture, { width, height } );
  50779. return backend.get( depthTexture ).texture;
  50780. }
  50781. /**
  50782. * Uploads the updated texture data to the GPU.
  50783. *
  50784. * @param {Texture} texture - The texture.
  50785. * @param {Object} [options={}] - Optional configuration parameter.
  50786. */
  50787. updateTexture( texture, options ) {
  50788. const textureData = this.backend.get( texture );
  50789. const mipmaps = texture.mipmaps;
  50790. const { textureDescriptorGPU } = textureData;
  50791. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  50792. return;
  50793. // transfer texture data
  50794. if ( texture.isDataTexture ) {
  50795. if ( mipmaps.length > 0 ) {
  50796. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50797. const mipmap = mipmaps[ i ];
  50798. this._copyBufferToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, 0, i );
  50799. }
  50800. } else {
  50801. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  50802. }
  50803. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  50804. for ( let i = 0; i < options.image.depth; i ++ ) {
  50805. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  50806. }
  50807. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  50808. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  50809. } else if ( texture.isCubeTexture ) {
  50810. this._copyCubeMapToTexture( texture, textureData.texture, textureDescriptorGPU );
  50811. } else {
  50812. if ( mipmaps.length > 0 ) {
  50813. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50814. const mipmap = mipmaps[ i ];
  50815. this._copyImageToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha, i );
  50816. }
  50817. } else {
  50818. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  50819. }
  50820. }
  50821. //
  50822. textureData.version = texture.version;
  50823. }
  50824. /**
  50825. * Returns texture data as a typed array.
  50826. *
  50827. * @async
  50828. * @param {Texture} texture - The texture to copy.
  50829. * @param {number} x - The x coordinate of the copy origin.
  50830. * @param {number} y - The y coordinate of the copy origin.
  50831. * @param {number} width - The width of the copy.
  50832. * @param {number} height - The height of the copy.
  50833. * @param {number} faceIndex - The face index.
  50834. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  50835. */
  50836. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  50837. const device = this.backend.device;
  50838. const textureData = this.backend.get( texture );
  50839. const textureGPU = textureData.texture;
  50840. const format = textureData.textureDescriptorGPU.format;
  50841. const bytesPerTexel = this._getBytesPerTexel( format );
  50842. let bytesPerRow = width * bytesPerTexel;
  50843. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  50844. const readBuffer = device.createBuffer(
  50845. {
  50846. size: ( ( height - 1 ) * bytesPerRow ) + ( width * bytesPerTexel ), // see https://github.com/mrdoob/three.js/issues/31658#issuecomment-3229442010
  50847. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  50848. }
  50849. );
  50850. const encoder = device.createCommandEncoder();
  50851. encoder.copyTextureToBuffer(
  50852. {
  50853. texture: textureGPU,
  50854. origin: { x, y, z: faceIndex },
  50855. },
  50856. {
  50857. buffer: readBuffer,
  50858. bytesPerRow: bytesPerRow
  50859. },
  50860. {
  50861. width: width,
  50862. height: height
  50863. }
  50864. );
  50865. const typedArrayType = this._getTypedArrayType( format );
  50866. device.queue.submit( [ encoder.finish() ] );
  50867. await readBuffer.mapAsync( GPUMapMode.READ );
  50868. const buffer = readBuffer.getMappedRange();
  50869. return new typedArrayType( buffer );
  50870. }
  50871. /**
  50872. * Frees all internal resources.
  50873. */
  50874. dispose() {
  50875. this._samplerCache.clear();
  50876. }
  50877. /**
  50878. * Returns the default GPU texture for the given format.
  50879. *
  50880. * @private
  50881. * @param {string} format - The GPU format.
  50882. * @return {GPUTexture} The GPU texture.
  50883. */
  50884. _getDefaultTextureGPU( format ) {
  50885. let defaultTexture = this.defaultTexture[ format ];
  50886. if ( defaultTexture === undefined ) {
  50887. const texture = new Texture();
  50888. texture.minFilter = NearestFilter;
  50889. texture.magFilter = NearestFilter;
  50890. this.createTexture( texture, { width: 1, height: 1, format } );
  50891. this.defaultTexture[ format ] = defaultTexture = texture;
  50892. }
  50893. return this.backend.get( defaultTexture ).texture;
  50894. }
  50895. /**
  50896. * Returns the default GPU cube texture for the given format.
  50897. *
  50898. * @private
  50899. * @param {string} format - The GPU format.
  50900. * @return {GPUTexture} The GPU texture.
  50901. */
  50902. _getDefaultCubeTextureGPU( format ) {
  50903. let defaultCubeTexture = this.defaultTexture[ format ];
  50904. if ( defaultCubeTexture === undefined ) {
  50905. const texture = new CubeTexture();
  50906. texture.minFilter = NearestFilter;
  50907. texture.magFilter = NearestFilter;
  50908. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  50909. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  50910. }
  50911. return this.backend.get( defaultCubeTexture ).texture;
  50912. }
  50913. /**
  50914. * Uploads cube texture image data to the GPU memory.
  50915. *
  50916. * @private
  50917. * @param {CubeTexture} texture - The cube texture.
  50918. * @param {GPUTexture} textureGPU - The GPU texture.
  50919. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  50920. */
  50921. _copyCubeMapToTexture( texture, textureGPU, textureDescriptorGPU ) {
  50922. const images = texture.images;
  50923. const mipmaps = texture.mipmaps;
  50924. for ( let i = 0; i < 6; i ++ ) {
  50925. const image = images[ i ];
  50926. const flipIndex = texture.flipY === true ? _flipMap[ i ] : i;
  50927. if ( image.isDataTexture ) {
  50928. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY );
  50929. } else {
  50930. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha );
  50931. }
  50932. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50933. const mipmap = mipmaps[ j ];
  50934. const image = mipmap.images[ i ];
  50935. if ( image.isDataTexture ) {
  50936. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, 0, j + 1 );
  50937. } else {
  50938. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha, j + 1 );
  50939. }
  50940. }
  50941. }
  50942. }
  50943. /**
  50944. * Uploads texture image data to the GPU memory.
  50945. *
  50946. * @private
  50947. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  50948. * @param {GPUTexture} textureGPU - The GPU texture.
  50949. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  50950. * @param {number} originDepth - The origin depth.
  50951. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  50952. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  50953. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  50954. */
  50955. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha, mipLevel = 0 ) {
  50956. const device = this.backend.device;
  50957. const width = ( mipLevel > 0 ) ? image.width : textureDescriptorGPU.size.width;
  50958. const height = ( mipLevel > 0 ) ? image.height : textureDescriptorGPU.size.height;
  50959. device.queue.copyExternalImageToTexture(
  50960. {
  50961. source: image,
  50962. flipY: flipY
  50963. }, {
  50964. texture: textureGPU,
  50965. mipLevel: mipLevel,
  50966. origin: { x: 0, y: 0, z: originDepth },
  50967. premultipliedAlpha: premultiplyAlpha
  50968. }, {
  50969. width: width,
  50970. height: height,
  50971. depthOrArrayLayers: 1
  50972. }
  50973. );
  50974. }
  50975. /**
  50976. * Returns the pass utils singleton.
  50977. *
  50978. * @private
  50979. * @return {WebGPUTexturePassUtils} The utils instance.
  50980. */
  50981. _getPassUtils() {
  50982. let passUtils = this._passUtils;
  50983. if ( passUtils === null ) {
  50984. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  50985. }
  50986. return passUtils;
  50987. }
  50988. /**
  50989. * Generates mipmaps for the given GPU texture.
  50990. *
  50991. * @private
  50992. * @param {GPUTexture} textureGPU - The GPU texture object.
  50993. * @param {Object} textureDescriptorGPU - The texture descriptor.
  50994. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  50995. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  50996. */
  50997. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0, encoder = null ) {
  50998. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer, encoder );
  50999. }
  51000. /**
  51001. * Flip the contents of the given GPU texture along its vertical axis.
  51002. *
  51003. * @private
  51004. * @param {GPUTexture} textureGPU - The GPU texture object.
  51005. * @param {Object} textureDescriptorGPU - The texture descriptor.
  51006. * @param {number} [originDepth=0] - The origin depth.
  51007. */
  51008. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  51009. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  51010. }
  51011. /**
  51012. * Uploads texture buffer data to the GPU memory.
  51013. *
  51014. * @private
  51015. * @param {Object} image - An object defining the image buffer data.
  51016. * @param {GPUTexture} textureGPU - The GPU texture.
  51017. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51018. * @param {number} originDepth - The origin depth.
  51019. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  51020. * @param {number} [depth=0] - The depth offset when copying array or 3D texture data.
  51021. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  51022. */
  51023. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0, mipLevel = 0 ) {
  51024. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  51025. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  51026. const device = this.backend.device;
  51027. const data = image.data;
  51028. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  51029. const bytesPerRow = image.width * bytesPerTexel;
  51030. device.queue.writeTexture(
  51031. {
  51032. texture: textureGPU,
  51033. mipLevel: mipLevel,
  51034. origin: { x: 0, y: 0, z: originDepth }
  51035. },
  51036. data,
  51037. {
  51038. offset: image.width * image.height * bytesPerTexel * depth,
  51039. bytesPerRow
  51040. },
  51041. {
  51042. width: image.width,
  51043. height: image.height,
  51044. depthOrArrayLayers: 1
  51045. } );
  51046. if ( flipY === true ) {
  51047. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  51048. }
  51049. }
  51050. /**
  51051. * Uploads compressed texture data to the GPU memory.
  51052. *
  51053. * @private
  51054. * @param {Array<Object>} mipmaps - An array with mipmap data.
  51055. * @param {GPUTexture} textureGPU - The GPU texture.
  51056. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51057. */
  51058. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  51059. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  51060. const device = this.backend.device;
  51061. const blockData = this._getBlockData( textureDescriptorGPU.format );
  51062. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  51063. for ( let i = 0; i < mipmaps.length; i ++ ) {
  51064. const mipmap = mipmaps[ i ];
  51065. const width = mipmap.width;
  51066. const height = mipmap.height;
  51067. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  51068. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  51069. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  51070. for ( let j = 0; j < depth; j ++ ) {
  51071. device.queue.writeTexture(
  51072. {
  51073. texture: textureGPU,
  51074. mipLevel: i,
  51075. origin: { x: 0, y: 0, z: j }
  51076. },
  51077. mipmap.data,
  51078. {
  51079. offset: j * bytesPerImage,
  51080. bytesPerRow,
  51081. rowsPerImage: Math.ceil( height / blockData.height )
  51082. },
  51083. {
  51084. width: Math.ceil( width / blockData.width ) * blockData.width,
  51085. height: Math.ceil( height / blockData.height ) * blockData.height,
  51086. depthOrArrayLayers: 1
  51087. }
  51088. );
  51089. }
  51090. }
  51091. }
  51092. /**
  51093. * This method is only relevant for compressed texture formats. It returns a block
  51094. * data descriptor for the given GPU compressed texture format.
  51095. *
  51096. * @private
  51097. * @param {string} format - The GPU compressed texture format.
  51098. * @return {Object} The block data descriptor.
  51099. */
  51100. _getBlockData( format ) {
  51101. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  51102. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  51103. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  51104. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  51105. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  51106. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  51107. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  51108. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  51109. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  51110. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  51111. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  51112. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  51113. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  51114. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  51115. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  51116. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  51117. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  51118. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  51119. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  51120. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  51121. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  51122. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  51123. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  51124. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  51125. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  51126. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  51127. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  51128. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  51129. }
  51130. /**
  51131. * Converts the three.js uv wrapping constants to GPU address mode constants.
  51132. *
  51133. * @private
  51134. * @param {number} value - The three.js constant defining a uv wrapping mode.
  51135. * @return {string} The GPU address mode.
  51136. */
  51137. _convertAddressMode( value ) {
  51138. let addressMode = GPUAddressMode.ClampToEdge;
  51139. if ( value === RepeatWrapping ) {
  51140. addressMode = GPUAddressMode.Repeat;
  51141. } else if ( value === MirroredRepeatWrapping ) {
  51142. addressMode = GPUAddressMode.MirrorRepeat;
  51143. }
  51144. return addressMode;
  51145. }
  51146. /**
  51147. * Converts the three.js filter constants to GPU filter constants.
  51148. *
  51149. * @private
  51150. * @param {number} value - The three.js constant defining a filter mode.
  51151. * @return {string} The GPU filter mode.
  51152. */
  51153. _convertFilterMode( value ) {
  51154. let filterMode = GPUFilterMode.Linear;
  51155. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  51156. filterMode = GPUFilterMode.Nearest;
  51157. }
  51158. return filterMode;
  51159. }
  51160. /**
  51161. * Returns the bytes-per-texel value for the given GPU texture format.
  51162. *
  51163. * @private
  51164. * @param {string} format - The GPU texture format.
  51165. * @return {number} The bytes-per-texel.
  51166. */
  51167. _getBytesPerTexel( format ) {
  51168. // 8-bit formats
  51169. if ( format === GPUTextureFormat.R8Unorm ||
  51170. format === GPUTextureFormat.R8Snorm ||
  51171. format === GPUTextureFormat.R8Uint ||
  51172. format === GPUTextureFormat.R8Sint ) return 1;
  51173. // 16-bit formats
  51174. if ( format === GPUTextureFormat.R16Uint ||
  51175. format === GPUTextureFormat.R16Sint ||
  51176. format === GPUTextureFormat.R16Float ||
  51177. format === GPUTextureFormat.RG8Unorm ||
  51178. format === GPUTextureFormat.RG8Snorm ||
  51179. format === GPUTextureFormat.RG8Uint ||
  51180. format === GPUTextureFormat.RG8Sint ) return 2;
  51181. // 32-bit formats
  51182. if ( format === GPUTextureFormat.R32Uint ||
  51183. format === GPUTextureFormat.R32Sint ||
  51184. format === GPUTextureFormat.R32Float ||
  51185. format === GPUTextureFormat.RG16Uint ||
  51186. format === GPUTextureFormat.RG16Sint ||
  51187. format === GPUTextureFormat.RG16Float ||
  51188. format === GPUTextureFormat.RGBA8Unorm ||
  51189. format === GPUTextureFormat.RGBA8UnormSRGB ||
  51190. format === GPUTextureFormat.RGBA8Snorm ||
  51191. format === GPUTextureFormat.RGBA8Uint ||
  51192. format === GPUTextureFormat.RGBA8Sint ||
  51193. format === GPUTextureFormat.BGRA8Unorm ||
  51194. format === GPUTextureFormat.BGRA8UnormSRGB ||
  51195. // Packed 32-bit formats
  51196. format === GPUTextureFormat.RGB9E5UFloat ||
  51197. format === GPUTextureFormat.RGB10A2Unorm ||
  51198. format === GPUTextureFormat.RG11B10UFloat ||
  51199. format === GPUTextureFormat.Depth32Float ||
  51200. format === GPUTextureFormat.Depth24Plus ||
  51201. format === GPUTextureFormat.Depth24PlusStencil8 ||
  51202. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  51203. // 64-bit formats
  51204. if ( format === GPUTextureFormat.RG32Uint ||
  51205. format === GPUTextureFormat.RG32Sint ||
  51206. format === GPUTextureFormat.RG32Float ||
  51207. format === GPUTextureFormat.RGBA16Uint ||
  51208. format === GPUTextureFormat.RGBA16Sint ||
  51209. format === GPUTextureFormat.RGBA16Float ) return 8;
  51210. // 128-bit formats
  51211. if ( format === GPUTextureFormat.RGBA32Uint ||
  51212. format === GPUTextureFormat.RGBA32Sint ||
  51213. format === GPUTextureFormat.RGBA32Float ) return 16;
  51214. }
  51215. /**
  51216. * Returns the corresponding typed array type for the given GPU texture format.
  51217. *
  51218. * @private
  51219. * @param {string} format - The GPU texture format.
  51220. * @return {TypedArray.constructor} The typed array type.
  51221. */
  51222. _getTypedArrayType( format ) {
  51223. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  51224. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  51225. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  51226. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  51227. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  51228. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  51229. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  51230. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  51231. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  51232. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  51233. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return Uint8Array;
  51234. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  51235. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  51236. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  51237. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  51238. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  51239. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  51240. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  51241. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  51242. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  51243. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  51244. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  51245. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  51246. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  51247. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  51248. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  51249. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  51250. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  51251. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  51252. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  51253. if ( format === GPUTextureFormat.BGRA8Unorm || format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  51254. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  51255. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  51256. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  51257. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  51258. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  51259. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  51260. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  51261. }
  51262. /**
  51263. * Returns the GPU dimensions for the given texture.
  51264. *
  51265. * @private
  51266. * @param {Texture} texture - The texture.
  51267. * @return {string} The GPU dimension.
  51268. */
  51269. _getDimension( texture ) {
  51270. let dimension;
  51271. if ( texture.is3DTexture || texture.isData3DTexture ) {
  51272. dimension = GPUTextureDimension.ThreeD;
  51273. } else {
  51274. dimension = GPUTextureDimension.TwoD;
  51275. }
  51276. return dimension;
  51277. }
  51278. }
  51279. /**
  51280. * Returns the GPU format for the given texture.
  51281. *
  51282. * @param {Texture} texture - The texture.
  51283. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  51284. * It is not necessary to apply the device for most formats.
  51285. * @return {string} The GPU format.
  51286. */
  51287. function getFormat( texture, device = null ) {
  51288. const format = texture.format;
  51289. const type = texture.type;
  51290. const colorSpace = texture.colorSpace;
  51291. const transfer = ColorManagement.getTransfer( colorSpace );
  51292. let formatGPU;
  51293. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  51294. switch ( format ) {
  51295. case RGB_S3TC_DXT1_Format:
  51296. case RGBA_S3TC_DXT1_Format:
  51297. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  51298. break;
  51299. case RGBA_S3TC_DXT3_Format:
  51300. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  51301. break;
  51302. case RGBA_S3TC_DXT5_Format:
  51303. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  51304. break;
  51305. case RED_RGTC1_Format:
  51306. formatGPU = GPUTextureFormat.BC4RUnorm;
  51307. break;
  51308. case SIGNED_RED_RGTC1_Format:
  51309. formatGPU = GPUTextureFormat.BC4RSnorm;
  51310. break;
  51311. case RED_GREEN_RGTC2_Format:
  51312. formatGPU = GPUTextureFormat.BC5RGUnorm;
  51313. break;
  51314. case SIGNED_RED_GREEN_RGTC2_Format:
  51315. formatGPU = GPUTextureFormat.BC5RGSnorm;
  51316. break;
  51317. case RGBA_BPTC_Format:
  51318. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC7RGBAUnormSRGB : GPUTextureFormat.BC7RGBAUnorm;
  51319. break;
  51320. case RGB_ETC2_Format:
  51321. case RGB_ETC1_Format:
  51322. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  51323. break;
  51324. case RGBA_ETC2_EAC_Format:
  51325. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  51326. break;
  51327. case R11_EAC_Format:
  51328. formatGPU = GPUTextureFormat.EACR11Unorm;
  51329. break;
  51330. case SIGNED_R11_EAC_Format:
  51331. formatGPU = GPUTextureFormat.EACR11Snorm;
  51332. break;
  51333. case RG11_EAC_Format:
  51334. formatGPU = GPUTextureFormat.EACRG11Unorm;
  51335. break;
  51336. case SIGNED_RG11_EAC_Format:
  51337. formatGPU = GPUTextureFormat.EACRG11Snorm;
  51338. break;
  51339. case RGBA_ASTC_4x4_Format:
  51340. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  51341. break;
  51342. case RGBA_ASTC_5x4_Format:
  51343. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  51344. break;
  51345. case RGBA_ASTC_5x5_Format:
  51346. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  51347. break;
  51348. case RGBA_ASTC_6x5_Format:
  51349. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  51350. break;
  51351. case RGBA_ASTC_6x6_Format:
  51352. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  51353. break;
  51354. case RGBA_ASTC_8x5_Format:
  51355. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  51356. break;
  51357. case RGBA_ASTC_8x6_Format:
  51358. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  51359. break;
  51360. case RGBA_ASTC_8x8_Format:
  51361. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  51362. break;
  51363. case RGBA_ASTC_10x5_Format:
  51364. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  51365. break;
  51366. case RGBA_ASTC_10x6_Format:
  51367. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  51368. break;
  51369. case RGBA_ASTC_10x8_Format:
  51370. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  51371. break;
  51372. case RGBA_ASTC_10x10_Format:
  51373. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  51374. break;
  51375. case RGBA_ASTC_12x10_Format:
  51376. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  51377. break;
  51378. case RGBA_ASTC_12x12_Format:
  51379. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  51380. break;
  51381. case RGBAFormat:
  51382. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  51383. break;
  51384. default:
  51385. error( 'WebGPURenderer: Unsupported texture format.', format );
  51386. }
  51387. } else {
  51388. switch ( format ) {
  51389. case RGBAFormat:
  51390. switch ( type ) {
  51391. case ByteType:
  51392. formatGPU = GPUTextureFormat.RGBA8Snorm;
  51393. break;
  51394. case ShortType:
  51395. formatGPU = GPUTextureFormat.RGBA16Sint;
  51396. break;
  51397. case UnsignedShortType:
  51398. formatGPU = GPUTextureFormat.RGBA16Uint;
  51399. break;
  51400. case UnsignedIntType:
  51401. formatGPU = GPUTextureFormat.RGBA32Uint;
  51402. break;
  51403. case IntType:
  51404. formatGPU = GPUTextureFormat.RGBA32Sint;
  51405. break;
  51406. case UnsignedByteType:
  51407. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  51408. break;
  51409. case HalfFloatType:
  51410. formatGPU = GPUTextureFormat.RGBA16Float;
  51411. break;
  51412. case FloatType:
  51413. formatGPU = GPUTextureFormat.RGBA32Float;
  51414. break;
  51415. default:
  51416. error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  51417. }
  51418. break;
  51419. case RGBFormat:
  51420. switch ( type ) {
  51421. case UnsignedInt5999Type:
  51422. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  51423. break;
  51424. case UnsignedInt101111Type:
  51425. formatGPU = GPUTextureFormat.RG11B10UFloat;
  51426. break;
  51427. default:
  51428. error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  51429. }
  51430. break;
  51431. case RedFormat:
  51432. switch ( type ) {
  51433. case ByteType:
  51434. formatGPU = GPUTextureFormat.R8Snorm;
  51435. break;
  51436. case ShortType:
  51437. formatGPU = GPUTextureFormat.R16Sint;
  51438. break;
  51439. case UnsignedShortType:
  51440. formatGPU = GPUTextureFormat.R16Uint;
  51441. break;
  51442. case UnsignedIntType:
  51443. formatGPU = GPUTextureFormat.R32Uint;
  51444. break;
  51445. case IntType:
  51446. formatGPU = GPUTextureFormat.R32Sint;
  51447. break;
  51448. case UnsignedByteType:
  51449. formatGPU = GPUTextureFormat.R8Unorm;
  51450. break;
  51451. case HalfFloatType:
  51452. formatGPU = GPUTextureFormat.R16Float;
  51453. break;
  51454. case FloatType:
  51455. formatGPU = GPUTextureFormat.R32Float;
  51456. break;
  51457. default:
  51458. error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  51459. }
  51460. break;
  51461. case RGFormat:
  51462. switch ( type ) {
  51463. case ByteType:
  51464. formatGPU = GPUTextureFormat.RG8Snorm;
  51465. break;
  51466. case ShortType:
  51467. formatGPU = GPUTextureFormat.RG16Sint;
  51468. break;
  51469. case UnsignedShortType:
  51470. formatGPU = GPUTextureFormat.RG16Uint;
  51471. break;
  51472. case UnsignedIntType:
  51473. formatGPU = GPUTextureFormat.RG32Uint;
  51474. break;
  51475. case IntType:
  51476. formatGPU = GPUTextureFormat.RG32Sint;
  51477. break;
  51478. case UnsignedByteType:
  51479. formatGPU = GPUTextureFormat.RG8Unorm;
  51480. break;
  51481. case HalfFloatType:
  51482. formatGPU = GPUTextureFormat.RG16Float;
  51483. break;
  51484. case FloatType:
  51485. formatGPU = GPUTextureFormat.RG32Float;
  51486. break;
  51487. default:
  51488. error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  51489. }
  51490. break;
  51491. case DepthFormat:
  51492. switch ( type ) {
  51493. case UnsignedShortType:
  51494. formatGPU = GPUTextureFormat.Depth16Unorm;
  51495. break;
  51496. case UnsignedIntType:
  51497. formatGPU = GPUTextureFormat.Depth24Plus;
  51498. break;
  51499. case FloatType:
  51500. formatGPU = GPUTextureFormat.Depth32Float;
  51501. break;
  51502. default:
  51503. error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  51504. }
  51505. break;
  51506. case DepthStencilFormat:
  51507. switch ( type ) {
  51508. case UnsignedInt248Type:
  51509. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  51510. break;
  51511. case FloatType:
  51512. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  51513. error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  51514. }
  51515. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  51516. break;
  51517. default:
  51518. error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  51519. }
  51520. break;
  51521. case RedIntegerFormat:
  51522. switch ( type ) {
  51523. case IntType:
  51524. formatGPU = GPUTextureFormat.R32Sint;
  51525. break;
  51526. case UnsignedIntType:
  51527. formatGPU = GPUTextureFormat.R32Uint;
  51528. break;
  51529. default:
  51530. error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  51531. }
  51532. break;
  51533. case RGIntegerFormat:
  51534. switch ( type ) {
  51535. case IntType:
  51536. formatGPU = GPUTextureFormat.RG32Sint;
  51537. break;
  51538. case UnsignedIntType:
  51539. formatGPU = GPUTextureFormat.RG32Uint;
  51540. break;
  51541. default:
  51542. error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  51543. }
  51544. break;
  51545. case RGBAIntegerFormat:
  51546. switch ( type ) {
  51547. case IntType:
  51548. formatGPU = GPUTextureFormat.RGBA32Sint;
  51549. break;
  51550. case UnsignedIntType:
  51551. formatGPU = GPUTextureFormat.RGBA32Uint;
  51552. break;
  51553. default:
  51554. error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  51555. }
  51556. break;
  51557. default:
  51558. error( 'WebGPURenderer: Unsupported texture format.', format );
  51559. }
  51560. }
  51561. return formatGPU;
  51562. }
  51563. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  51564. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  51565. const wgslTypeLib$1 = {
  51566. 'f32': 'float',
  51567. 'i32': 'int',
  51568. 'u32': 'uint',
  51569. 'bool': 'bool',
  51570. 'vec2<f32>': 'vec2',
  51571. 'vec2<i32>': 'ivec2',
  51572. 'vec2<u32>': 'uvec2',
  51573. 'vec2<bool>': 'bvec2',
  51574. 'vec2f': 'vec2',
  51575. 'vec2i': 'ivec2',
  51576. 'vec2u': 'uvec2',
  51577. 'vec2b': 'bvec2',
  51578. 'vec3<f32>': 'vec3',
  51579. 'vec3<i32>': 'ivec3',
  51580. 'vec3<u32>': 'uvec3',
  51581. 'vec3<bool>': 'bvec3',
  51582. 'vec3f': 'vec3',
  51583. 'vec3i': 'ivec3',
  51584. 'vec3u': 'uvec3',
  51585. 'vec3b': 'bvec3',
  51586. 'vec4<f32>': 'vec4',
  51587. 'vec4<i32>': 'ivec4',
  51588. 'vec4<u32>': 'uvec4',
  51589. 'vec4<bool>': 'bvec4',
  51590. 'vec4f': 'vec4',
  51591. 'vec4i': 'ivec4',
  51592. 'vec4u': 'uvec4',
  51593. 'vec4b': 'bvec4',
  51594. 'mat2x2<f32>': 'mat2',
  51595. 'mat2x2f': 'mat2',
  51596. 'mat3x3<f32>': 'mat3',
  51597. 'mat3x3f': 'mat3',
  51598. 'mat4x4<f32>': 'mat4',
  51599. 'mat4x4f': 'mat4',
  51600. 'sampler': 'sampler',
  51601. 'texture_1d': 'texture',
  51602. 'texture_2d': 'texture',
  51603. 'texture_2d_array': 'texture',
  51604. 'texture_multisampled_2d': 'cubeTexture',
  51605. 'texture_depth_2d': 'depthTexture',
  51606. 'texture_depth_2d_array': 'depthTexture',
  51607. 'texture_depth_multisampled_2d': 'depthTexture',
  51608. 'texture_depth_cube': 'depthTexture',
  51609. 'texture_depth_cube_array': 'depthTexture',
  51610. 'texture_3d': 'texture3D',
  51611. 'texture_cube': 'cubeTexture',
  51612. 'texture_cube_array': 'cubeTexture',
  51613. 'texture_storage_1d': 'storageTexture',
  51614. 'texture_storage_2d': 'storageTexture',
  51615. 'texture_storage_2d_array': 'storageTexture',
  51616. 'texture_storage_3d': 'storageTexture'
  51617. };
  51618. const parse = ( source ) => {
  51619. source = source.trim();
  51620. const declaration = source.match( declarationRegexp );
  51621. if ( declaration !== null && declaration.length === 4 ) {
  51622. const inputsCode = declaration[ 2 ];
  51623. const propsMatches = [];
  51624. let match = null;
  51625. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  51626. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  51627. }
  51628. // Process matches to correctly pair names and types
  51629. const inputs = [];
  51630. for ( let i = 0; i < propsMatches.length; i ++ ) {
  51631. const { name, type } = propsMatches[ i ];
  51632. let resolvedType = type;
  51633. if ( resolvedType.startsWith( 'ptr' ) ) {
  51634. resolvedType = 'pointer';
  51635. } else {
  51636. if ( resolvedType.startsWith( 'texture' ) ) {
  51637. resolvedType = type.split( '<' )[ 0 ];
  51638. }
  51639. resolvedType = wgslTypeLib$1[ resolvedType ];
  51640. }
  51641. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  51642. }
  51643. const blockCode = source.substring( declaration[ 0 ].length );
  51644. const outputType = declaration[ 3 ] || 'void';
  51645. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  51646. const type = wgslTypeLib$1[ outputType ] || outputType;
  51647. return {
  51648. type,
  51649. inputs,
  51650. name,
  51651. inputsCode,
  51652. blockCode,
  51653. outputType
  51654. };
  51655. } else {
  51656. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  51657. }
  51658. };
  51659. /**
  51660. * This class represents a WSL node function.
  51661. *
  51662. * @augments NodeFunction
  51663. */
  51664. class WGSLNodeFunction extends NodeFunction {
  51665. /**
  51666. * Constructs a new WGSL node function.
  51667. *
  51668. * @param {string} source - The WGSL source.
  51669. */
  51670. constructor( source ) {
  51671. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  51672. super( type, inputs, name );
  51673. this.inputsCode = inputsCode;
  51674. this.blockCode = blockCode;
  51675. this.outputType = outputType;
  51676. }
  51677. /**
  51678. * This method returns the WGSL code of the node function.
  51679. *
  51680. * @param {string} [name=this.name] - The function's name.
  51681. * @return {string} The shader code.
  51682. */
  51683. getCode( name = this.name ) {
  51684. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  51685. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  51686. }
  51687. }
  51688. /**
  51689. * A WGSL node parser.
  51690. *
  51691. * @augments NodeParser
  51692. */
  51693. class WGSLNodeParser extends NodeParser {
  51694. /**
  51695. * The method parses the given WGSL code an returns a node function.
  51696. *
  51697. * @param {string} source - The WGSL code.
  51698. * @return {WGSLNodeFunction} A node function.
  51699. */
  51700. parseFunction( source ) {
  51701. return new WGSLNodeFunction( source );
  51702. }
  51703. }
  51704. const accessNames = {
  51705. [ NodeAccess.READ_ONLY ]: 'read',
  51706. [ NodeAccess.WRITE_ONLY ]: 'write',
  51707. [ NodeAccess.READ_WRITE ]: 'read_write'
  51708. };
  51709. const wrapNames = {
  51710. [ RepeatWrapping ]: 'repeat',
  51711. [ ClampToEdgeWrapping ]: 'clamp',
  51712. [ MirroredRepeatWrapping ]: 'mirror'
  51713. };
  51714. const gpuShaderStageLib = {
  51715. 'vertex': GPUShaderStage.VERTEX,
  51716. 'fragment': GPUShaderStage.FRAGMENT,
  51717. 'compute': GPUShaderStage.COMPUTE
  51718. };
  51719. const supports = {
  51720. instance: true,
  51721. swizzleAssign: false,
  51722. storageBuffer: true
  51723. };
  51724. const wgslFnOpLib = {
  51725. '^^': 'tsl_xor'
  51726. };
  51727. const wgslTypeLib = {
  51728. float: 'f32',
  51729. int: 'i32',
  51730. uint: 'u32',
  51731. bool: 'bool',
  51732. color: 'vec3<f32>',
  51733. vec2: 'vec2<f32>',
  51734. ivec2: 'vec2<i32>',
  51735. uvec2: 'vec2<u32>',
  51736. bvec2: 'vec2<bool>',
  51737. vec3: 'vec3<f32>',
  51738. ivec3: 'vec3<i32>',
  51739. uvec3: 'vec3<u32>',
  51740. bvec3: 'vec3<bool>',
  51741. vec4: 'vec4<f32>',
  51742. ivec4: 'vec4<i32>',
  51743. uvec4: 'vec4<u32>',
  51744. bvec4: 'vec4<bool>',
  51745. mat2: 'mat2x2<f32>',
  51746. mat3: 'mat3x3<f32>',
  51747. mat4: 'mat4x4<f32>'
  51748. };
  51749. const wgslCodeCache = {};
  51750. const wgslPolyfill = {
  51751. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  51752. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  51753. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  51754. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  51755. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  51756. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  51757. 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 ); }' ),
  51758. 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 ); }' ),
  51759. 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 ); }' ),
  51760. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  51761. 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 ); }' ),
  51762. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  51763. biquadraticTexture: new CodeNode( /* wgsl */`
  51764. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  51765. let res = vec2f( iRes );
  51766. let uvScaled = coord * res;
  51767. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  51768. // https://www.shadertoy.com/view/WtyXRy
  51769. let uv = uvWrapping - 0.5;
  51770. let iuv = floor( uv );
  51771. let f = fract( uv );
  51772. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  51773. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  51774. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  51775. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  51776. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  51777. }
  51778. ` )
  51779. };
  51780. const wgslMethods = {
  51781. dFdx: 'dpdx',
  51782. dFdy: '- dpdy',
  51783. mod_float: 'tsl_mod_float',
  51784. mod_vec2: 'tsl_mod_vec2',
  51785. mod_vec3: 'tsl_mod_vec3',
  51786. mod_vec4: 'tsl_mod_vec4',
  51787. equals_bool: 'tsl_equals_bool',
  51788. equals_bvec2: 'tsl_equals_bvec2',
  51789. equals_bvec3: 'tsl_equals_bvec3',
  51790. equals_bvec4: 'tsl_equals_bvec4',
  51791. inversesqrt: 'inverseSqrt',
  51792. bitcast: 'bitcast<f32>'
  51793. };
  51794. //
  51795. let diagnostics = '';
  51796. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  51797. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  51798. }
  51799. /**
  51800. * A node builder targeting WGSL.
  51801. *
  51802. * This module generates WGSL shader code from node materials and also
  51803. * generates the respective bindings and vertex buffer definitions. These
  51804. * data are later used by the renderer to create render and compute pipelines
  51805. * for render objects.
  51806. *
  51807. * @augments NodeBuilder
  51808. */
  51809. class WGSLNodeBuilder extends NodeBuilder {
  51810. /**
  51811. * Constructs a new WGSL node builder renderer.
  51812. *
  51813. * @param {Object3D} object - The 3D object.
  51814. * @param {Renderer} renderer - The renderer.
  51815. */
  51816. constructor( object, renderer ) {
  51817. super( object, renderer, new WGSLNodeParser() );
  51818. /**
  51819. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  51820. * another dictionary which manages UBOs per group ('render','frame','object').
  51821. *
  51822. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  51823. */
  51824. this.uniformGroups = {};
  51825. /**
  51826. * A dictionary that holds for each shader stage a Map of builtins.
  51827. *
  51828. * @type {Object<string,Map<string,Object>>}
  51829. */
  51830. this.builtins = {};
  51831. /**
  51832. * A dictionary that holds for each shader stage a Set of directives.
  51833. *
  51834. * @type {Object<string,Set<string>>}
  51835. */
  51836. this.directives = {};
  51837. /**
  51838. * A map for managing scope arrays. Only relevant for when using
  51839. * {@link WorkgroupInfoNode} in context of compute shaders.
  51840. *
  51841. * @type {Map<string,Object>}
  51842. */
  51843. this.scopedArrays = new Map();
  51844. }
  51845. /**
  51846. * Generates the WGSL snippet for sampled textures.
  51847. *
  51848. * @private
  51849. * @param {Texture} texture - The texture.
  51850. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51851. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51852. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  51853. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  51854. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51855. * @return {string} The WGSL snippet.
  51856. */
  51857. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  51858. if ( shaderStage === 'fragment' ) {
  51859. if ( depthSnippet ) {
  51860. if ( offsetSnippet ) {
  51861. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  51862. }
  51863. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  51864. } else {
  51865. if ( offsetSnippet ) {
  51866. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  51867. }
  51868. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  51869. }
  51870. } else {
  51871. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  51872. }
  51873. }
  51874. /**
  51875. * Generates the WGSL snippet when sampling textures with explicit mip level.
  51876. *
  51877. * @private
  51878. * @param {Texture} texture - The texture.
  51879. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51880. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51881. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  51882. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  51883. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  51884. * @return {string} The WGSL snippet.
  51885. */
  51886. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  51887. if ( this.isUnfilterable( texture ) === false ) {
  51888. if ( offsetSnippet ) {
  51889. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  51890. }
  51891. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  51892. } else if ( this.isFilteredTexture( texture ) ) {
  51893. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  51894. } else {
  51895. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  51896. }
  51897. }
  51898. /**
  51899. * Generates a wrap function used in context of textures.
  51900. *
  51901. * @param {Texture} texture - The texture to generate the function for.
  51902. * @return {string} The name of the generated function.
  51903. */
  51904. generateWrapFunction( texture ) {
  51905. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.is3DTexture || texture.isData3DTexture ? '3d' : '2d' }T`;
  51906. let nodeCode = wgslCodeCache[ functionName ];
  51907. if ( nodeCode === undefined ) {
  51908. const includes = [];
  51909. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  51910. const coordType = texture.is3DTexture || texture.isData3DTexture ? 'vec3f' : 'vec2f';
  51911. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  51912. const addWrapSnippet = ( wrap, axis ) => {
  51913. if ( wrap === RepeatWrapping ) {
  51914. includes.push( wgslPolyfill.repeatWrapping_float );
  51915. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  51916. } else if ( wrap === ClampToEdgeWrapping ) {
  51917. includes.push( wgslPolyfill.clampWrapping_float );
  51918. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  51919. } else if ( wrap === MirroredRepeatWrapping ) {
  51920. includes.push( wgslPolyfill.mirrorWrapping_float );
  51921. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  51922. } else {
  51923. code += `\t\tcoord.${ axis }`;
  51924. warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  51925. }
  51926. };
  51927. addWrapSnippet( texture.wrapS, 'x' );
  51928. code += ',\n';
  51929. addWrapSnippet( texture.wrapT, 'y' );
  51930. if ( texture.is3DTexture || texture.isData3DTexture ) {
  51931. code += ',\n';
  51932. addWrapSnippet( texture.wrapR, 'z' );
  51933. }
  51934. code += '\n\t);\n\n}\n';
  51935. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  51936. }
  51937. nodeCode.build( this );
  51938. return functionName;
  51939. }
  51940. /**
  51941. * Generates the array declaration string.
  51942. *
  51943. * @param {string} type - The type.
  51944. * @param {?number} [count] - The count.
  51945. * @return {string} The generated value as a shader string.
  51946. */
  51947. generateArrayDeclaration( type, count ) {
  51948. return `array< ${ this.getType( type ) }, ${ count } >`;
  51949. }
  51950. /**
  51951. * Generates a WGSL variable that holds the texture dimension of the given texture.
  51952. * It also returns information about the number of layers (elements) of an arrayed
  51953. * texture as well as the cube face count of cube textures.
  51954. *
  51955. * @param {Texture} texture - The texture to generate the function for.
  51956. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  51957. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  51958. * @return {string} The name of the dimension variable.
  51959. */
  51960. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  51961. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  51962. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  51963. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  51964. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  51965. let textureDimensionsParams;
  51966. let dimensionType;
  51967. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  51968. const isMultisampled = primarySamples > 1;
  51969. if ( texture.is3DTexture || texture.isData3DTexture ) {
  51970. dimensionType = 'vec3<u32>';
  51971. } else {
  51972. // Regular 2D textures, depth textures, etc.
  51973. dimensionType = 'vec2<u32>';
  51974. }
  51975. // Build parameters string based on texture type and multisampling
  51976. if ( isMultisampled || texture.isStorageTexture ) {
  51977. textureDimensionsParams = textureProperty;
  51978. } else {
  51979. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  51980. }
  51981. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  51982. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  51983. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.is3DTexture || texture.isData3DTexture ) {
  51984. textureData.arrayLayerCount = new VarNode(
  51985. new ExpressionNode(
  51986. `textureNumLayers(${textureProperty})`,
  51987. 'u32'
  51988. )
  51989. );
  51990. }
  51991. // For cube textures, we know it's always 6 faces
  51992. if ( texture.isTextureCube ) {
  51993. textureData.cubeFaceCount = new VarNode(
  51994. new ExpressionNode( '6u', 'u32' )
  51995. );
  51996. }
  51997. }
  51998. return textureDimensionNode.build( this );
  51999. }
  52000. /**
  52001. * Generates the WGSL snippet for a manual filtered texture.
  52002. *
  52003. * @param {Texture} texture - The texture.
  52004. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52005. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52006. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52007. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52008. * @return {string} The WGSL snippet.
  52009. */
  52010. generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet = '0u' ) {
  52011. this._include( 'biquadraticTexture' );
  52012. const wrapFunction = this.generateWrapFunction( texture );
  52013. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  52014. if ( offsetSnippet ) {
  52015. uvSnippet = `${ uvSnippet } + vec2<f32>(${ offsetSnippet }) / ${ textureDimension }`;
  52016. }
  52017. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  52018. }
  52019. /**
  52020. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  52021. * Since it's a lookup, no sampling or filtering is applied.
  52022. *
  52023. * @param {Texture} texture - The texture.
  52024. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52025. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52026. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52027. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52028. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52029. * @return {string} The WGSL snippet.
  52030. */
  52031. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet = '0u' ) {
  52032. const wrapFunction = this.generateWrapFunction( texture );
  52033. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  52034. const vecType = texture.is3DTexture || texture.isData3DTexture ? 'vec3' : 'vec2';
  52035. if ( offsetSnippet ) {
  52036. uvSnippet = `${ uvSnippet } + ${ vecType }<f32>(${ offsetSnippet }) / ${ vecType }<f32>( ${ textureDimension } )`;
  52037. }
  52038. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  52039. return this.generateTextureLoad( texture, textureProperty, coordSnippet, levelSnippet, depthSnippet, null );
  52040. }
  52041. /**
  52042. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  52043. *
  52044. * @param {Texture} texture - The texture.
  52045. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52046. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52047. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52048. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52049. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52050. * @return {string} The WGSL snippet.
  52051. */
  52052. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  52053. if ( levelSnippet === null ) levelSnippet = '0u';
  52054. if ( offsetSnippet ) {
  52055. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  52056. }
  52057. let snippet;
  52058. if ( depthSnippet ) {
  52059. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  52060. } else {
  52061. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  52062. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  52063. snippet += '.x';
  52064. }
  52065. }
  52066. return snippet;
  52067. }
  52068. /**
  52069. * Generates the WGSL snippet that writes a single texel to a texture.
  52070. *
  52071. * @param {Texture} texture - The texture.
  52072. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52073. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52074. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52075. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  52076. * @return {string} The WGSL snippet.
  52077. */
  52078. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  52079. let snippet;
  52080. if ( depthSnippet ) {
  52081. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  52082. } else {
  52083. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  52084. }
  52085. return snippet;
  52086. }
  52087. /**
  52088. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  52089. *
  52090. * @param {Texture} texture - The texture.
  52091. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  52092. */
  52093. isSampleCompare( texture ) {
  52094. return texture.isDepthTexture === true && texture.compareFunction !== null;
  52095. }
  52096. /**
  52097. * Returns `true` if the given texture is unfilterable.
  52098. *
  52099. * @param {Texture} texture - The texture.
  52100. * @return {boolean} Whether the given texture is unfilterable or not.
  52101. */
  52102. isUnfilterable( texture ) {
  52103. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  52104. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  52105. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  52106. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  52107. }
  52108. /**
  52109. * Generates the WGSL snippet for sampling/loading the given texture.
  52110. *
  52111. * @param {Texture} texture - The texture.
  52112. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52113. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52114. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52115. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52116. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52117. * @return {string} The WGSL snippet.
  52118. */
  52119. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52120. let snippet = null;
  52121. if ( this.isUnfilterable( texture ) ) {
  52122. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, '0', shaderStage );
  52123. } else {
  52124. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage );
  52125. }
  52126. return snippet;
  52127. }
  52128. /**
  52129. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  52130. *
  52131. * @param {Texture} texture - The texture.
  52132. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52133. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52134. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  52135. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52136. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52137. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52138. * @return {string} The WGSL snippet.
  52139. */
  52140. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52141. if ( shaderStage === 'fragment' ) {
  52142. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  52143. if ( offsetSnippet ) {
  52144. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  52145. }
  52146. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  52147. } else {
  52148. error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  52149. }
  52150. }
  52151. /**
  52152. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  52153. * against a reference value.
  52154. *
  52155. * @param {Texture} texture - The texture.
  52156. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52157. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52158. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  52159. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52160. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52161. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52162. * @return {string} The WGSL snippet.
  52163. */
  52164. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52165. if ( shaderStage === 'fragment' ) {
  52166. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  52167. if ( offsetSnippet ) {
  52168. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  52169. }
  52170. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  52171. }
  52172. if ( offsetSnippet ) {
  52173. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  52174. }
  52175. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  52176. } else {
  52177. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  52178. }
  52179. }
  52180. /**
  52181. * Generates the WGSL snippet when sampling textures with explicit mip level.
  52182. *
  52183. * @param {Texture} texture - The texture.
  52184. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52185. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52186. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52187. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52188. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52189. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52190. * @return {string} The WGSL snippet.
  52191. */
  52192. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  52193. if ( this.isUnfilterable( texture ) === false ) {
  52194. if ( offsetSnippet ) {
  52195. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  52196. }
  52197. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  52198. } else if ( this.isFilteredTexture( texture ) ) {
  52199. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  52200. } else {
  52201. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  52202. }
  52203. }
  52204. /**
  52205. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  52206. *
  52207. * @param {Texture} texture - The texture.
  52208. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52209. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52210. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  52211. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52212. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52213. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52214. * @return {string} The WGSL snippet.
  52215. */
  52216. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52217. if ( shaderStage === 'fragment' ) {
  52218. if ( offsetSnippet ) {
  52219. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  52220. }
  52221. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  52222. } else {
  52223. error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  52224. }
  52225. }
  52226. /**
  52227. * Returns a WGSL snippet that represents the property name of the given node.
  52228. *
  52229. * @param {Node} node - The node.
  52230. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52231. * @return {string} The property name.
  52232. */
  52233. getPropertyName( node, shaderStage = this.shaderStage ) {
  52234. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  52235. if ( shaderStage === 'vertex' ) {
  52236. return `varyings.${ node.name }`;
  52237. }
  52238. } else if ( node.isNodeUniform === true ) {
  52239. const name = node.name;
  52240. const type = node.type;
  52241. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  52242. return name;
  52243. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  52244. if ( this.isCustomStruct( node ) ) {
  52245. return name;
  52246. }
  52247. return name + '.value';
  52248. } else {
  52249. return node.groupNode.name + '.' + name;
  52250. }
  52251. }
  52252. return super.getPropertyName( node );
  52253. }
  52254. /**
  52255. * Returns the output struct name.
  52256. *
  52257. * @return {string} The name of the output struct.
  52258. */
  52259. getOutputStructName() {
  52260. return 'output';
  52261. }
  52262. /**
  52263. * Returns the native shader operator name for a given generic name.
  52264. *
  52265. * @param {string} op - The operator name to resolve.
  52266. * @return {?string} The resolved operator name.
  52267. */
  52268. getFunctionOperator( op ) {
  52269. const fnOp = wgslFnOpLib[ op ];
  52270. if ( fnOp !== undefined ) {
  52271. this._include( fnOp );
  52272. return fnOp;
  52273. }
  52274. return null;
  52275. }
  52276. /**
  52277. * Returns the node access for the given node and shader stage.
  52278. *
  52279. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  52280. * @param {string} shaderStage - The shader stage.
  52281. * @return {string} The node access.
  52282. */
  52283. getNodeAccess( node, shaderStage ) {
  52284. if ( shaderStage !== 'compute' ) {
  52285. if ( node.isAtomic === true ) {
  52286. warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  52287. return NodeAccess.READ_WRITE;
  52288. }
  52289. return NodeAccess.READ_ONLY;
  52290. }
  52291. return node.access;
  52292. }
  52293. /**
  52294. * Returns A WGSL snippet representing the storage access.
  52295. *
  52296. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  52297. * @param {string} shaderStage - The shader stage.
  52298. * @return {string} The WGSL snippet representing the storage access.
  52299. */
  52300. getStorageAccess( node, shaderStage ) {
  52301. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  52302. }
  52303. /**
  52304. * This method is one of the more important ones since it's responsible
  52305. * for generating a matching binding instance for the given uniform node.
  52306. *
  52307. * These bindings are later used in the renderer to create bind groups
  52308. * and layouts.
  52309. *
  52310. * @param {UniformNode} node - The uniform node.
  52311. * @param {string} type - The node data type.
  52312. * @param {string} shaderStage - The shader stage.
  52313. * @param {?string} [name=null] - An optional uniform name.
  52314. * @return {NodeUniform} The node uniform object.
  52315. */
  52316. getUniformFromNode( node, type, shaderStage, name = null ) {
  52317. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  52318. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  52319. if ( nodeData.uniformGPU === undefined ) {
  52320. let uniformGPU;
  52321. const group = node.groupNode;
  52322. const groupName = group.name;
  52323. const bindings = this.getBindGroupArray( groupName, shaderStage );
  52324. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  52325. let texture = null;
  52326. const access = this.getNodeAccess( node, shaderStage );
  52327. if ( type === 'texture' || type === 'storageTexture' ) {
  52328. if ( node.value.is3DTexture === true ) {
  52329. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  52330. } else {
  52331. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  52332. }
  52333. } else if ( type === 'cubeTexture' ) {
  52334. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  52335. } else if ( type === 'texture3D' ) {
  52336. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  52337. }
  52338. texture.store = node.isStorageTextureNode === true;
  52339. texture.mipLevel = texture.store ? node.mipLevel : 0;
  52340. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  52341. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  52342. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  52343. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  52344. bindings.push( sampler, texture );
  52345. uniformGPU = [ sampler, texture ];
  52346. } else {
  52347. bindings.push( texture );
  52348. uniformGPU = [ texture ];
  52349. }
  52350. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  52351. const sharedData = this.getSharedDataFromNode( node );
  52352. let buffer = sharedData.buffer;
  52353. if ( buffer === undefined ) {
  52354. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  52355. buffer = new bufferClass( node, group );
  52356. sharedData.buffer = buffer;
  52357. }
  52358. buffer.setVisibility( buffer.getVisibility() | gpuShaderStageLib[ shaderStage ] );
  52359. bindings.push( buffer );
  52360. uniformGPU = buffer;
  52361. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  52362. } else {
  52363. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  52364. let uniformsGroup = uniformsStage[ groupName ];
  52365. if ( uniformsGroup === undefined ) {
  52366. uniformsGroup = new NodeUniformsGroup( groupName, group );
  52367. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  52368. uniformsStage[ groupName ] = uniformsGroup;
  52369. bindings.push( uniformsGroup );
  52370. }
  52371. uniformGPU = this.getNodeUniform( uniformNode, type );
  52372. uniformsGroup.addUniform( uniformGPU );
  52373. }
  52374. nodeData.uniformGPU = uniformGPU;
  52375. }
  52376. return uniformNode;
  52377. }
  52378. /**
  52379. * This method should be used whenever builtins are required in nodes.
  52380. * The internal builtins data structure will make sure builtins are
  52381. * defined in the WGSL source.
  52382. *
  52383. * @param {string} name - The builtin name.
  52384. * @param {string} property - The property name.
  52385. * @param {string} type - The node data type.
  52386. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52387. * @return {string} The property name.
  52388. */
  52389. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  52390. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  52391. if ( map.has( name ) === false ) {
  52392. map.set( name, {
  52393. name,
  52394. property,
  52395. type
  52396. } );
  52397. }
  52398. return property;
  52399. }
  52400. /**
  52401. * Returns `true` if the given builtin is defined in the given shader stage.
  52402. *
  52403. * @param {string} name - The builtin name.
  52404. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52405. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  52406. */
  52407. hasBuiltin( name, shaderStage = this.shaderStage ) {
  52408. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  52409. }
  52410. /**
  52411. * Returns the vertex index builtin.
  52412. *
  52413. * @return {string} The vertex index.
  52414. */
  52415. getVertexIndex() {
  52416. if ( this.shaderStage === 'vertex' ) {
  52417. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  52418. }
  52419. return 'vertexIndex';
  52420. }
  52421. /**
  52422. * Builds the given shader node.
  52423. *
  52424. * @param {ShaderNodeInternal} shaderNode - The shader node.
  52425. * @return {string} The WGSL function code.
  52426. */
  52427. buildFunctionCode( shaderNode ) {
  52428. const layout = shaderNode.layout;
  52429. const flowData = this.flowShaderNode( shaderNode );
  52430. const parameters = [];
  52431. for ( const input of layout.inputs ) {
  52432. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  52433. }
  52434. //
  52435. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  52436. ${ flowData.vars }
  52437. ${ flowData.code }
  52438. `;
  52439. if ( flowData.result ) {
  52440. code += `\treturn ${ flowData.result };\n`;
  52441. }
  52442. code += '\n}\n';
  52443. //
  52444. return code;
  52445. }
  52446. /**
  52447. * Contextually returns either the vertex stage instance index builtin
  52448. * or the linearized index of an compute invocation within a grid of workgroups.
  52449. *
  52450. * @return {string} The instance index.
  52451. */
  52452. getInstanceIndex() {
  52453. if ( this.shaderStage === 'vertex' ) {
  52454. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  52455. }
  52456. return 'instanceIndex';
  52457. }
  52458. /**
  52459. * Returns a builtin representing the index of a compute invocation within the scope of a workgroup load.
  52460. *
  52461. * @return {string} The invocation local index.
  52462. */
  52463. getInvocationLocalIndex() {
  52464. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  52465. }
  52466. /**
  52467. * Returns a builtin representing the size of a subgroup within the current shader.
  52468. *
  52469. * @return {string} The subgroup size.
  52470. */
  52471. getSubgroupSize() {
  52472. this.enableSubGroups();
  52473. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  52474. }
  52475. /**
  52476. * Returns a builtin representing the index of a compute invocation within the scope of a subgroup.
  52477. *
  52478. * @return {string} The invocation subgroup index.
  52479. */
  52480. getInvocationSubgroupIndex() {
  52481. this.enableSubGroups();
  52482. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  52483. }
  52484. /**
  52485. * Returns a builtin representing the index of a compute invocation's subgroup within its workgroup.
  52486. *
  52487. * @return {string} The subgroup index.
  52488. */
  52489. getSubgroupIndex() {
  52490. this.enableSubGroups();
  52491. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  52492. }
  52493. /**
  52494. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  52495. *
  52496. * @return {null} Null.
  52497. */
  52498. getDrawIndex() {
  52499. return null;
  52500. }
  52501. /**
  52502. * Returns the front facing builtin.
  52503. *
  52504. * @return {string} The front facing builtin.
  52505. */
  52506. getFrontFacing() {
  52507. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  52508. }
  52509. /**
  52510. * Returns the frag coord builtin.
  52511. *
  52512. * @return {string} The frag coord builtin.
  52513. */
  52514. getFragCoord() {
  52515. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  52516. }
  52517. /**
  52518. * Returns the frag depth builtin.
  52519. *
  52520. * @return {string} The frag depth builtin.
  52521. */
  52522. getFragDepth() {
  52523. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  52524. }
  52525. /**
  52526. * Returns the clip distances builtin.
  52527. *
  52528. * @return {string} The clip distances builtin.
  52529. */
  52530. getClipDistance() {
  52531. return 'varyings.hw_clip_distances';
  52532. }
  52533. /**
  52534. * Whether to flip texture data along its vertical axis or not.
  52535. *
  52536. * @return {boolean} Returns always `false` in context of WGSL.
  52537. */
  52538. isFlipY() {
  52539. return false;
  52540. }
  52541. /**
  52542. * Enables the given directive for the given shader stage.
  52543. *
  52544. * @param {string} name - The directive name.
  52545. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  52546. */
  52547. enableDirective( name, shaderStage = this.shaderStage ) {
  52548. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  52549. stage.add( name );
  52550. }
  52551. /**
  52552. * Returns the directives of the given shader stage as a WGSL string.
  52553. *
  52554. * @param {string} shaderStage - The shader stage.
  52555. * @return {string} A WGSL snippet that enables the directives of the given stage.
  52556. */
  52557. getDirectives( shaderStage ) {
  52558. const snippets = [];
  52559. const directives = this.directives[ shaderStage ];
  52560. if ( directives !== undefined ) {
  52561. for ( const directive of directives ) {
  52562. snippets.push( `enable ${directive};` );
  52563. }
  52564. }
  52565. return snippets.join( '\n' );
  52566. }
  52567. /**
  52568. * Enables the 'subgroups' directive.
  52569. */
  52570. enableSubGroups() {
  52571. this.enableDirective( 'subgroups' );
  52572. }
  52573. /**
  52574. * Enables the 'subgroups-f16' directive.
  52575. */
  52576. enableSubgroupsF16() {
  52577. this.enableDirective( 'subgroups-f16' );
  52578. }
  52579. /**
  52580. * Enables the 'clip_distances' directive.
  52581. */
  52582. enableClipDistances() {
  52583. this.enableDirective( 'clip_distances' );
  52584. }
  52585. /**
  52586. * Enables the 'f16' directive.
  52587. */
  52588. enableShaderF16() {
  52589. this.enableDirective( 'f16' );
  52590. }
  52591. /**
  52592. * Enables the 'dual_source_blending' directive.
  52593. */
  52594. enableDualSourceBlending() {
  52595. this.enableDirective( 'dual_source_blending' );
  52596. }
  52597. /**
  52598. * Enables hardware clipping.
  52599. *
  52600. * @param {string} planeCount - The clipping plane count.
  52601. */
  52602. enableHardwareClipping( planeCount ) {
  52603. this.enableClipDistances();
  52604. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  52605. }
  52606. /**
  52607. * Returns the builtins of the given shader stage as a WGSL string.
  52608. *
  52609. * @param {string} shaderStage - The shader stage.
  52610. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  52611. */
  52612. getBuiltins( shaderStage ) {
  52613. const snippets = [];
  52614. const builtins = this.builtins[ shaderStage ];
  52615. if ( builtins !== undefined ) {
  52616. for ( const { name, property, type } of builtins.values() ) {
  52617. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  52618. }
  52619. }
  52620. return snippets.join( ',\n\t' );
  52621. }
  52622. /**
  52623. * This method should be used when a new scoped buffer is used in context of
  52624. * compute shaders. It adds the array to the internal data structure which is
  52625. * later used to generate the respective WGSL.
  52626. *
  52627. * @param {string} name - The array name.
  52628. * @param {string} scope - The scope.
  52629. * @param {string} bufferType - The buffer type.
  52630. * @param {string} bufferCount - The buffer count.
  52631. * @return {string} The array name.
  52632. */
  52633. getScopedArray( name, scope, bufferType, bufferCount ) {
  52634. if ( this.scopedArrays.has( name ) === false ) {
  52635. this.scopedArrays.set( name, {
  52636. name,
  52637. scope,
  52638. bufferType,
  52639. bufferCount
  52640. } );
  52641. }
  52642. return name;
  52643. }
  52644. /**
  52645. * Returns the scoped arrays of the given shader stage as a WGSL string.
  52646. *
  52647. * @param {string} shaderStage - The shader stage.
  52648. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  52649. * Returns `undefined` when used in the vertex or fragment stage.
  52650. */
  52651. getScopedArrays( shaderStage ) {
  52652. if ( shaderStage !== 'compute' ) {
  52653. return;
  52654. }
  52655. const snippets = [];
  52656. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  52657. const type = this.getType( bufferType );
  52658. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  52659. }
  52660. return snippets.join( '\n' );
  52661. }
  52662. /**
  52663. * Returns the shader attributes of the given shader stage as a WGSL string.
  52664. *
  52665. * @param {string} shaderStage - The shader stage.
  52666. * @return {string} The WGSL snippet that defines the shader attributes.
  52667. */
  52668. getAttributes( shaderStage ) {
  52669. const snippets = [];
  52670. if ( shaderStage === 'compute' ) {
  52671. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  52672. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  52673. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  52674. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  52675. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  52676. this.enableDirective( 'subgroups', shaderStage );
  52677. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  52678. }
  52679. }
  52680. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  52681. const builtins = this.getBuiltins( 'attribute' );
  52682. if ( builtins ) snippets.push( builtins );
  52683. const attributes = this.getAttributesArray();
  52684. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  52685. const attribute = attributes[ index ];
  52686. const name = attribute.name;
  52687. const type = this.getType( attribute.type );
  52688. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  52689. }
  52690. }
  52691. return snippets.join( ',\n\t' );
  52692. }
  52693. /**
  52694. * Returns the members of the given struct type node as a WGSL string.
  52695. *
  52696. * @param {StructTypeNode} struct - The struct type node.
  52697. * @return {string} The WGSL snippet that defines the struct members.
  52698. */
  52699. getStructMembers( struct ) {
  52700. const snippets = [];
  52701. for ( const member of struct.members ) {
  52702. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  52703. let type = this.getType( member.type );
  52704. if ( member.atomic ) {
  52705. type = 'atomic< ' + type + ' >';
  52706. }
  52707. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  52708. }
  52709. if ( struct.output ) {
  52710. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  52711. }
  52712. return snippets.join( ',\n' );
  52713. }
  52714. /**
  52715. * Returns the structs of the given shader stage as a WGSL string.
  52716. *
  52717. * @param {string} shaderStage - The shader stage.
  52718. * @return {string} The WGSL snippet that defines the structs.
  52719. */
  52720. getStructs( shaderStage ) {
  52721. let result = '';
  52722. const structs = this.structs[ shaderStage ];
  52723. if ( structs.length > 0 ) {
  52724. const snippets = [];
  52725. for ( const struct of structs ) {
  52726. let snippet = `struct ${ struct.name } {\n`;
  52727. snippet += this.getStructMembers( struct );
  52728. snippet += '\n};';
  52729. snippets.push( snippet );
  52730. }
  52731. result = '\n' + snippets.join( '\n\n' ) + '\n';
  52732. }
  52733. return result;
  52734. }
  52735. /**
  52736. * Returns a WGSL string representing a variable.
  52737. *
  52738. * @param {string} type - The variable's type.
  52739. * @param {string} name - The variable's name.
  52740. * @param {?number} [count=null] - The array length.
  52741. * @return {string} The WGSL snippet that defines a variable.
  52742. */
  52743. getVar( type, name, count = null ) {
  52744. let snippet = `var ${ name } : `;
  52745. if ( count !== null ) {
  52746. snippet += this.generateArrayDeclaration( type, count );
  52747. } else {
  52748. snippet += this.getType( type );
  52749. }
  52750. return snippet;
  52751. }
  52752. /**
  52753. * Returns the variables of the given shader stage as a WGSL string.
  52754. *
  52755. * @param {string} shaderStage - The shader stage.
  52756. * @return {string} The WGSL snippet that defines the variables.
  52757. */
  52758. getVars( shaderStage ) {
  52759. const snippets = [];
  52760. const vars = this.vars[ shaderStage ];
  52761. if ( vars !== undefined ) {
  52762. for ( const variable of vars ) {
  52763. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  52764. }
  52765. }
  52766. return `\n${ snippets.join( '\n' ) }\n`;
  52767. }
  52768. /**
  52769. * Returns the varyings of the given shader stage as a WGSL string.
  52770. *
  52771. * @param {string} shaderStage - The shader stage.
  52772. * @return {string} The WGSL snippet that defines the varyings.
  52773. */
  52774. getVaryings( shaderStage ) {
  52775. const snippets = [];
  52776. if ( shaderStage === 'vertex' ) {
  52777. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  52778. }
  52779. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  52780. const varyings = this.varyings;
  52781. const vars = this.vars[ shaderStage ];
  52782. for ( let index = 0; index < varyings.length; index ++ ) {
  52783. const varying = varyings[ index ];
  52784. if ( varying.needsInterpolation ) {
  52785. let attributesSnippet = `@location( ${index} )`;
  52786. if ( varying.interpolationType ) {
  52787. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  52788. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  52789. // Otherwise, optimize interpolation when sensible
  52790. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  52791. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  52792. }
  52793. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  52794. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  52795. vars.push( varying );
  52796. }
  52797. }
  52798. }
  52799. const builtins = this.getBuiltins( shaderStage );
  52800. if ( builtins ) snippets.push( builtins );
  52801. const code = snippets.join( ',\n\t' );
  52802. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  52803. }
  52804. isCustomStruct( nodeUniform ) {
  52805. const attribute = nodeUniform.value;
  52806. const bufferNode = nodeUniform.node;
  52807. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  52808. const isStructArray =
  52809. ( bufferNode.value && bufferNode.value.array ) &&
  52810. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  52811. return isAttributeStructType && ! isStructArray;
  52812. }
  52813. /**
  52814. * Returns the uniforms of the given shader stage as a WGSL string.
  52815. *
  52816. * @param {string} shaderStage - The shader stage.
  52817. * @return {string} The WGSL snippet that defines the uniforms.
  52818. */
  52819. getUniforms( shaderStage ) {
  52820. const uniforms = this.uniforms[ shaderStage ];
  52821. const bindingSnippets = [];
  52822. const bufferSnippets = [];
  52823. const structSnippets = [];
  52824. const uniformGroups = {};
  52825. for ( const uniform of uniforms ) {
  52826. const groupName = uniform.groupNode.name;
  52827. const uniformIndexes = this.bindingsIndexes[ groupName ];
  52828. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  52829. const texture = uniform.node.value;
  52830. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  52831. if ( this.isSampleCompare( texture ) ) {
  52832. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  52833. } else {
  52834. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  52835. }
  52836. }
  52837. let textureType;
  52838. let multisampled = '';
  52839. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  52840. if ( primarySamples > 1 ) {
  52841. multisampled = '_multisampled';
  52842. }
  52843. if ( texture.isCubeTexture === true ) {
  52844. textureType = 'texture_cube<f32>';
  52845. } else if ( texture.isDepthTexture === true ) {
  52846. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  52847. textureType = `texture${ multisampled }_2d<f32>`;
  52848. } else {
  52849. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  52850. }
  52851. } else if ( uniform.node.isStorageTextureNode === true ) {
  52852. const format = getFormat( texture );
  52853. const access = this.getStorageAccess( uniform.node, shaderStage );
  52854. const is3D = uniform.node.value.is3DTexture;
  52855. const isArrayTexture = uniform.node.value.isArrayTexture;
  52856. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  52857. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  52858. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  52859. textureType = 'texture_2d_array<f32>';
  52860. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  52861. textureType = 'texture_3d<f32>';
  52862. } else {
  52863. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  52864. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  52865. }
  52866. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  52867. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  52868. const bufferNode = uniform.node;
  52869. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  52870. const bufferCount = bufferNode.bufferCount;
  52871. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  52872. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  52873. if ( this.isCustomStruct( uniform ) ) {
  52874. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  52875. } else {
  52876. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  52877. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  52878. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  52879. }
  52880. } else {
  52881. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  52882. const groupName = uniform.groupNode.name;
  52883. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  52884. index: uniformIndexes.binding ++,
  52885. id: uniformIndexes.group,
  52886. snippets: []
  52887. } );
  52888. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  52889. }
  52890. }
  52891. for ( const name in uniformGroups ) {
  52892. const group = uniformGroups[ name ];
  52893. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  52894. }
  52895. let code = bindingSnippets.join( '\n' );
  52896. code += bufferSnippets.join( '\n' );
  52897. code += structSnippets.join( '\n' );
  52898. return code;
  52899. }
  52900. /**
  52901. * Controls the code build of the shader stages.
  52902. */
  52903. buildCode() {
  52904. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  52905. this.sortBindingGroups();
  52906. for ( const shaderStage in shadersData ) {
  52907. this.shaderStage = shaderStage;
  52908. const stageData = shadersData[ shaderStage ];
  52909. stageData.uniforms = this.getUniforms( shaderStage );
  52910. stageData.attributes = this.getAttributes( shaderStage );
  52911. stageData.varyings = this.getVaryings( shaderStage );
  52912. stageData.structs = this.getStructs( shaderStage );
  52913. stageData.vars = this.getVars( shaderStage );
  52914. stageData.codes = this.getCodes( shaderStage );
  52915. stageData.directives = this.getDirectives( shaderStage );
  52916. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  52917. //
  52918. let flow = '// code\n\n';
  52919. flow += this.flowCode[ shaderStage ];
  52920. const flowNodes = this.flowNodes[ shaderStage ];
  52921. const mainNode = flowNodes[ flowNodes.length - 1 ];
  52922. const outputNode = mainNode.outputNode;
  52923. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  52924. for ( const node of flowNodes ) {
  52925. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  52926. const slotName = node.name;
  52927. if ( slotName ) {
  52928. if ( flow.length > 0 ) flow += '\n';
  52929. flow += `\t// flow -> ${ slotName }\n`;
  52930. }
  52931. flow += `${ flowSlotData.code }\n\t`;
  52932. if ( node === mainNode && shaderStage !== 'compute' ) {
  52933. flow += '// result\n\n\t';
  52934. if ( shaderStage === 'vertex' ) {
  52935. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  52936. } else if ( shaderStage === 'fragment' ) {
  52937. if ( isOutputStruct ) {
  52938. stageData.returnType = outputNode.getNodeType( this );
  52939. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  52940. flow += `return ${ flowSlotData.result };`;
  52941. } else {
  52942. let structSnippet = '\t@location(0) color: vec4<f32>';
  52943. const builtins = this.getBuiltins( 'output' );
  52944. if ( builtins ) structSnippet += ',\n\t' + builtins;
  52945. stageData.returnType = 'OutputStruct';
  52946. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  52947. stageData.structs += '\nvar<private> output : OutputStruct;';
  52948. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  52949. }
  52950. }
  52951. }
  52952. }
  52953. stageData.flow = flow;
  52954. }
  52955. this.shaderStage = null;
  52956. if ( this.material !== null ) {
  52957. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  52958. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  52959. } else {
  52960. // Early strictly validated in computeNode
  52961. const workgroupSize = this.object.workgroupSize;
  52962. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  52963. }
  52964. }
  52965. /**
  52966. * Returns the native shader method name for a given generic name.
  52967. *
  52968. * @param {string} method - The method name to resolve.
  52969. * @param {?string} [output=null] - An optional output.
  52970. * @return {string} The resolved WGSL method name.
  52971. */
  52972. getMethod( method, output = null ) {
  52973. let wgslMethod;
  52974. if ( output !== null ) {
  52975. wgslMethod = this._getWGSLMethod( method + '_' + output );
  52976. }
  52977. if ( wgslMethod === undefined ) {
  52978. wgslMethod = this._getWGSLMethod( method );
  52979. }
  52980. return wgslMethod || method;
  52981. }
  52982. /**
  52983. * Returns the bitcast method name for a given input and outputType.
  52984. *
  52985. * @param {string} type - The output type to bitcast to.
  52986. * @return {string} The resolved WGSL bitcast invocation.
  52987. */
  52988. getBitcastMethod( type ) {
  52989. const dataType = this.getType( type );
  52990. return `bitcast<${ dataType }>`;
  52991. }
  52992. /**
  52993. * Returns the native snippet for a ternary operation.
  52994. *
  52995. * @param {string} condSnippet - The condition determining which expression gets resolved.
  52996. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  52997. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  52998. * @return {string} The resolved method name.
  52999. */
  53000. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  53001. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  53002. }
  53003. /**
  53004. * Returns the WGSL type of the given node data type.
  53005. *
  53006. * @param {string} type - The node data type.
  53007. * @return {string} The WGSL type.
  53008. */
  53009. getType( type ) {
  53010. return wgslTypeLib[ type ] || type;
  53011. }
  53012. /**
  53013. * Whether the requested feature is available or not.
  53014. *
  53015. * @param {string} name - The requested feature.
  53016. * @return {boolean} Whether the requested feature is supported or not.
  53017. */
  53018. isAvailable( name ) {
  53019. let result = supports[ name ];
  53020. if ( result === undefined ) {
  53021. if ( name === 'float32Filterable' ) {
  53022. result = this.renderer.hasFeature( 'float32-filterable' );
  53023. } else if ( name === 'clipDistance' ) {
  53024. result = this.renderer.hasFeature( 'clip-distances' );
  53025. }
  53026. supports[ name ] = result;
  53027. }
  53028. return result;
  53029. }
  53030. /**
  53031. * Returns the native shader method name for a given generic name.
  53032. *
  53033. * @private
  53034. * @param {string} method - The method name to resolve.
  53035. * @return {string} The resolved WGSL method name.
  53036. */
  53037. _getWGSLMethod( method ) {
  53038. if ( wgslPolyfill[ method ] !== undefined ) {
  53039. this._include( method );
  53040. }
  53041. return wgslMethods[ method ];
  53042. }
  53043. /**
  53044. * Includes the given method name into the current
  53045. * function node.
  53046. *
  53047. * @private
  53048. * @param {string} name - The method name to include.
  53049. * @return {CodeNode} The respective code node.
  53050. */
  53051. _include( name ) {
  53052. const codeNode = wgslPolyfill[ name ];
  53053. codeNode.build( this );
  53054. this.addInclude( codeNode );
  53055. return codeNode;
  53056. }
  53057. /**
  53058. * Returns a WGSL vertex shader based on the given shader data.
  53059. *
  53060. * @private
  53061. * @param {Object} shaderData - The shader data.
  53062. * @return {string} The vertex shader.
  53063. */
  53064. _getWGSLVertexCode( shaderData ) {
  53065. return `${ this.getSignature() }
  53066. // directives
  53067. ${shaderData.directives}
  53068. // structs
  53069. ${shaderData.structs}
  53070. // uniforms
  53071. ${shaderData.uniforms}
  53072. // varyings
  53073. ${shaderData.varyings}
  53074. var<private> varyings : VaryingsStruct;
  53075. // codes
  53076. ${shaderData.codes}
  53077. @vertex
  53078. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  53079. // vars
  53080. ${shaderData.vars}
  53081. // flow
  53082. ${shaderData.flow}
  53083. return varyings;
  53084. }
  53085. `;
  53086. }
  53087. /**
  53088. * Returns a WGSL fragment shader based on the given shader data.
  53089. *
  53090. * @private
  53091. * @param {Object} shaderData - The shader data.
  53092. * @return {string} The vertex shader.
  53093. */
  53094. _getWGSLFragmentCode( shaderData ) {
  53095. return `${ this.getSignature() }
  53096. // global
  53097. ${ diagnostics }
  53098. // structs
  53099. ${shaderData.structs}
  53100. // uniforms
  53101. ${shaderData.uniforms}
  53102. // codes
  53103. ${shaderData.codes}
  53104. @fragment
  53105. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  53106. // vars
  53107. ${shaderData.vars}
  53108. // flow
  53109. ${shaderData.flow}
  53110. }
  53111. `;
  53112. }
  53113. /**
  53114. * Returns a WGSL compute shader based on the given shader data.
  53115. *
  53116. * @private
  53117. * @param {Object} shaderData - The shader data.
  53118. * @param {string} workgroupSize - The workgroup size.
  53119. * @return {string} The vertex shader.
  53120. */
  53121. _getWGSLComputeCode( shaderData, workgroupSize ) {
  53122. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  53123. return `${ this.getSignature() }
  53124. // directives
  53125. ${ shaderData.directives }
  53126. // system
  53127. var<private> instanceIndex : u32;
  53128. // locals
  53129. ${ shaderData.scopedArrays }
  53130. // structs
  53131. ${ shaderData.structs }
  53132. // uniforms
  53133. ${ shaderData.uniforms }
  53134. // codes
  53135. ${ shaderData.codes }
  53136. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  53137. fn main( ${ shaderData.attributes } ) {
  53138. // system
  53139. instanceIndex = globalId.x
  53140. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  53141. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  53142. // vars
  53143. ${ shaderData.vars }
  53144. // flow
  53145. ${ shaderData.flow }
  53146. }
  53147. `;
  53148. }
  53149. /**
  53150. * Returns a WGSL struct based on the given name and variables.
  53151. *
  53152. * @private
  53153. * @param {string} name - The struct name.
  53154. * @param {string} vars - The struct variables.
  53155. * @return {string} The WGSL snippet representing a struct.
  53156. */
  53157. _getWGSLStruct( name, vars ) {
  53158. return `
  53159. struct ${name} {
  53160. ${vars}
  53161. };`;
  53162. }
  53163. /**
  53164. * Returns a WGSL struct binding.
  53165. *
  53166. * @private
  53167. * @param {string} name - The struct name.
  53168. * @param {string} vars - The struct variables.
  53169. * @param {string} access - The access.
  53170. * @param {number} [binding=0] - The binding index.
  53171. * @param {number} [group=0] - The group index.
  53172. * @return {string} The WGSL snippet representing a struct binding.
  53173. */
  53174. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  53175. const structName = name + 'Struct';
  53176. const structSnippet = this._getWGSLStruct( structName, vars );
  53177. return `${structSnippet}
  53178. @binding( ${ binding } ) @group( ${ group } )
  53179. var<${access}> ${ name } : ${ structName };`;
  53180. }
  53181. }
  53182. /**
  53183. * A WebGPU backend utility module with common helpers.
  53184. *
  53185. * @private
  53186. */
  53187. class WebGPUUtils {
  53188. /**
  53189. * Constructs a new utility object.
  53190. *
  53191. * @param {WebGPUBackend} backend - The WebGPU backend.
  53192. */
  53193. constructor( backend ) {
  53194. /**
  53195. * A reference to the WebGPU backend.
  53196. *
  53197. * @type {WebGPUBackend}
  53198. */
  53199. this.backend = backend;
  53200. }
  53201. /**
  53202. * Returns the depth/stencil GPU format for the given render context.
  53203. *
  53204. * @param {RenderContext} renderContext - The render context.
  53205. * @return {string} The depth/stencil GPU texture format.
  53206. */
  53207. getCurrentDepthStencilFormat( renderContext ) {
  53208. let format;
  53209. if ( renderContext.depthTexture !== null ) {
  53210. format = this.getTextureFormatGPU( renderContext.depthTexture );
  53211. } else if ( renderContext.depth && renderContext.stencil ) {
  53212. format = GPUTextureFormat.Depth24PlusStencil8;
  53213. } else if ( renderContext.depth ) {
  53214. format = GPUTextureFormat.Depth24Plus;
  53215. }
  53216. return format;
  53217. }
  53218. /**
  53219. * Returns the GPU format for the given texture.
  53220. *
  53221. * @param {Texture} texture - The texture.
  53222. * @return {string} The GPU texture format.
  53223. */
  53224. getTextureFormatGPU( texture ) {
  53225. return this.backend.get( texture ).format;
  53226. }
  53227. /**
  53228. * Returns an object that defines the multi-sampling state of the given texture.
  53229. *
  53230. * @param {Texture} texture - The texture.
  53231. * @return {Object} The multi-sampling state.
  53232. */
  53233. getTextureSampleData( texture ) {
  53234. let samples;
  53235. if ( texture.isFramebufferTexture ) {
  53236. samples = 1;
  53237. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  53238. const renderer = this.backend.renderer;
  53239. const renderTarget = renderer.getRenderTarget();
  53240. samples = renderTarget ? renderTarget.samples : renderer.currentSamples;
  53241. } else if ( texture.renderTarget ) {
  53242. samples = texture.renderTarget.samples;
  53243. }
  53244. samples = samples || 1;
  53245. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  53246. const primarySamples = isMSAA ? 1 : samples;
  53247. return { samples, primarySamples, isMSAA };
  53248. }
  53249. /**
  53250. * Returns the default color attachment's GPU format of the current render context.
  53251. *
  53252. * @param {RenderContext} renderContext - The render context.
  53253. * @return {string} The GPU texture format of the default color attachment.
  53254. */
  53255. getCurrentColorFormat( renderContext ) {
  53256. let format;
  53257. if ( renderContext.textures !== null ) {
  53258. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  53259. } else {
  53260. format = this.getPreferredCanvasFormat(); // default context format
  53261. }
  53262. return format;
  53263. }
  53264. /**
  53265. * Returns the GPU formats of all color attachments of the current render context.
  53266. *
  53267. * @param {RenderContext} renderContext - The render context.
  53268. * @return {Array<string>} The GPU texture formats of all color attachments.
  53269. */
  53270. getCurrentColorFormats( renderContext ) {
  53271. if ( renderContext.textures !== null ) {
  53272. return renderContext.textures.map( t => this.getTextureFormatGPU( t ) );
  53273. } else {
  53274. return [ this.getPreferredCanvasFormat() ]; // default context format
  53275. }
  53276. }
  53277. /**
  53278. * Returns the output color space of the current render context.
  53279. *
  53280. * @param {RenderContext} renderContext - The render context.
  53281. * @return {string} The output color space.
  53282. */
  53283. getCurrentColorSpace( renderContext ) {
  53284. if ( renderContext.textures !== null ) {
  53285. return renderContext.textures[ 0 ].colorSpace;
  53286. }
  53287. return this.backend.renderer.outputColorSpace;
  53288. }
  53289. /**
  53290. * Returns GPU primitive topology for the given object and material.
  53291. *
  53292. * @param {Object3D} object - The 3D object.
  53293. * @param {Material} material - The material.
  53294. * @return {string} The GPU primitive topology.
  53295. */
  53296. getPrimitiveTopology( object, material ) {
  53297. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  53298. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  53299. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  53300. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  53301. }
  53302. /**
  53303. * Returns a modified sample count from the given sample count value.
  53304. *
  53305. * That is required since WebGPU only supports either 1 or 4.
  53306. *
  53307. * @param {number} sampleCount - The input sample count.
  53308. * @return {number} The (potentially updated) output sample count.
  53309. */
  53310. getSampleCount( sampleCount ) {
  53311. return sampleCount >= 4 ? 4 : 1;
  53312. }
  53313. /**
  53314. * Returns the sample count of the given render context.
  53315. *
  53316. * @param {RenderContext} renderContext - The render context.
  53317. * @return {number} The sample count.
  53318. */
  53319. getSampleCountRenderContext( renderContext ) {
  53320. if ( renderContext.textures !== null ) {
  53321. return this.getSampleCount( renderContext.sampleCount );
  53322. }
  53323. return this.getSampleCount( this.backend.renderer.currentSamples );
  53324. }
  53325. /**
  53326. * Returns the preferred canvas format.
  53327. *
  53328. * There is a separate method for this so it's possible to
  53329. * honor edge cases for specific devices.
  53330. *
  53331. * @return {string} The GPU texture format of the canvas.
  53332. */
  53333. getPreferredCanvasFormat() {
  53334. const outputType = this.backend.parameters.outputType;
  53335. if ( outputType === undefined ) {
  53336. return navigator.gpu.getPreferredCanvasFormat();
  53337. } else if ( outputType === UnsignedByteType ) {
  53338. return GPUTextureFormat.BGRA8Unorm;
  53339. } else if ( outputType === HalfFloatType ) {
  53340. return GPUTextureFormat.RGBA16Float;
  53341. } else {
  53342. throw new Error( 'Unsupported outputType' );
  53343. }
  53344. }
  53345. }
  53346. const typedArraysToVertexFormatPrefix = new Map( [
  53347. [ Int8Array, [ 'sint8', 'snorm8' ]],
  53348. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  53349. [ Int16Array, [ 'sint16', 'snorm16' ]],
  53350. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  53351. [ Int32Array, [ 'sint32', 'snorm32' ]],
  53352. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  53353. [ Float32Array, [ 'float32', ]],
  53354. ] );
  53355. if ( typeof Float16Array !== 'undefined' ) {
  53356. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  53357. }
  53358. const typedAttributeToVertexFormatPrefix = new Map( [
  53359. [ Float16BufferAttribute, [ 'float16', ]],
  53360. ] );
  53361. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  53362. [ Int32Array, 'sint32' ],
  53363. [ Int16Array, 'sint32' ], // patch for INT16
  53364. [ Uint32Array, 'uint32' ],
  53365. [ Uint16Array, 'uint32' ], // patch for UINT16
  53366. [ Float32Array, 'float32' ]
  53367. ] );
  53368. /**
  53369. * A WebGPU backend utility module for managing shader attributes.
  53370. *
  53371. * @private
  53372. */
  53373. class WebGPUAttributeUtils {
  53374. /**
  53375. * Constructs a new utility object.
  53376. *
  53377. * @param {WebGPUBackend} backend - The WebGPU backend.
  53378. */
  53379. constructor( backend ) {
  53380. /**
  53381. * A reference to the WebGPU backend.
  53382. *
  53383. * @type {WebGPUBackend}
  53384. */
  53385. this.backend = backend;
  53386. }
  53387. /**
  53388. * Creates the GPU buffer for the given buffer attribute.
  53389. *
  53390. * @param {BufferAttribute} attribute - The buffer attribute.
  53391. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  53392. */
  53393. createAttribute( attribute, usage ) {
  53394. const bufferAttribute = this._getBufferAttribute( attribute );
  53395. const backend = this.backend;
  53396. const bufferData = backend.get( bufferAttribute );
  53397. let buffer = bufferData.buffer;
  53398. if ( buffer === undefined ) {
  53399. const device = backend.device;
  53400. let array = bufferAttribute.array;
  53401. // patch for INT16 and UINT16
  53402. if ( attribute.normalized === false ) {
  53403. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  53404. array = new Int32Array( array );
  53405. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  53406. array = new Uint32Array( array );
  53407. if ( usage & GPUBufferUsage.INDEX ) {
  53408. for ( let i = 0; i < array.length; i ++ ) {
  53409. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  53410. }
  53411. }
  53412. }
  53413. }
  53414. bufferAttribute.array = array;
  53415. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  53416. array = new array.constructor( bufferAttribute.count * 4 );
  53417. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  53418. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  53419. }
  53420. // Update BufferAttribute
  53421. bufferAttribute.itemSize = 4;
  53422. bufferAttribute.array = array;
  53423. bufferData._force3to4BytesAlignment = true;
  53424. }
  53425. // ensure 4 byte alignment
  53426. const byteLength = array.byteLength;
  53427. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  53428. buffer = device.createBuffer( {
  53429. label: bufferAttribute.name,
  53430. size: size,
  53431. usage: usage,
  53432. mappedAtCreation: true
  53433. } );
  53434. new array.constructor( buffer.getMappedRange() ).set( array );
  53435. buffer.unmap();
  53436. bufferData.buffer = buffer;
  53437. }
  53438. }
  53439. /**
  53440. * Updates the GPU buffer of the given buffer attribute.
  53441. *
  53442. * @param {BufferAttribute} attribute - The buffer attribute.
  53443. */
  53444. updateAttribute( attribute ) {
  53445. const bufferAttribute = this._getBufferAttribute( attribute );
  53446. const backend = this.backend;
  53447. const device = backend.device;
  53448. const bufferData = backend.get( bufferAttribute );
  53449. const buffer = backend.get( bufferAttribute ).buffer;
  53450. let array = bufferAttribute.array;
  53451. // if storage buffer ensure 4 byte alignment
  53452. if ( bufferData._force3to4BytesAlignment === true ) {
  53453. array = new array.constructor( bufferAttribute.count * 4 );
  53454. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  53455. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  53456. }
  53457. bufferAttribute.array = array;
  53458. }
  53459. const updateRanges = bufferAttribute.updateRanges;
  53460. if ( updateRanges.length === 0 ) {
  53461. // Not using update ranges
  53462. device.queue.writeBuffer(
  53463. buffer,
  53464. 0,
  53465. array,
  53466. 0
  53467. );
  53468. } else {
  53469. const isTyped = isTypedArray( array );
  53470. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  53471. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  53472. const range = updateRanges[ i ];
  53473. let dataOffset, size;
  53474. if ( bufferData._force3to4BytesAlignment === true ) {
  53475. const vertexStart = Math.floor( range.start / 3 );
  53476. const vertexCount = Math.ceil( range.count / 3 );
  53477. dataOffset = vertexStart * 4 * byteOffsetFactor;
  53478. size = vertexCount * 4 * byteOffsetFactor;
  53479. } else {
  53480. dataOffset = range.start * byteOffsetFactor;
  53481. size = range.count * byteOffsetFactor;
  53482. }
  53483. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  53484. device.queue.writeBuffer(
  53485. buffer,
  53486. bufferOffset,
  53487. array,
  53488. dataOffset,
  53489. size
  53490. );
  53491. }
  53492. bufferAttribute.clearUpdateRanges();
  53493. }
  53494. }
  53495. /**
  53496. * This method creates the vertex buffer layout data which are
  53497. * require when creating a render pipeline for the given render object.
  53498. *
  53499. * @param {RenderObject} renderObject - The render object.
  53500. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  53501. */
  53502. createShaderVertexBuffers( renderObject ) {
  53503. const attributes = renderObject.getAttributes();
  53504. const vertexBuffers = new Map();
  53505. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  53506. const geometryAttribute = attributes[ slot ];
  53507. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  53508. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  53509. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  53510. if ( vertexBufferLayout === undefined ) {
  53511. let arrayStride, stepMode;
  53512. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  53513. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  53514. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  53515. } else {
  53516. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  53517. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  53518. }
  53519. // patch for INT16 and UINT16
  53520. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  53521. arrayStride = 4;
  53522. }
  53523. vertexBufferLayout = {
  53524. arrayStride,
  53525. attributes: [],
  53526. stepMode
  53527. };
  53528. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  53529. }
  53530. const format = this._getVertexFormat( geometryAttribute );
  53531. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  53532. vertexBufferLayout.attributes.push( {
  53533. shaderLocation: slot,
  53534. offset,
  53535. format
  53536. } );
  53537. }
  53538. return Array.from( vertexBuffers.values() );
  53539. }
  53540. /**
  53541. * Destroys the GPU buffer of the given buffer attribute.
  53542. *
  53543. * @param {BufferAttribute} attribute - The buffer attribute.
  53544. */
  53545. destroyAttribute( attribute ) {
  53546. const backend = this.backend;
  53547. const data = backend.get( this._getBufferAttribute( attribute ) );
  53548. data.buffer.destroy();
  53549. backend.delete( attribute );
  53550. }
  53551. /**
  53552. * This method performs a readback operation by moving buffer data from
  53553. * a storage buffer attribute from the GPU to the CPU.
  53554. *
  53555. * @async
  53556. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  53557. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  53558. */
  53559. async getArrayBufferAsync( attribute ) {
  53560. const backend = this.backend;
  53561. const device = backend.device;
  53562. const data = backend.get( this._getBufferAttribute( attribute ) );
  53563. const bufferGPU = data.buffer;
  53564. const size = bufferGPU.size;
  53565. const readBufferGPU = device.createBuffer( {
  53566. label: `${ attribute.name }_readback`,
  53567. size,
  53568. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  53569. } );
  53570. const cmdEncoder = device.createCommandEncoder( {
  53571. label: `readback_encoder_${ attribute.name }`
  53572. } );
  53573. cmdEncoder.copyBufferToBuffer(
  53574. bufferGPU,
  53575. 0,
  53576. readBufferGPU,
  53577. 0,
  53578. size
  53579. );
  53580. const gpuCommands = cmdEncoder.finish();
  53581. device.queue.submit( [ gpuCommands ] );
  53582. await readBufferGPU.mapAsync( GPUMapMode.READ );
  53583. const arrayBuffer = readBufferGPU.getMappedRange();
  53584. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  53585. readBufferGPU.unmap();
  53586. return dstBuffer.buffer;
  53587. }
  53588. /**
  53589. * Returns the vertex format of the given buffer attribute.
  53590. *
  53591. * @private
  53592. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  53593. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  53594. */
  53595. _getVertexFormat( geometryAttribute ) {
  53596. const { itemSize, normalized } = geometryAttribute;
  53597. const ArrayType = geometryAttribute.array.constructor;
  53598. const AttributeType = geometryAttribute.constructor;
  53599. let format;
  53600. if ( itemSize === 1 ) {
  53601. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  53602. } else {
  53603. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  53604. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  53605. if ( prefix ) {
  53606. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  53607. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  53608. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  53609. if ( paddedItemSize % 1 ) {
  53610. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  53611. }
  53612. format = `${prefix}x${paddedItemSize}`;
  53613. }
  53614. }
  53615. if ( ! format ) {
  53616. error( 'WebGPUAttributeUtils: Vertex format not supported yet.' );
  53617. }
  53618. return format;
  53619. }
  53620. /**
  53621. * Utility method for handling interleaved buffer attributes correctly.
  53622. * To process them, their `InterleavedBuffer` is returned.
  53623. *
  53624. * @private
  53625. * @param {BufferAttribute} attribute - The attribute.
  53626. * @return {BufferAttribute|InterleavedBuffer}
  53627. */
  53628. _getBufferAttribute( attribute ) {
  53629. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  53630. return attribute;
  53631. }
  53632. }
  53633. /**
  53634. * A WebGPU backend utility module for managing bindings.
  53635. *
  53636. * When reading the documentation it's helpful to keep in mind that
  53637. * all class definitions starting with 'GPU*' are modules from the
  53638. * WebGPU API. So for example `BindGroup` is a class from the engine
  53639. * whereas `GPUBindGroup` is a class from WebGPU.
  53640. *
  53641. * @private
  53642. */
  53643. class WebGPUBindingUtils {
  53644. /**
  53645. * Constructs a new utility object.
  53646. *
  53647. * @param {WebGPUBackend} backend - The WebGPU backend.
  53648. */
  53649. constructor( backend ) {
  53650. /**
  53651. * A reference to the WebGPU backend.
  53652. *
  53653. * @type {WebGPUBackend}
  53654. */
  53655. this.backend = backend;
  53656. /**
  53657. * A cache for managing bind group layouts.
  53658. *
  53659. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  53660. */
  53661. this.bindGroupLayoutCache = new WeakMap();
  53662. }
  53663. /**
  53664. * Creates a GPU bind group layout for the given bind group.
  53665. *
  53666. * @param {BindGroup} bindGroup - The bind group.
  53667. * @return {GPUBindGroupLayout} The GPU bind group layout.
  53668. */
  53669. createBindingsLayout( bindGroup ) {
  53670. const backend = this.backend;
  53671. const device = backend.device;
  53672. const entries = [];
  53673. let index = 0;
  53674. for ( const binding of bindGroup.bindings ) {
  53675. const bindingGPU = {
  53676. binding: index ++,
  53677. visibility: binding.visibility
  53678. };
  53679. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  53680. const buffer = {}; // GPUBufferBindingLayout
  53681. if ( binding.isStorageBuffer ) {
  53682. if ( binding.visibility & GPUShaderStage.COMPUTE ) {
  53683. // compute
  53684. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  53685. buffer.type = GPUBufferBindingType.Storage;
  53686. } else {
  53687. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  53688. }
  53689. } else {
  53690. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  53691. }
  53692. }
  53693. bindingGPU.buffer = buffer;
  53694. } else if ( binding.isSampledTexture && binding.store ) {
  53695. const storageTexture = {}; // GPUStorageTextureBindingLayout
  53696. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  53697. const access = binding.access;
  53698. if ( access === NodeAccess.READ_WRITE ) {
  53699. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  53700. } else if ( access === NodeAccess.WRITE_ONLY ) {
  53701. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  53702. } else {
  53703. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  53704. }
  53705. if ( binding.texture.isArrayTexture ) {
  53706. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  53707. } else if ( binding.texture.is3DTexture ) {
  53708. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  53709. }
  53710. bindingGPU.storageTexture = storageTexture;
  53711. } else if ( binding.isSampledTexture ) {
  53712. const texture = {}; // GPUTextureBindingLayout
  53713. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  53714. if ( primarySamples > 1 ) {
  53715. texture.multisampled = true;
  53716. if ( ! binding.texture.isDepthTexture ) {
  53717. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  53718. }
  53719. }
  53720. if ( binding.texture.isDepthTexture ) {
  53721. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  53722. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  53723. } else {
  53724. texture.sampleType = GPUTextureSampleType.Depth;
  53725. }
  53726. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  53727. const type = binding.texture.type;
  53728. if ( type === IntType ) {
  53729. texture.sampleType = GPUTextureSampleType.SInt;
  53730. } else if ( type === UnsignedIntType ) {
  53731. texture.sampleType = GPUTextureSampleType.UInt;
  53732. } else if ( type === FloatType ) {
  53733. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  53734. texture.sampleType = GPUTextureSampleType.Float;
  53735. } else {
  53736. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  53737. }
  53738. }
  53739. }
  53740. if ( binding.isSampledCubeTexture ) {
  53741. texture.viewDimension = GPUTextureViewDimension.Cube;
  53742. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  53743. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  53744. } else if ( binding.isSampledTexture3D ) {
  53745. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  53746. }
  53747. bindingGPU.texture = texture;
  53748. } else if ( binding.isSampler ) {
  53749. const sampler = {}; // GPUSamplerBindingLayout
  53750. if ( binding.texture.isDepthTexture ) {
  53751. if ( binding.texture.compareFunction !== null ) {
  53752. sampler.type = GPUSamplerBindingType.Comparison;
  53753. } else if ( backend.compatibilityMode ) {
  53754. sampler.type = GPUSamplerBindingType.NonFiltering;
  53755. }
  53756. }
  53757. bindingGPU.sampler = sampler;
  53758. } else {
  53759. error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  53760. }
  53761. entries.push( bindingGPU );
  53762. }
  53763. return device.createBindGroupLayout( { entries } );
  53764. }
  53765. /**
  53766. * Creates bindings from the given bind group definition.
  53767. *
  53768. * @param {BindGroup} bindGroup - The bind group.
  53769. * @param {Array<BindGroup>} bindings - Array of bind groups.
  53770. * @param {number} cacheIndex - The cache index.
  53771. * @param {number} version - The version.
  53772. */
  53773. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  53774. const { backend, bindGroupLayoutCache } = this;
  53775. const bindingsData = backend.get( bindGroup );
  53776. // setup (static) binding layout and (dynamic) binding group
  53777. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  53778. if ( bindLayoutGPU === undefined ) {
  53779. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  53780. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  53781. }
  53782. let bindGroupGPU;
  53783. if ( cacheIndex > 0 ) {
  53784. if ( bindingsData.groups === undefined ) {
  53785. bindingsData.groups = [];
  53786. bindingsData.versions = [];
  53787. }
  53788. if ( bindingsData.versions[ cacheIndex ] === version ) {
  53789. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  53790. }
  53791. }
  53792. if ( bindGroupGPU === undefined ) {
  53793. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  53794. if ( cacheIndex > 0 ) {
  53795. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  53796. bindingsData.versions[ cacheIndex ] = version;
  53797. }
  53798. }
  53799. bindingsData.group = bindGroupGPU;
  53800. bindingsData.layout = bindLayoutGPU;
  53801. }
  53802. /**
  53803. * Updates a buffer binding.
  53804. *
  53805. * @param {Buffer} binding - The buffer binding to update.
  53806. */
  53807. updateBinding( binding ) {
  53808. const backend = this.backend;
  53809. const device = backend.device;
  53810. const array = binding.buffer; // cpu
  53811. const buffer = backend.get( binding ).buffer; // gpu
  53812. const updateRanges = binding.updateRanges;
  53813. if ( updateRanges.length === 0 ) {
  53814. device.queue.writeBuffer(
  53815. buffer,
  53816. 0,
  53817. array,
  53818. 0
  53819. );
  53820. } else {
  53821. const isTyped = isTypedArray( array );
  53822. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  53823. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  53824. const range = updateRanges[ i ];
  53825. const dataOffset = range.start * byteOffsetFactor;
  53826. const size = range.count * byteOffsetFactor;
  53827. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  53828. device.queue.writeBuffer(
  53829. buffer,
  53830. bufferOffset,
  53831. array,
  53832. dataOffset,
  53833. size
  53834. );
  53835. }
  53836. binding.clearUpdateRanges();
  53837. }
  53838. }
  53839. /**
  53840. * Creates a GPU bind group for the camera index.
  53841. *
  53842. * @param {Uint32Array} data - The index data.
  53843. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  53844. * @return {GPUBindGroup} The GPU bind group.
  53845. */
  53846. createBindGroupIndex( data, layout ) {
  53847. const backend = this.backend;
  53848. const device = backend.device;
  53849. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  53850. const index = data[ 0 ];
  53851. const buffer = device.createBuffer( {
  53852. label: 'bindingCameraIndex_' + index,
  53853. size: 16, // uint(4) * 4
  53854. usage: usage
  53855. } );
  53856. device.queue.writeBuffer( buffer, 0, data, 0 );
  53857. const entries = [ { binding: 0, resource: { buffer } } ];
  53858. return device.createBindGroup( {
  53859. label: 'bindGroupCameraIndex_' + index,
  53860. layout,
  53861. entries
  53862. } );
  53863. }
  53864. /**
  53865. * Creates a GPU bind group for the given bind group and GPU layout.
  53866. *
  53867. * @param {BindGroup} bindGroup - The bind group.
  53868. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  53869. * @return {GPUBindGroup} The GPU bind group.
  53870. */
  53871. createBindGroup( bindGroup, layoutGPU ) {
  53872. const backend = this.backend;
  53873. const device = backend.device;
  53874. let bindingPoint = 0;
  53875. const entriesGPU = [];
  53876. for ( const binding of bindGroup.bindings ) {
  53877. if ( binding.isUniformBuffer ) {
  53878. const bindingData = backend.get( binding );
  53879. if ( bindingData.buffer === undefined ) {
  53880. const byteLength = binding.byteLength;
  53881. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  53882. const visibilities = [];
  53883. if ( binding.visibility & GPUShaderStage.VERTEX ) {
  53884. visibilities.push( 'vertex' );
  53885. }
  53886. if ( binding.visibility & GPUShaderStage.FRAGMENT ) {
  53887. visibilities.push( 'fragment' );
  53888. }
  53889. if ( binding.visibility & GPUShaderStage.COMPUTE ) {
  53890. visibilities.push( 'compute' );
  53891. }
  53892. const bufferVisibility = `(${visibilities.join( ',' )})`;
  53893. const bufferGPU = device.createBuffer( {
  53894. label: `bindingBuffer${binding.id}_${binding.name}_${bufferVisibility}`,
  53895. size: byteLength,
  53896. usage: usage
  53897. } );
  53898. bindingData.buffer = bufferGPU;
  53899. }
  53900. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  53901. } else if ( binding.isStorageBuffer ) {
  53902. const bindingData = backend.get( binding );
  53903. if ( bindingData.buffer === undefined ) {
  53904. const attribute = binding.attribute;
  53905. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  53906. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  53907. bindingData.buffer = backend.get( attribute ).buffer;
  53908. }
  53909. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  53910. } else if ( binding.isSampledTexture ) {
  53911. const textureData = backend.get( binding.texture );
  53912. let resourceGPU;
  53913. if ( textureData.externalTexture !== undefined ) {
  53914. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  53915. } else {
  53916. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  53917. const baseMipLevel = binding.store ? binding.mipLevel : 0;
  53918. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  53919. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  53920. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  53921. }
  53922. propertyName += `-${ mipLevelCount }-${ baseMipLevel }`;
  53923. resourceGPU = textureData[ propertyName ];
  53924. if ( resourceGPU === undefined ) {
  53925. const aspectGPU = GPUTextureAspect.All;
  53926. let dimensionViewGPU;
  53927. if ( binding.isSampledCubeTexture ) {
  53928. dimensionViewGPU = GPUTextureViewDimension.Cube;
  53929. } else if ( binding.isSampledTexture3D ) {
  53930. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  53931. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  53932. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  53933. } else {
  53934. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  53935. }
  53936. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount, baseMipLevel } );
  53937. }
  53938. }
  53939. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  53940. } else if ( binding.isSampler ) {
  53941. const textureGPU = backend.get( binding.texture );
  53942. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  53943. }
  53944. bindingPoint ++;
  53945. }
  53946. return device.createBindGroup( {
  53947. label: 'bindGroup_' + bindGroup.name,
  53948. layout: layoutGPU,
  53949. entries: entriesGPU
  53950. } );
  53951. }
  53952. }
  53953. /**
  53954. * A WebGPU backend utility module for managing pipelines.
  53955. *
  53956. * @private
  53957. */
  53958. class WebGPUPipelineUtils {
  53959. /**
  53960. * Constructs a new utility object.
  53961. *
  53962. * @param {WebGPUBackend} backend - The WebGPU backend.
  53963. */
  53964. constructor( backend ) {
  53965. /**
  53966. * A reference to the WebGPU backend.
  53967. *
  53968. * @type {WebGPUBackend}
  53969. */
  53970. this.backend = backend;
  53971. /**
  53972. * A Weak Map that tracks the active pipeline for render or compute passes.
  53973. *
  53974. * @private
  53975. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  53976. */
  53977. this._activePipelines = new WeakMap();
  53978. }
  53979. /**
  53980. * Sets the given pipeline for the given pass. The method makes sure to only set the
  53981. * pipeline when necessary.
  53982. *
  53983. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  53984. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  53985. */
  53986. setPipeline( pass, pipeline ) {
  53987. const currentPipeline = this._activePipelines.get( pass );
  53988. if ( currentPipeline !== pipeline ) {
  53989. pass.setPipeline( pipeline );
  53990. this._activePipelines.set( pass, pipeline );
  53991. }
  53992. }
  53993. /**
  53994. * Returns the sample count derived from the given render context.
  53995. *
  53996. * @private
  53997. * @param {RenderContext} renderContext - The render context.
  53998. * @return {number} The sample count.
  53999. */
  54000. _getSampleCount( renderContext ) {
  54001. return this.backend.utils.getSampleCountRenderContext( renderContext );
  54002. }
  54003. /**
  54004. * Creates a render pipeline for the given render object.
  54005. *
  54006. * @param {RenderObject} renderObject - The render object.
  54007. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  54008. */
  54009. createRenderPipeline( renderObject, promises ) {
  54010. const { object, material, geometry, pipeline } = renderObject;
  54011. const { vertexProgram, fragmentProgram } = pipeline;
  54012. const backend = this.backend;
  54013. const device = backend.device;
  54014. const utils = backend.utils;
  54015. const pipelineData = backend.get( pipeline );
  54016. // bind group layouts
  54017. const bindGroupLayouts = [];
  54018. for ( const bindGroup of renderObject.getBindings() ) {
  54019. const bindingsData = backend.get( bindGroup );
  54020. bindGroupLayouts.push( bindingsData.layout );
  54021. }
  54022. // vertex buffers
  54023. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  54024. // blending
  54025. let blending;
  54026. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  54027. blending = this._getBlending( material );
  54028. }
  54029. // stencil
  54030. let stencilFront = {};
  54031. if ( material.stencilWrite === true ) {
  54032. stencilFront = {
  54033. compare: this._getStencilCompare( material ),
  54034. failOp: this._getStencilOperation( material.stencilFail ),
  54035. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  54036. passOp: this._getStencilOperation( material.stencilZPass )
  54037. };
  54038. }
  54039. const colorWriteMask = this._getColorWriteMask( material );
  54040. const targets = [];
  54041. if ( renderObject.context.textures !== null ) {
  54042. const textures = renderObject.context.textures;
  54043. for ( let i = 0; i < textures.length; i ++ ) {
  54044. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  54045. if ( i === 0 ) {
  54046. targets.push( {
  54047. format: colorFormat,
  54048. blend: blending,
  54049. writeMask: colorWriteMask
  54050. } );
  54051. } else {
  54052. targets.push( {
  54053. format: colorFormat,
  54054. writeMask: colorWriteMask
  54055. } );
  54056. }
  54057. }
  54058. } else {
  54059. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  54060. targets.push( {
  54061. format: colorFormat,
  54062. blend: blending,
  54063. writeMask: colorWriteMask
  54064. } );
  54065. }
  54066. const vertexModule = backend.get( vertexProgram ).module;
  54067. const fragmentModule = backend.get( fragmentProgram ).module;
  54068. const primitiveState = this._getPrimitiveState( object, geometry, material );
  54069. const depthCompare = this._getDepthCompare( material );
  54070. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  54071. const sampleCount = this._getSampleCount( renderObject.context );
  54072. const pipelineDescriptor = {
  54073. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  54074. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  54075. fragment: Object.assign( {}, fragmentModule, { targets } ),
  54076. primitive: primitiveState,
  54077. multisample: {
  54078. count: sampleCount,
  54079. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  54080. },
  54081. layout: device.createPipelineLayout( {
  54082. bindGroupLayouts
  54083. } )
  54084. };
  54085. const depthStencil = {};
  54086. const renderDepth = renderObject.context.depth;
  54087. const renderStencil = renderObject.context.stencil;
  54088. if ( renderDepth === true || renderStencil === true ) {
  54089. if ( renderDepth === true ) {
  54090. depthStencil.format = depthStencilFormat;
  54091. depthStencil.depthWriteEnabled = material.depthWrite;
  54092. depthStencil.depthCompare = depthCompare;
  54093. }
  54094. if ( renderStencil === true ) {
  54095. depthStencil.stencilFront = stencilFront;
  54096. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  54097. depthStencil.stencilReadMask = material.stencilFuncMask;
  54098. depthStencil.stencilWriteMask = material.stencilWriteMask;
  54099. }
  54100. if ( material.polygonOffset === true ) {
  54101. depthStencil.depthBias = material.polygonOffsetUnits;
  54102. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  54103. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  54104. }
  54105. pipelineDescriptor.depthStencil = depthStencil;
  54106. }
  54107. // create pipeline
  54108. device.pushErrorScope( 'validation' );
  54109. if ( promises === null ) {
  54110. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  54111. device.popErrorScope().then( ( err ) => {
  54112. if ( err !== null ) {
  54113. pipelineData.error = true;
  54114. error( err.message );
  54115. }
  54116. } );
  54117. } else {
  54118. const p = new Promise( async ( resolve /*, reject*/ ) => {
  54119. try {
  54120. pipelineData.pipeline = await device.createRenderPipelineAsync( pipelineDescriptor );
  54121. } catch ( err ) { }
  54122. const errorScope = await device.popErrorScope();
  54123. if ( errorScope !== null ) {
  54124. pipelineData.error = true;
  54125. error( errorScope.message );
  54126. }
  54127. resolve();
  54128. } );
  54129. promises.push( p );
  54130. }
  54131. }
  54132. /**
  54133. * Creates GPU render bundle encoder for the given render context.
  54134. *
  54135. * @param {RenderContext} renderContext - The render context.
  54136. * @param {?string} [label='renderBundleEncoder'] - The label.
  54137. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  54138. */
  54139. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  54140. const backend = this.backend;
  54141. const { utils, device } = backend;
  54142. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  54143. const colorFormats = utils.getCurrentColorFormats( renderContext );
  54144. const sampleCount = this._getSampleCount( renderContext );
  54145. const descriptor = {
  54146. label,
  54147. colorFormats,
  54148. depthStencilFormat,
  54149. sampleCount
  54150. };
  54151. return device.createRenderBundleEncoder( descriptor );
  54152. }
  54153. /**
  54154. * Creates a compute pipeline for the given compute node.
  54155. *
  54156. * @param {ComputePipeline} pipeline - The compute pipeline.
  54157. * @param {Array<BindGroup>} bindings - The bindings.
  54158. */
  54159. createComputePipeline( pipeline, bindings ) {
  54160. const backend = this.backend;
  54161. const device = backend.device;
  54162. const computeProgram = backend.get( pipeline.computeProgram ).module;
  54163. const pipelineGPU = backend.get( pipeline );
  54164. // bind group layouts
  54165. const bindGroupLayouts = [];
  54166. for ( const bindingsGroup of bindings ) {
  54167. const bindingsData = backend.get( bindingsGroup );
  54168. bindGroupLayouts.push( bindingsData.layout );
  54169. }
  54170. pipelineGPU.pipeline = device.createComputePipeline( {
  54171. compute: computeProgram,
  54172. layout: device.createPipelineLayout( {
  54173. bindGroupLayouts
  54174. } )
  54175. } );
  54176. }
  54177. /**
  54178. * Returns the blending state as a descriptor object required
  54179. * for the pipeline creation.
  54180. *
  54181. * @private
  54182. * @param {Material} material - The material.
  54183. * @return {Object} The blending state.
  54184. */
  54185. _getBlending( material ) {
  54186. let color, alpha;
  54187. const blending = material.blending;
  54188. const blendSrc = material.blendSrc;
  54189. const blendDst = material.blendDst;
  54190. const blendEquation = material.blendEquation;
  54191. if ( blending === CustomBlending ) {
  54192. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  54193. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  54194. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  54195. color = {
  54196. srcFactor: this._getBlendFactor( blendSrc ),
  54197. dstFactor: this._getBlendFactor( blendDst ),
  54198. operation: this._getBlendOperation( blendEquation )
  54199. };
  54200. alpha = {
  54201. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  54202. dstFactor: this._getBlendFactor( blendDstAlpha ),
  54203. operation: this._getBlendOperation( blendEquationAlpha )
  54204. };
  54205. } else {
  54206. const premultipliedAlpha = material.premultipliedAlpha;
  54207. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  54208. color = {
  54209. srcFactor: srcRGB,
  54210. dstFactor: dstRGB,
  54211. operation: GPUBlendOperation.Add
  54212. };
  54213. alpha = {
  54214. srcFactor: srcAlpha,
  54215. dstFactor: dstAlpha,
  54216. operation: GPUBlendOperation.Add
  54217. };
  54218. };
  54219. if ( premultipliedAlpha ) {
  54220. switch ( blending ) {
  54221. case NormalBlending:
  54222. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  54223. break;
  54224. case AdditiveBlending:
  54225. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  54226. break;
  54227. case SubtractiveBlending:
  54228. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  54229. break;
  54230. case MultiplyBlending:
  54231. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  54232. break;
  54233. }
  54234. } else {
  54235. switch ( blending ) {
  54236. case NormalBlending:
  54237. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  54238. break;
  54239. case AdditiveBlending:
  54240. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  54241. break;
  54242. case SubtractiveBlending:
  54243. error( 'WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true' );
  54244. break;
  54245. case MultiplyBlending:
  54246. error( 'WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true' );
  54247. break;
  54248. }
  54249. }
  54250. }
  54251. if ( color !== undefined && alpha !== undefined ) {
  54252. return { color, alpha };
  54253. } else {
  54254. error( 'WebGPURenderer: Invalid blending: ', blending );
  54255. }
  54256. }
  54257. /**
  54258. * Returns the GPU blend factor which is required for the pipeline creation.
  54259. *
  54260. * @private
  54261. * @param {number} blend - The blend factor as a three.js constant.
  54262. * @return {string} The GPU blend factor.
  54263. */
  54264. _getBlendFactor( blend ) {
  54265. let blendFactor;
  54266. switch ( blend ) {
  54267. case ZeroFactor:
  54268. blendFactor = GPUBlendFactor.Zero;
  54269. break;
  54270. case OneFactor:
  54271. blendFactor = GPUBlendFactor.One;
  54272. break;
  54273. case SrcColorFactor:
  54274. blendFactor = GPUBlendFactor.Src;
  54275. break;
  54276. case OneMinusSrcColorFactor:
  54277. blendFactor = GPUBlendFactor.OneMinusSrc;
  54278. break;
  54279. case SrcAlphaFactor:
  54280. blendFactor = GPUBlendFactor.SrcAlpha;
  54281. break;
  54282. case OneMinusSrcAlphaFactor:
  54283. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  54284. break;
  54285. case DstColorFactor:
  54286. blendFactor = GPUBlendFactor.Dst;
  54287. break;
  54288. case OneMinusDstColorFactor:
  54289. blendFactor = GPUBlendFactor.OneMinusDst;
  54290. break;
  54291. case DstAlphaFactor:
  54292. blendFactor = GPUBlendFactor.DstAlpha;
  54293. break;
  54294. case OneMinusDstAlphaFactor:
  54295. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  54296. break;
  54297. case SrcAlphaSaturateFactor:
  54298. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  54299. break;
  54300. case BlendColorFactor:
  54301. blendFactor = GPUBlendFactor.Constant;
  54302. break;
  54303. case OneMinusBlendColorFactor:
  54304. blendFactor = GPUBlendFactor.OneMinusConstant;
  54305. break;
  54306. default:
  54307. error( 'WebGPURenderer: Blend factor not supported.', blend );
  54308. }
  54309. return blendFactor;
  54310. }
  54311. /**
  54312. * Returns the GPU stencil compare function which is required for the pipeline creation.
  54313. *
  54314. * @private
  54315. * @param {Material} material - The material.
  54316. * @return {string} The GPU stencil compare function.
  54317. */
  54318. _getStencilCompare( material ) {
  54319. let stencilCompare;
  54320. const stencilFunc = material.stencilFunc;
  54321. switch ( stencilFunc ) {
  54322. case NeverStencilFunc:
  54323. stencilCompare = GPUCompareFunction.Never;
  54324. break;
  54325. case AlwaysStencilFunc:
  54326. stencilCompare = GPUCompareFunction.Always;
  54327. break;
  54328. case LessStencilFunc:
  54329. stencilCompare = GPUCompareFunction.Less;
  54330. break;
  54331. case LessEqualStencilFunc:
  54332. stencilCompare = GPUCompareFunction.LessEqual;
  54333. break;
  54334. case EqualStencilFunc:
  54335. stencilCompare = GPUCompareFunction.Equal;
  54336. break;
  54337. case GreaterEqualStencilFunc:
  54338. stencilCompare = GPUCompareFunction.GreaterEqual;
  54339. break;
  54340. case GreaterStencilFunc:
  54341. stencilCompare = GPUCompareFunction.Greater;
  54342. break;
  54343. case NotEqualStencilFunc:
  54344. stencilCompare = GPUCompareFunction.NotEqual;
  54345. break;
  54346. default:
  54347. error( 'WebGPURenderer: Invalid stencil function.', stencilFunc );
  54348. }
  54349. return stencilCompare;
  54350. }
  54351. /**
  54352. * Returns the GPU stencil operation which is required for the pipeline creation.
  54353. *
  54354. * @private
  54355. * @param {number} op - A three.js constant defining the stencil operation.
  54356. * @return {string} The GPU stencil operation.
  54357. */
  54358. _getStencilOperation( op ) {
  54359. let stencilOperation;
  54360. switch ( op ) {
  54361. case KeepStencilOp:
  54362. stencilOperation = GPUStencilOperation.Keep;
  54363. break;
  54364. case ZeroStencilOp:
  54365. stencilOperation = GPUStencilOperation.Zero;
  54366. break;
  54367. case ReplaceStencilOp:
  54368. stencilOperation = GPUStencilOperation.Replace;
  54369. break;
  54370. case InvertStencilOp:
  54371. stencilOperation = GPUStencilOperation.Invert;
  54372. break;
  54373. case IncrementStencilOp:
  54374. stencilOperation = GPUStencilOperation.IncrementClamp;
  54375. break;
  54376. case DecrementStencilOp:
  54377. stencilOperation = GPUStencilOperation.DecrementClamp;
  54378. break;
  54379. case IncrementWrapStencilOp:
  54380. stencilOperation = GPUStencilOperation.IncrementWrap;
  54381. break;
  54382. case DecrementWrapStencilOp:
  54383. stencilOperation = GPUStencilOperation.DecrementWrap;
  54384. break;
  54385. default:
  54386. error( 'WebGPURenderer: Invalid stencil operation.', stencilOperation );
  54387. }
  54388. return stencilOperation;
  54389. }
  54390. /**
  54391. * Returns the GPU blend operation which is required for the pipeline creation.
  54392. *
  54393. * @private
  54394. * @param {number} blendEquation - A three.js constant defining the blend equation.
  54395. * @return {string} The GPU blend operation.
  54396. */
  54397. _getBlendOperation( blendEquation ) {
  54398. let blendOperation;
  54399. switch ( blendEquation ) {
  54400. case AddEquation:
  54401. blendOperation = GPUBlendOperation.Add;
  54402. break;
  54403. case SubtractEquation:
  54404. blendOperation = GPUBlendOperation.Subtract;
  54405. break;
  54406. case ReverseSubtractEquation:
  54407. blendOperation = GPUBlendOperation.ReverseSubtract;
  54408. break;
  54409. case MinEquation:
  54410. blendOperation = GPUBlendOperation.Min;
  54411. break;
  54412. case MaxEquation:
  54413. blendOperation = GPUBlendOperation.Max;
  54414. break;
  54415. default:
  54416. error( 'WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  54417. }
  54418. return blendOperation;
  54419. }
  54420. /**
  54421. * Returns the primitive state as a descriptor object required
  54422. * for the pipeline creation.
  54423. *
  54424. * @private
  54425. * @param {Object3D} object - The 3D object.
  54426. * @param {BufferGeometry} geometry - The geometry.
  54427. * @param {Material} material - The material.
  54428. * @return {Object} The primitive state.
  54429. */
  54430. _getPrimitiveState( object, geometry, material ) {
  54431. const descriptor = {};
  54432. const utils = this.backend.utils;
  54433. //
  54434. descriptor.topology = utils.getPrimitiveTopology( object, material );
  54435. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  54436. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  54437. }
  54438. //
  54439. let flipSided = ( material.side === BackSide );
  54440. if ( object.isMesh && object.matrixWorld.determinant() < 0 ) flipSided = ! flipSided;
  54441. descriptor.frontFace = ( flipSided === true ) ? GPUFrontFace.CW : GPUFrontFace.CCW;
  54442. //
  54443. descriptor.cullMode = ( material.side === DoubleSide ) ? GPUCullMode.None : GPUCullMode.Back;
  54444. return descriptor;
  54445. }
  54446. /**
  54447. * Returns the GPU color write mask which is required for the pipeline creation.
  54448. *
  54449. * @private
  54450. * @param {Material} material - The material.
  54451. * @return {number} The GPU color write mask.
  54452. */
  54453. _getColorWriteMask( material ) {
  54454. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  54455. }
  54456. /**
  54457. * Returns the GPU depth compare function which is required for the pipeline creation.
  54458. *
  54459. * @private
  54460. * @param {Material} material - The material.
  54461. * @return {string} The GPU depth compare function.
  54462. */
  54463. _getDepthCompare( material ) {
  54464. let depthCompare;
  54465. if ( material.depthTest === false ) {
  54466. depthCompare = GPUCompareFunction.Always;
  54467. } else {
  54468. const depthFunc = material.depthFunc;
  54469. switch ( depthFunc ) {
  54470. case NeverDepth:
  54471. depthCompare = GPUCompareFunction.Never;
  54472. break;
  54473. case AlwaysDepth:
  54474. depthCompare = GPUCompareFunction.Always;
  54475. break;
  54476. case LessDepth:
  54477. depthCompare = GPUCompareFunction.Less;
  54478. break;
  54479. case LessEqualDepth:
  54480. depthCompare = GPUCompareFunction.LessEqual;
  54481. break;
  54482. case EqualDepth:
  54483. depthCompare = GPUCompareFunction.Equal;
  54484. break;
  54485. case GreaterEqualDepth:
  54486. depthCompare = GPUCompareFunction.GreaterEqual;
  54487. break;
  54488. case GreaterDepth:
  54489. depthCompare = GPUCompareFunction.Greater;
  54490. break;
  54491. case NotEqualDepth:
  54492. depthCompare = GPUCompareFunction.NotEqual;
  54493. break;
  54494. default:
  54495. error( 'WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  54496. }
  54497. }
  54498. return depthCompare;
  54499. }
  54500. }
  54501. /**
  54502. * Manages a pool of WebGPU timestamp queries for performance measurement.
  54503. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  54504. *
  54505. * @augments TimestampQueryPool
  54506. */
  54507. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  54508. /**
  54509. * Creates a new WebGPU timestamp query pool.
  54510. *
  54511. * @param {GPUDevice} device - The WebGPU device to create queries on.
  54512. * @param {string} type - The type identifier for this query pool.
  54513. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  54514. */
  54515. constructor( device, type, maxQueries = 2048 ) {
  54516. super( maxQueries );
  54517. this.device = device;
  54518. this.type = type;
  54519. this.querySet = this.device.createQuerySet( {
  54520. type: 'timestamp',
  54521. count: this.maxQueries,
  54522. label: `queryset_global_timestamp_${type}`
  54523. } );
  54524. const bufferSize = this.maxQueries * 8;
  54525. this.resolveBuffer = this.device.createBuffer( {
  54526. label: `buffer_timestamp_resolve_${type}`,
  54527. size: bufferSize,
  54528. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  54529. } );
  54530. this.resultBuffer = this.device.createBuffer( {
  54531. label: `buffer_timestamp_result_${type}`,
  54532. size: bufferSize,
  54533. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  54534. } );
  54535. }
  54536. /**
  54537. * Allocates a pair of queries for a given render context.
  54538. *
  54539. * @param {string} uid - A unique identifier for the render context.
  54540. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  54541. */
  54542. allocateQueriesForContext( uid ) {
  54543. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  54544. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  54545. 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() } ).` );
  54546. return null;
  54547. }
  54548. const baseOffset = this.currentQueryIndex;
  54549. this.currentQueryIndex += 2;
  54550. this.queryOffsets.set( uid, baseOffset );
  54551. return baseOffset;
  54552. }
  54553. /**
  54554. * Asynchronously resolves all pending queries and returns the total duration.
  54555. * If there's already a pending resolve operation, returns that promise instead.
  54556. *
  54557. * @async
  54558. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  54559. */
  54560. async resolveQueriesAsync() {
  54561. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  54562. return this.lastValue;
  54563. }
  54564. if ( this.pendingResolve ) {
  54565. return this.pendingResolve;
  54566. }
  54567. this.pendingResolve = this._resolveQueries();
  54568. try {
  54569. const result = await this.pendingResolve;
  54570. return result;
  54571. } finally {
  54572. this.pendingResolve = null;
  54573. }
  54574. }
  54575. /**
  54576. * Internal method to resolve queries and calculate total duration.
  54577. *
  54578. * @async
  54579. * @private
  54580. * @returns {Promise<number>} The total duration in milliseconds.
  54581. */
  54582. async _resolveQueries() {
  54583. if ( this.isDisposed ) {
  54584. return this.lastValue;
  54585. }
  54586. try {
  54587. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  54588. return this.lastValue;
  54589. }
  54590. const currentOffsets = new Map( this.queryOffsets );
  54591. const queryCount = this.currentQueryIndex;
  54592. const bytesUsed = queryCount * 8;
  54593. // Reset state before GPU work
  54594. this.currentQueryIndex = 0;
  54595. this.queryOffsets.clear();
  54596. const commandEncoder = this.device.createCommandEncoder();
  54597. commandEncoder.resolveQuerySet(
  54598. this.querySet,
  54599. 0,
  54600. queryCount,
  54601. this.resolveBuffer,
  54602. 0
  54603. );
  54604. commandEncoder.copyBufferToBuffer(
  54605. this.resolveBuffer,
  54606. 0,
  54607. this.resultBuffer,
  54608. 0,
  54609. bytesUsed
  54610. );
  54611. const commandBuffer = commandEncoder.finish();
  54612. this.device.queue.submit( [ commandBuffer ] );
  54613. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  54614. return this.lastValue;
  54615. }
  54616. // Create and track the mapping operation
  54617. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  54618. if ( this.isDisposed ) {
  54619. if ( this.resultBuffer.mapState === 'mapped' ) {
  54620. this.resultBuffer.unmap();
  54621. }
  54622. return this.lastValue;
  54623. }
  54624. //
  54625. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  54626. const framesDuration = {};
  54627. const frames = [];
  54628. for ( const [ uid, baseOffset ] of currentOffsets ) {
  54629. const match = uid.match( /^(.*):f(\d+)$/ );
  54630. const frame = parseInt( match[ 2 ] );
  54631. if ( frames.includes( frame ) === false ) {
  54632. frames.push( frame );
  54633. }
  54634. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  54635. const startTime = times[ baseOffset ];
  54636. const endTime = times[ baseOffset + 1 ];
  54637. const duration = Number( endTime - startTime ) / 1e6;
  54638. this.timestamps.set( uid, duration );
  54639. framesDuration[ frame ] += duration;
  54640. }
  54641. // Return the total duration of the last frame
  54642. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  54643. this.resultBuffer.unmap();
  54644. this.lastValue = totalDuration;
  54645. this.frames = frames;
  54646. return totalDuration;
  54647. } catch ( e ) {
  54648. error( 'Error resolving queries:', e );
  54649. if ( this.resultBuffer.mapState === 'mapped' ) {
  54650. this.resultBuffer.unmap();
  54651. }
  54652. return this.lastValue;
  54653. }
  54654. }
  54655. /**
  54656. * Dispose of the query pool.
  54657. *
  54658. * @async
  54659. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  54660. */
  54661. async dispose() {
  54662. if ( this.isDisposed ) {
  54663. return;
  54664. }
  54665. this.isDisposed = true;
  54666. // Wait for pending resolve operation
  54667. if ( this.pendingResolve ) {
  54668. try {
  54669. await this.pendingResolve;
  54670. } catch ( e ) {
  54671. error( 'Error waiting for pending resolve:', e );
  54672. }
  54673. }
  54674. // Ensure buffer is unmapped before destroying
  54675. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  54676. try {
  54677. this.resultBuffer.unmap();
  54678. } catch ( e ) {
  54679. error( 'Error unmapping buffer:', e );
  54680. }
  54681. }
  54682. // Destroy resources
  54683. if ( this.querySet ) {
  54684. this.querySet.destroy();
  54685. this.querySet = null;
  54686. }
  54687. if ( this.resolveBuffer ) {
  54688. this.resolveBuffer.destroy();
  54689. this.resolveBuffer = null;
  54690. }
  54691. if ( this.resultBuffer ) {
  54692. this.resultBuffer.destroy();
  54693. this.resultBuffer = null;
  54694. }
  54695. this.queryOffsets.clear();
  54696. this.pendingResolve = null;
  54697. }
  54698. }
  54699. /*// debugger tools
  54700. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  54701. //*/
  54702. /**
  54703. * A backend implementation targeting WebGPU.
  54704. *
  54705. * @private
  54706. * @augments Backend
  54707. */
  54708. class WebGPUBackend extends Backend {
  54709. /**
  54710. * WebGPUBackend options.
  54711. *
  54712. * @typedef {Object} WebGPUBackend~Options
  54713. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  54714. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  54715. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  54716. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  54717. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  54718. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  54719. * @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.
  54720. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  54721. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  54722. * @property {string} [powerPreference=undefined] - The power preference.
  54723. * @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.
  54724. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  54725. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  54726. */
  54727. /**
  54728. * Constructs a new WebGPU backend.
  54729. *
  54730. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  54731. */
  54732. constructor( parameters = {} ) {
  54733. super( parameters );
  54734. /**
  54735. * This flag can be used for type testing.
  54736. *
  54737. * @type {boolean}
  54738. * @readonly
  54739. * @default true
  54740. */
  54741. this.isWebGPUBackend = true;
  54742. // some parameters require default values other than "undefined"
  54743. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  54744. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  54745. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  54746. /**
  54747. * Indicates whether the backend is in compatibility mode or not.
  54748. * @type {boolean}
  54749. * @default false
  54750. */
  54751. this.compatibilityMode = this.parameters.compatibilityMode;
  54752. /**
  54753. * A reference to the device.
  54754. *
  54755. * @type {?GPUDevice}
  54756. * @default null
  54757. */
  54758. this.device = null;
  54759. /**
  54760. * A reference to the default render pass descriptor.
  54761. *
  54762. * @type {?Object}
  54763. * @default null
  54764. */
  54765. this.defaultRenderPassdescriptor = null;
  54766. /**
  54767. * A reference to a backend module holding common utility functions.
  54768. *
  54769. * @type {WebGPUUtils}
  54770. */
  54771. this.utils = new WebGPUUtils( this );
  54772. /**
  54773. * A reference to a backend module holding shader attribute-related
  54774. * utility functions.
  54775. *
  54776. * @type {WebGPUAttributeUtils}
  54777. */
  54778. this.attributeUtils = new WebGPUAttributeUtils( this );
  54779. /**
  54780. * A reference to a backend module holding shader binding-related
  54781. * utility functions.
  54782. *
  54783. * @type {WebGPUBindingUtils}
  54784. */
  54785. this.bindingUtils = new WebGPUBindingUtils( this );
  54786. /**
  54787. * A reference to a backend module holding shader pipeline-related
  54788. * utility functions.
  54789. *
  54790. * @type {WebGPUPipelineUtils}
  54791. */
  54792. this.pipelineUtils = new WebGPUPipelineUtils( this );
  54793. /**
  54794. * A reference to a backend module holding shader texture-related
  54795. * utility functions.
  54796. *
  54797. * @type {WebGPUTextureUtils}
  54798. */
  54799. this.textureUtils = new WebGPUTextureUtils( this );
  54800. /**
  54801. * A map that manages the resolve buffers for occlusion queries.
  54802. *
  54803. * @type {Map<number,GPUBuffer>}
  54804. */
  54805. this.occludedResolveCache = new Map();
  54806. }
  54807. /**
  54808. * Initializes the backend so it is ready for usage.
  54809. *
  54810. * @async
  54811. * @param {Renderer} renderer - The renderer.
  54812. * @return {Promise} A Promise that resolves when the backend has been initialized.
  54813. */
  54814. async init( renderer ) {
  54815. await super.init( renderer );
  54816. //
  54817. const parameters = this.parameters;
  54818. // create the device if it is not passed with parameters
  54819. let device;
  54820. if ( parameters.device === undefined ) {
  54821. const adapterOptions = {
  54822. powerPreference: parameters.powerPreference,
  54823. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  54824. };
  54825. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  54826. if ( adapter === null ) {
  54827. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  54828. }
  54829. // feature support
  54830. const features = Object.values( GPUFeatureName );
  54831. const supportedFeatures = [];
  54832. for ( const name of features ) {
  54833. if ( adapter.features.has( name ) ) {
  54834. supportedFeatures.push( name );
  54835. }
  54836. }
  54837. const deviceDescriptor = {
  54838. requiredFeatures: supportedFeatures,
  54839. requiredLimits: parameters.requiredLimits
  54840. };
  54841. device = await adapter.requestDevice( deviceDescriptor );
  54842. } else {
  54843. device = parameters.device;
  54844. }
  54845. device.lost.then( ( info ) => {
  54846. const deviceLossInfo = {
  54847. api: 'WebGPU',
  54848. message: info.message || 'Unknown reason',
  54849. reason: info.reason || null,
  54850. originalEvent: info
  54851. };
  54852. renderer.onDeviceLost( deviceLossInfo );
  54853. } );
  54854. this.device = device;
  54855. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  54856. this.updateSize();
  54857. }
  54858. /**
  54859. * A reference to the context.
  54860. *
  54861. * @type {?GPUCanvasContext}
  54862. * @default null
  54863. */
  54864. get context() {
  54865. const canvasTarget = this.renderer.getCanvasTarget();
  54866. const canvasData = this.get( canvasTarget );
  54867. let context = canvasData.context;
  54868. if ( context === undefined ) {
  54869. const parameters = this.parameters;
  54870. if ( canvasTarget.isDefaultCanvasTarget === true && parameters.context !== undefined ) {
  54871. context = parameters.context;
  54872. } else {
  54873. context = canvasTarget.domElement.getContext( 'webgpu' );
  54874. }
  54875. // OffscreenCanvas does not have setAttribute, see #22811
  54876. if ( 'setAttribute' in canvasTarget.domElement ) canvasTarget.domElement.setAttribute( 'data-engine', `three.js r${ REVISION } webgpu` );
  54877. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  54878. const toneMappingMode = parameters.outputType === HalfFloatType ? 'extended' : 'standard';
  54879. context.configure( {
  54880. device: this.device,
  54881. format: this.utils.getPreferredCanvasFormat(),
  54882. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  54883. alphaMode: alphaMode,
  54884. toneMapping: {
  54885. mode: toneMappingMode
  54886. }
  54887. } );
  54888. canvasData.context = context;
  54889. }
  54890. return context;
  54891. }
  54892. /**
  54893. * The coordinate system of the backend.
  54894. *
  54895. * @type {number}
  54896. * @readonly
  54897. */
  54898. get coordinateSystem() {
  54899. return WebGPUCoordinateSystem;
  54900. }
  54901. /**
  54902. * This method performs a readback operation by moving buffer data from
  54903. * a storage buffer attribute from the GPU to the CPU.
  54904. *
  54905. * @async
  54906. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  54907. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  54908. */
  54909. async getArrayBufferAsync( attribute ) {
  54910. return await this.attributeUtils.getArrayBufferAsync( attribute );
  54911. }
  54912. /**
  54913. * Returns the backend's rendering context.
  54914. *
  54915. * @return {GPUCanvasContext} The rendering context.
  54916. */
  54917. getContext() {
  54918. return this.context;
  54919. }
  54920. /**
  54921. * Returns the default render pass descriptor.
  54922. *
  54923. * In WebGPU, the default framebuffer must be configured
  54924. * like custom framebuffers so the backend needs a render
  54925. * pass descriptor even when rendering directly to screen.
  54926. *
  54927. * @private
  54928. * @return {Object} The render pass descriptor.
  54929. */
  54930. _getDefaultRenderPassDescriptor() {
  54931. const renderer = this.renderer;
  54932. const canvasTarget = renderer.getCanvasTarget();
  54933. const canvasData = this.get( canvasTarget );
  54934. const samples = renderer.currentSamples;
  54935. let descriptor = canvasData.descriptor;
  54936. if ( descriptor === undefined || canvasData.samples !== samples ) {
  54937. descriptor = {
  54938. colorAttachments: [ {
  54939. view: null
  54940. } ]
  54941. };
  54942. if ( renderer.depth === true || renderer.stencil === true ) {
  54943. descriptor.depthStencilAttachment = {
  54944. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  54945. };
  54946. }
  54947. const colorAttachment = descriptor.colorAttachments[ 0 ];
  54948. if ( samples > 0 ) {
  54949. colorAttachment.view = this.textureUtils.getColorBuffer().createView();
  54950. } else {
  54951. colorAttachment.resolveTarget = undefined;
  54952. }
  54953. canvasData.descriptor = descriptor;
  54954. canvasData.samples = samples;
  54955. }
  54956. const colorAttachment = descriptor.colorAttachments[ 0 ];
  54957. if ( samples > 0 ) {
  54958. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  54959. } else {
  54960. colorAttachment.view = this.context.getCurrentTexture().createView();
  54961. }
  54962. return descriptor;
  54963. }
  54964. /**
  54965. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  54966. *
  54967. * @param {RenderContext} renderContext - The render context.
  54968. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  54969. *
  54970. * @private
  54971. */
  54972. _isRenderCameraDepthArray( renderContext ) {
  54973. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  54974. }
  54975. /**
  54976. * Returns the render pass descriptor for the given render context.
  54977. *
  54978. * @private
  54979. * @param {RenderContext} renderContext - The render context.
  54980. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  54981. * @return {Object} The render pass descriptor.
  54982. */
  54983. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  54984. const renderTarget = renderContext.renderTarget;
  54985. const renderTargetData = this.get( renderTarget );
  54986. let descriptors = renderTargetData.descriptors;
  54987. if ( descriptors === undefined ||
  54988. renderTargetData.width !== renderTarget.width ||
  54989. renderTargetData.height !== renderTarget.height ||
  54990. renderTargetData.samples !== renderTarget.samples
  54991. ) {
  54992. descriptors = {};
  54993. renderTargetData.descriptors = descriptors;
  54994. }
  54995. const cacheKey = renderContext.getCacheKey();
  54996. let descriptorBase = descriptors[ cacheKey ];
  54997. if ( descriptorBase === undefined ) {
  54998. const textures = renderContext.textures;
  54999. const textureViews = [];
  55000. let sliceIndex;
  55001. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  55002. for ( let i = 0; i < textures.length; i ++ ) {
  55003. const textureData = this.get( textures[ i ] );
  55004. const viewDescriptor = {
  55005. label: `colorAttachment_${ i }`,
  55006. baseMipLevel: renderContext.activeMipmapLevel,
  55007. mipLevelCount: 1,
  55008. baseArrayLayer: renderContext.activeCubeFace,
  55009. arrayLayerCount: 1,
  55010. dimension: GPUTextureViewDimension.TwoD
  55011. };
  55012. if ( renderTarget.isRenderTarget3D ) {
  55013. sliceIndex = renderContext.activeCubeFace;
  55014. viewDescriptor.baseArrayLayer = 0;
  55015. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  55016. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  55017. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  55018. if ( isRenderCameraDepthArray === true ) {
  55019. const cameras = renderContext.camera.cameras;
  55020. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  55021. const layerViewDescriptor = {
  55022. ...viewDescriptor,
  55023. baseArrayLayer: layer,
  55024. arrayLayerCount: 1,
  55025. dimension: GPUTextureViewDimension.TwoD
  55026. };
  55027. const textureView = textureData.texture.createView( layerViewDescriptor );
  55028. textureViews.push( {
  55029. view: textureView,
  55030. resolveTarget: undefined,
  55031. depthSlice: undefined
  55032. } );
  55033. }
  55034. } else {
  55035. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  55036. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  55037. }
  55038. }
  55039. if ( isRenderCameraDepthArray !== true ) {
  55040. const textureView = textureData.texture.createView( viewDescriptor );
  55041. let view, resolveTarget;
  55042. if ( textureData.msaaTexture !== undefined ) {
  55043. view = textureData.msaaTexture.createView();
  55044. resolveTarget = textureView;
  55045. } else {
  55046. view = textureView;
  55047. resolveTarget = undefined;
  55048. }
  55049. textureViews.push( {
  55050. view,
  55051. resolveTarget,
  55052. depthSlice: sliceIndex
  55053. } );
  55054. }
  55055. }
  55056. descriptorBase = { textureViews };
  55057. if ( renderContext.depth ) {
  55058. const depthTextureData = this.get( renderContext.depthTexture );
  55059. const options = {};
  55060. if ( renderContext.depthTexture.isArrayTexture ) {
  55061. options.dimension = GPUTextureViewDimension.TwoD;
  55062. options.arrayLayerCount = 1;
  55063. options.baseArrayLayer = renderContext.activeCubeFace;
  55064. }
  55065. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  55066. }
  55067. descriptors[ cacheKey ] = descriptorBase;
  55068. renderTargetData.width = renderTarget.width;
  55069. renderTargetData.height = renderTarget.height;
  55070. renderTargetData.samples = renderTarget.samples;
  55071. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  55072. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  55073. }
  55074. const descriptor = {
  55075. colorAttachments: []
  55076. };
  55077. // Apply dynamic properties to cached views
  55078. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  55079. const viewInfo = descriptorBase.textureViews[ i ];
  55080. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  55081. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  55082. clearValue = colorAttachmentsConfig.clearValue;
  55083. }
  55084. descriptor.colorAttachments.push( {
  55085. view: viewInfo.view,
  55086. depthSlice: viewInfo.depthSlice,
  55087. resolveTarget: viewInfo.resolveTarget,
  55088. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  55089. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  55090. clearValue: clearValue
  55091. } );
  55092. }
  55093. if ( descriptorBase.depthStencilView ) {
  55094. descriptor.depthStencilAttachment = {
  55095. view: descriptorBase.depthStencilView
  55096. };
  55097. }
  55098. return descriptor;
  55099. }
  55100. /**
  55101. * This method is executed at the beginning of a render call and prepares
  55102. * the WebGPU state for upcoming render calls
  55103. *
  55104. * @param {RenderContext} renderContext - The render context.
  55105. */
  55106. beginRender( renderContext ) {
  55107. const renderContextData = this.get( renderContext );
  55108. //
  55109. const device = this.device;
  55110. const occlusionQueryCount = renderContext.occlusionQueryCount;
  55111. let occlusionQuerySet;
  55112. if ( occlusionQueryCount > 0 ) {
  55113. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  55114. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  55115. // Get a reference to the array of objects with queries. The renderContextData property
  55116. // can be changed by another render pass before the buffer.mapAsyc() completes.
  55117. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  55118. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  55119. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  55120. //
  55121. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  55122. renderContextData.occlusionQuerySet = occlusionQuerySet;
  55123. renderContextData.occlusionQueryIndex = 0;
  55124. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  55125. renderContextData.lastOcclusionObject = null;
  55126. }
  55127. let descriptor;
  55128. if ( renderContext.textures === null ) {
  55129. descriptor = this._getDefaultRenderPassDescriptor();
  55130. } else {
  55131. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  55132. }
  55133. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ), descriptor );
  55134. descriptor.occlusionQuerySet = occlusionQuerySet;
  55135. const depthStencilAttachment = descriptor.depthStencilAttachment;
  55136. if ( renderContext.textures !== null ) {
  55137. const colorAttachments = descriptor.colorAttachments;
  55138. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  55139. const colorAttachment = colorAttachments[ i ];
  55140. if ( renderContext.clearColor ) {
  55141. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  55142. colorAttachment.loadOp = GPULoadOp.Clear;
  55143. } else {
  55144. colorAttachment.loadOp = GPULoadOp.Load;
  55145. }
  55146. colorAttachment.storeOp = GPUStoreOp.Store;
  55147. }
  55148. } else {
  55149. const colorAttachment = descriptor.colorAttachments[ 0 ];
  55150. if ( renderContext.clearColor ) {
  55151. colorAttachment.clearValue = renderContext.clearColorValue;
  55152. colorAttachment.loadOp = GPULoadOp.Clear;
  55153. } else {
  55154. colorAttachment.loadOp = GPULoadOp.Load;
  55155. }
  55156. colorAttachment.storeOp = GPUStoreOp.Store;
  55157. }
  55158. //
  55159. if ( renderContext.depth ) {
  55160. if ( renderContext.clearDepth ) {
  55161. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  55162. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  55163. } else {
  55164. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  55165. }
  55166. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  55167. }
  55168. if ( renderContext.stencil ) {
  55169. if ( renderContext.clearStencil ) {
  55170. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  55171. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  55172. } else {
  55173. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  55174. }
  55175. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  55176. }
  55177. //
  55178. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  55179. // shadow arrays - prepare bundle encoders for each camera in an array camera
  55180. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  55181. const cameras = renderContext.camera.cameras;
  55182. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  55183. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  55184. } else {
  55185. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  55186. }
  55187. // Create bundle encoders for each layer
  55188. renderContextData.bundleEncoders = [];
  55189. renderContextData.bundleSets = [];
  55190. // Create separate bundle encoders for each camera in the array
  55191. for ( let i = 0; i < cameras.length; i ++ ) {
  55192. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  55193. renderContext,
  55194. 'renderBundleArrayCamera_' + i
  55195. );
  55196. // Initialize state tracking for this bundle
  55197. const bundleSets = {
  55198. attributes: {},
  55199. bindingGroups: [],
  55200. pipeline: null,
  55201. index: null
  55202. };
  55203. renderContextData.bundleEncoders.push( bundleEncoder );
  55204. renderContextData.bundleSets.push( bundleSets );
  55205. }
  55206. // We'll complete the bundles in finishRender
  55207. renderContextData.currentPass = null;
  55208. } else {
  55209. const currentPass = encoder.beginRenderPass( descriptor );
  55210. renderContextData.currentPass = currentPass;
  55211. if ( renderContext.viewport ) {
  55212. this.updateViewport( renderContext );
  55213. }
  55214. if ( renderContext.scissor ) {
  55215. this.updateScissor( renderContext );
  55216. }
  55217. }
  55218. //
  55219. renderContextData.descriptor = descriptor;
  55220. renderContextData.encoder = encoder;
  55221. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  55222. renderContextData.renderBundles = [];
  55223. }
  55224. /**
  55225. * This method creates layer descriptors for each camera in an array camera
  55226. * to prepare for rendering to a depth array texture.
  55227. *
  55228. * @param {RenderContext} renderContext - The render context.
  55229. * @param {Object} renderContextData - The render context data.
  55230. * @param {Object} descriptor - The render pass descriptor.
  55231. * @param {ArrayCamera} cameras - The array camera.
  55232. *
  55233. * @private
  55234. */
  55235. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  55236. const depthStencilAttachment = descriptor.depthStencilAttachment;
  55237. renderContextData.layerDescriptors = [];
  55238. const depthTextureData = this.get( renderContext.depthTexture );
  55239. if ( ! depthTextureData.viewCache ) {
  55240. depthTextureData.viewCache = [];
  55241. }
  55242. for ( let i = 0; i < cameras.length; i ++ ) {
  55243. const layerDescriptor = {
  55244. ...descriptor,
  55245. colorAttachments: [ {
  55246. ...descriptor.colorAttachments[ 0 ],
  55247. view: descriptor.colorAttachments[ i ].view
  55248. } ]
  55249. };
  55250. if ( descriptor.depthStencilAttachment ) {
  55251. const layerIndex = i;
  55252. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  55253. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  55254. dimension: GPUTextureViewDimension.TwoD,
  55255. baseArrayLayer: i,
  55256. arrayLayerCount: 1
  55257. } );
  55258. }
  55259. layerDescriptor.depthStencilAttachment = {
  55260. view: depthTextureData.viewCache[ layerIndex ],
  55261. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  55262. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  55263. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  55264. };
  55265. if ( renderContext.stencil ) {
  55266. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  55267. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  55268. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  55269. }
  55270. } else {
  55271. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  55272. }
  55273. renderContextData.layerDescriptors.push( layerDescriptor );
  55274. }
  55275. }
  55276. /**
  55277. * This method updates the layer descriptors for each camera in an array camera
  55278. * to prepare for rendering to a depth array texture.
  55279. *
  55280. * @param {RenderContext} renderContext - The render context.
  55281. * @param {Object} renderContextData - The render context data.
  55282. * @param {ArrayCamera} cameras - The array camera.
  55283. *
  55284. */
  55285. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  55286. for ( let i = 0; i < cameras.length; i ++ ) {
  55287. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  55288. if ( layerDescriptor.depthStencilAttachment ) {
  55289. const depthAttachment = layerDescriptor.depthStencilAttachment;
  55290. if ( renderContext.depth ) {
  55291. if ( renderContext.clearDepth ) {
  55292. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  55293. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  55294. } else {
  55295. depthAttachment.depthLoadOp = GPULoadOp.Load;
  55296. }
  55297. }
  55298. if ( renderContext.stencil ) {
  55299. if ( renderContext.clearStencil ) {
  55300. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  55301. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  55302. } else {
  55303. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  55304. }
  55305. }
  55306. }
  55307. }
  55308. }
  55309. /**
  55310. * This method is executed at the end of a render call and finalizes work
  55311. * after draw calls.
  55312. *
  55313. * @param {RenderContext} renderContext - The render context.
  55314. */
  55315. finishRender( renderContext ) {
  55316. const renderContextData = this.get( renderContext );
  55317. const occlusionQueryCount = renderContext.occlusionQueryCount;
  55318. if ( renderContextData.renderBundles.length > 0 ) {
  55319. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  55320. }
  55321. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  55322. renderContextData.currentPass.endOcclusionQuery();
  55323. }
  55324. // shadow arrays - Execute bundles for each layer
  55325. const encoder = renderContextData.encoder;
  55326. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  55327. const bundles = [];
  55328. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  55329. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  55330. bundles.push( bundleEncoder.finish() );
  55331. }
  55332. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  55333. if ( i < bundles.length ) {
  55334. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  55335. const renderPass = encoder.beginRenderPass( layerDescriptor );
  55336. if ( renderContext.viewport ) {
  55337. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  55338. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  55339. }
  55340. if ( renderContext.scissor ) {
  55341. const { x, y, width, height } = renderContext.scissorValue;
  55342. renderPass.setScissorRect( x, y, width, height );
  55343. }
  55344. renderPass.executeBundles( [ bundles[ i ] ] );
  55345. renderPass.end();
  55346. }
  55347. }
  55348. } else if ( renderContextData.currentPass ) {
  55349. renderContextData.currentPass.end();
  55350. }
  55351. if ( occlusionQueryCount > 0 ) {
  55352. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  55353. //
  55354. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  55355. if ( queryResolveBuffer === undefined ) {
  55356. queryResolveBuffer = this.device.createBuffer(
  55357. {
  55358. size: bufferSize,
  55359. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  55360. }
  55361. );
  55362. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  55363. }
  55364. //
  55365. const readBuffer = this.device.createBuffer(
  55366. {
  55367. size: bufferSize,
  55368. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  55369. }
  55370. );
  55371. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  55372. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  55373. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  55374. renderContextData.occlusionQueryBuffer = readBuffer;
  55375. //
  55376. this.resolveOccludedAsync( renderContext );
  55377. }
  55378. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  55379. //
  55380. if ( renderContext.textures !== null ) {
  55381. const textures = renderContext.textures;
  55382. for ( let i = 0; i < textures.length; i ++ ) {
  55383. const texture = textures[ i ];
  55384. if ( texture.generateMipmaps === true ) {
  55385. this.textureUtils.generateMipmaps( texture );
  55386. }
  55387. }
  55388. }
  55389. }
  55390. /**
  55391. * Returns `true` if the given 3D object is fully occluded by other
  55392. * 3D objects in the scene.
  55393. *
  55394. * @param {RenderContext} renderContext - The render context.
  55395. * @param {Object3D} object - The 3D object to test.
  55396. * @return {boolean} Whether the 3D object is fully occluded or not.
  55397. */
  55398. isOccluded( renderContext, object ) {
  55399. const renderContextData = this.get( renderContext );
  55400. return renderContextData.occluded && renderContextData.occluded.has( object );
  55401. }
  55402. /**
  55403. * This method processes the result of occlusion queries and writes it
  55404. * into render context data.
  55405. *
  55406. * @async
  55407. * @param {RenderContext} renderContext - The render context.
  55408. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  55409. */
  55410. async resolveOccludedAsync( renderContext ) {
  55411. const renderContextData = this.get( renderContext );
  55412. // handle occlusion query results
  55413. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  55414. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  55415. const occluded = new WeakSet();
  55416. renderContextData.currentOcclusionQueryObjects = null;
  55417. renderContextData.currentOcclusionQueryBuffer = null;
  55418. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  55419. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  55420. const results = new BigUint64Array( buffer );
  55421. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  55422. if ( results[ i ] === BigInt( 0 ) ) {
  55423. occluded.add( currentOcclusionQueryObjects[ i ] );
  55424. }
  55425. }
  55426. currentOcclusionQueryBuffer.destroy();
  55427. renderContextData.occluded = occluded;
  55428. }
  55429. }
  55430. /**
  55431. * Updates the viewport with the values from the given render context.
  55432. *
  55433. * @param {RenderContext} renderContext - The render context.
  55434. */
  55435. updateViewport( renderContext ) {
  55436. const { currentPass } = this.get( renderContext );
  55437. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  55438. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  55439. }
  55440. /**
  55441. * Updates the scissor with the values from the given render context.
  55442. *
  55443. * @param {RenderContext} renderContext - The render context.
  55444. */
  55445. updateScissor( renderContext ) {
  55446. const { currentPass } = this.get( renderContext );
  55447. const { x, y, width, height } = renderContext.scissorValue;
  55448. currentPass.setScissorRect( x, y, width, height );
  55449. }
  55450. /**
  55451. * Returns the clear color and alpha into a single
  55452. * color object.
  55453. *
  55454. * @return {Color4} The clear color.
  55455. */
  55456. getClearColor() {
  55457. const clearColor = super.getClearColor();
  55458. // only premultiply alpha when alphaMode is "premultiplied"
  55459. if ( this.renderer.alpha === true ) {
  55460. clearColor.r *= clearColor.a;
  55461. clearColor.g *= clearColor.a;
  55462. clearColor.b *= clearColor.a;
  55463. }
  55464. return clearColor;
  55465. }
  55466. /**
  55467. * Performs a clear operation.
  55468. *
  55469. * @param {boolean} color - Whether the color buffer should be cleared or not.
  55470. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  55471. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  55472. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  55473. */
  55474. clear( color, depth, stencil, renderTargetContext = null ) {
  55475. const device = this.device;
  55476. const renderer = this.renderer;
  55477. let colorAttachments = [];
  55478. let depthStencilAttachment;
  55479. let clearValue;
  55480. let supportsDepth;
  55481. let supportsStencil;
  55482. if ( color ) {
  55483. const clearColor = this.getClearColor();
  55484. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  55485. }
  55486. if ( renderTargetContext === null ) {
  55487. supportsDepth = renderer.depth;
  55488. supportsStencil = renderer.stencil;
  55489. const descriptor = this._getDefaultRenderPassDescriptor();
  55490. if ( color ) {
  55491. colorAttachments = descriptor.colorAttachments;
  55492. const colorAttachment = colorAttachments[ 0 ];
  55493. colorAttachment.clearValue = clearValue;
  55494. colorAttachment.loadOp = GPULoadOp.Clear;
  55495. colorAttachment.storeOp = GPUStoreOp.Store;
  55496. }
  55497. if ( supportsDepth || supportsStencil ) {
  55498. depthStencilAttachment = descriptor.depthStencilAttachment;
  55499. }
  55500. } else {
  55501. supportsDepth = renderTargetContext.depth;
  55502. supportsStencil = renderTargetContext.stencil;
  55503. const clearConfig = {
  55504. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  55505. clearValue: color ? clearValue : undefined
  55506. };
  55507. if ( supportsDepth ) {
  55508. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  55509. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  55510. clearConfig.depthStoreOp = GPUStoreOp.Store;
  55511. }
  55512. if ( supportsStencil ) {
  55513. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  55514. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  55515. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  55516. }
  55517. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  55518. colorAttachments = descriptor.colorAttachments;
  55519. depthStencilAttachment = descriptor.depthStencilAttachment;
  55520. }
  55521. if ( supportsDepth && depthStencilAttachment ) {
  55522. if ( depth ) {
  55523. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  55524. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  55525. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  55526. } else {
  55527. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  55528. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  55529. }
  55530. }
  55531. //
  55532. if ( supportsStencil && depthStencilAttachment ) {
  55533. if ( stencil ) {
  55534. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  55535. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  55536. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  55537. } else {
  55538. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  55539. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  55540. }
  55541. }
  55542. //
  55543. const encoder = device.createCommandEncoder( { label: 'clear' } );
  55544. const currentPass = encoder.beginRenderPass( {
  55545. colorAttachments,
  55546. depthStencilAttachment
  55547. } );
  55548. currentPass.end();
  55549. device.queue.submit( [ encoder.finish() ] );
  55550. }
  55551. // compute
  55552. /**
  55553. * This method is executed at the beginning of a compute call and
  55554. * prepares the state for upcoming compute tasks.
  55555. *
  55556. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  55557. */
  55558. beginCompute( computeGroup ) {
  55559. const groupGPU = this.get( computeGroup );
  55560. //
  55561. const descriptor = {
  55562. label: 'computeGroup_' + computeGroup.id
  55563. };
  55564. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ), descriptor );
  55565. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  55566. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  55567. }
  55568. /**
  55569. * Executes a compute command for the given compute node.
  55570. *
  55571. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  55572. * @param {Node} computeNode - The compute node.
  55573. * @param {Array<BindGroup>} bindings - The bindings.
  55574. * @param {ComputePipeline} pipeline - The compute pipeline.
  55575. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  55576. * - A single number representing count, or
  55577. * - An array [x, y, z] representing dispatch size, or
  55578. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  55579. */
  55580. compute( computeGroup, computeNode, bindings, pipeline, dispatchSize = null ) {
  55581. const computeNodeData = this.get( computeNode );
  55582. const { passEncoderGPU } = this.get( computeGroup );
  55583. // pipeline
  55584. const pipelineGPU = this.get( pipeline ).pipeline;
  55585. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  55586. // bind groups
  55587. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  55588. const bindGroup = bindings[ i ];
  55589. const bindingsData = this.get( bindGroup );
  55590. passEncoderGPU.setBindGroup( i, bindingsData.group );
  55591. }
  55592. if ( dispatchSize === null ) {
  55593. dispatchSize = computeNode.count;
  55594. }
  55595. // When the dispatchSize is set with a StorageBuffer from the GPU.
  55596. if ( dispatchSize && typeof dispatchSize === 'object' && dispatchSize.isIndirectStorageBufferAttribute ) {
  55597. const dispatchBuffer = this.get( dispatchSize ).buffer;
  55598. passEncoderGPU.dispatchWorkgroupsIndirect( dispatchBuffer, 0 );
  55599. return;
  55600. }
  55601. if ( typeof dispatchSize === 'number' ) {
  55602. // If a single number is given, we calculate the dispatch size based on the workgroup size
  55603. const count = dispatchSize;
  55604. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  55605. // cache dispatch size to avoid recalculating it every time
  55606. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  55607. computeNodeData.count = count;
  55608. const workgroupSize = computeNode.workgroupSize;
  55609. let size = workgroupSize[ 0 ];
  55610. for ( let i = 1; i < workgroupSize.length; i ++ )
  55611. size *= workgroupSize[ i ];
  55612. const dispatchCount = Math.ceil( count / size );
  55613. //
  55614. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  55615. dispatchSize = [ dispatchCount, 1, 1 ];
  55616. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  55617. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  55618. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  55619. }
  55620. computeNodeData.dispatchSize = dispatchSize;
  55621. }
  55622. dispatchSize = computeNodeData.dispatchSize;
  55623. }
  55624. //
  55625. passEncoderGPU.dispatchWorkgroups(
  55626. dispatchSize[ 0 ],
  55627. dispatchSize[ 1 ] || 1,
  55628. dispatchSize[ 2 ] || 1
  55629. );
  55630. }
  55631. /**
  55632. * This method is executed at the end of a compute call and
  55633. * finalizes work after compute tasks.
  55634. *
  55635. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  55636. */
  55637. finishCompute( computeGroup ) {
  55638. const groupData = this.get( computeGroup );
  55639. groupData.passEncoderGPU.end();
  55640. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  55641. }
  55642. // render object
  55643. /**
  55644. * Executes a draw command for the given render object.
  55645. *
  55646. * @param {RenderObject} renderObject - The render object to draw.
  55647. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  55648. */
  55649. draw( renderObject, info ) {
  55650. const { object, material, context, pipeline } = renderObject;
  55651. const bindings = renderObject.getBindings();
  55652. const renderContextData = this.get( context );
  55653. const pipelineData = this.get( pipeline );
  55654. const pipelineGPU = pipelineData.pipeline;
  55655. if ( pipelineData.error === true ) return;
  55656. const index = renderObject.getIndex();
  55657. const hasIndex = ( index !== null );
  55658. const drawParams = renderObject.getDrawParameters();
  55659. if ( drawParams === null ) return;
  55660. // pipeline
  55661. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  55662. // pipeline
  55663. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  55664. currentSets.pipeline = pipelineGPU;
  55665. // bind groups
  55666. const currentBindingGroups = currentSets.bindingGroups;
  55667. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  55668. const bindGroup = bindings[ i ];
  55669. const bindingsData = this.get( bindGroup );
  55670. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  55671. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  55672. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  55673. }
  55674. }
  55675. // attributes
  55676. // index
  55677. if ( hasIndex === true ) {
  55678. if ( currentSets.index !== index ) {
  55679. const buffer = this.get( index ).buffer;
  55680. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  55681. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  55682. currentSets.index = index;
  55683. }
  55684. }
  55685. // vertex buffers
  55686. const vertexBuffers = renderObject.getVertexBuffers();
  55687. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  55688. const vertexBuffer = vertexBuffers[ i ];
  55689. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  55690. const buffer = this.get( vertexBuffer ).buffer;
  55691. passEncoderGPU.setVertexBuffer( i, buffer );
  55692. currentSets.attributes[ i ] = vertexBuffer;
  55693. }
  55694. }
  55695. // stencil
  55696. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  55697. passEncoderGPU.setStencilReference( material.stencilRef );
  55698. renderContextData.currentStencilRef = material.stencilRef;
  55699. }
  55700. };
  55701. // Define draw function
  55702. const draw = ( passEncoderGPU, currentSets ) => {
  55703. setPipelineAndBindings( passEncoderGPU, currentSets );
  55704. if ( object.isBatchedMesh === true ) {
  55705. const starts = object._multiDrawStarts;
  55706. const counts = object._multiDrawCounts;
  55707. const drawCount = object._multiDrawCount;
  55708. const drawInstances = object._multiDrawInstances;
  55709. if ( drawInstances !== null ) {
  55710. // @deprecated, r174
  55711. warnOnce( 'WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  55712. }
  55713. for ( let i = 0; i < drawCount; i ++ ) {
  55714. const count = drawInstances ? drawInstances[ i ] : 1;
  55715. const firstInstance = count > 1 ? 0 : i;
  55716. if ( hasIndex === true ) {
  55717. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  55718. } else {
  55719. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  55720. }
  55721. info.update( object, counts[ i ], count );
  55722. }
  55723. } else if ( hasIndex === true ) {
  55724. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  55725. const indirect = renderObject.getIndirect();
  55726. if ( indirect !== null ) {
  55727. const buffer = this.get( indirect ).buffer;
  55728. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  55729. } else {
  55730. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  55731. }
  55732. info.update( object, indexCount, instanceCount );
  55733. } else {
  55734. const { vertexCount, instanceCount, firstVertex } = drawParams;
  55735. const indirect = renderObject.getIndirect();
  55736. if ( indirect !== null ) {
  55737. const buffer = this.get( indirect ).buffer;
  55738. passEncoderGPU.drawIndirect( buffer, 0 );
  55739. } else {
  55740. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  55741. }
  55742. info.update( object, vertexCount, instanceCount );
  55743. }
  55744. };
  55745. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  55746. const cameraData = this.get( renderObject.camera );
  55747. const cameras = renderObject.camera.cameras;
  55748. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  55749. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  55750. const bindingsData = this.get( cameraIndex );
  55751. const indexesGPU = [];
  55752. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  55753. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  55754. data[ 0 ] = i;
  55755. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  55756. indexesGPU.push( bindGroupIndex );
  55757. }
  55758. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  55759. }
  55760. const pixelRatio = this.renderer.getPixelRatio();
  55761. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  55762. const subCamera = cameras[ i ];
  55763. if ( object.layers.test( subCamera.layers ) ) {
  55764. const vp = subCamera.viewport;
  55765. let pass = renderContextData.currentPass;
  55766. let sets = renderContextData.currentSets;
  55767. if ( renderContextData.bundleEncoders ) {
  55768. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  55769. const bundleSets = renderContextData.bundleSets[ i ];
  55770. pass = bundleEncoder;
  55771. sets = bundleSets;
  55772. }
  55773. if ( vp ) {
  55774. pass.setViewport(
  55775. Math.floor( vp.x * pixelRatio ),
  55776. Math.floor( vp.y * pixelRatio ),
  55777. Math.floor( vp.width * pixelRatio ),
  55778. Math.floor( vp.height * pixelRatio ),
  55779. context.viewportValue.minDepth,
  55780. context.viewportValue.maxDepth
  55781. );
  55782. }
  55783. // Set camera index binding for this layer
  55784. if ( cameraIndex && cameraData.indexesGPU ) {
  55785. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  55786. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  55787. }
  55788. draw( pass, sets );
  55789. }
  55790. }
  55791. } else {
  55792. // Regular single camera rendering
  55793. if ( renderContextData.currentPass ) {
  55794. // Handle occlusion queries
  55795. if ( renderContextData.occlusionQuerySet !== undefined ) {
  55796. const lastObject = renderContextData.lastOcclusionObject;
  55797. if ( lastObject !== object ) {
  55798. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  55799. renderContextData.currentPass.endOcclusionQuery();
  55800. renderContextData.occlusionQueryIndex ++;
  55801. }
  55802. if ( object.occlusionTest === true ) {
  55803. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  55804. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  55805. }
  55806. renderContextData.lastOcclusionObject = object;
  55807. }
  55808. }
  55809. draw( renderContextData.currentPass, renderContextData.currentSets );
  55810. }
  55811. }
  55812. }
  55813. // cache key
  55814. /**
  55815. * Returns `true` if the render pipeline requires an update.
  55816. *
  55817. * @param {RenderObject} renderObject - The render object.
  55818. * @return {boolean} Whether the render pipeline requires an update or not.
  55819. */
  55820. needsRenderUpdate( renderObject ) {
  55821. const data = this.get( renderObject );
  55822. const { object, material } = renderObject;
  55823. const utils = this.utils;
  55824. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  55825. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  55826. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  55827. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  55828. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  55829. let needsUpdate = false;
  55830. if ( data.material !== material || data.materialVersion !== material.version ||
  55831. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  55832. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  55833. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  55834. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  55835. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  55836. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  55837. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  55838. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  55839. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  55840. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  55841. data.primitiveTopology !== primitiveTopology ||
  55842. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  55843. ) {
  55844. data.material = material; data.materialVersion = material.version;
  55845. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  55846. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  55847. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  55848. data.colorWrite = material.colorWrite;
  55849. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  55850. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  55851. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  55852. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  55853. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  55854. data.sampleCount = sampleCount;
  55855. data.colorSpace = colorSpace;
  55856. data.colorFormat = colorFormat;
  55857. data.depthStencilFormat = depthStencilFormat;
  55858. data.primitiveTopology = primitiveTopology;
  55859. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  55860. needsUpdate = true;
  55861. }
  55862. return needsUpdate;
  55863. }
  55864. /**
  55865. * Returns a cache key that is used to identify render pipelines.
  55866. *
  55867. * @param {RenderObject} renderObject - The render object.
  55868. * @return {string} The cache key.
  55869. */
  55870. getRenderCacheKey( renderObject ) {
  55871. const { object, material } = renderObject;
  55872. const utils = this.utils;
  55873. const renderContext = renderObject.context;
  55874. // meshes with negative scale have a different frontFace render pipeline
  55875. // descriptor value so the following must be honored in the cache key
  55876. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  55877. return [
  55878. material.transparent, material.blending, material.premultipliedAlpha,
  55879. material.blendSrc, material.blendDst, material.blendEquation,
  55880. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  55881. material.colorWrite,
  55882. material.depthWrite, material.depthTest, material.depthFunc,
  55883. material.stencilWrite, material.stencilFunc,
  55884. material.stencilFail, material.stencilZFail, material.stencilZPass,
  55885. material.stencilFuncMask, material.stencilWriteMask,
  55886. material.side,
  55887. frontFaceCW,
  55888. utils.getSampleCountRenderContext( renderContext ),
  55889. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  55890. utils.getPrimitiveTopology( object, material ),
  55891. renderObject.getGeometryCacheKey(),
  55892. renderObject.clippingContextCacheKey
  55893. ].join();
  55894. }
  55895. // textures
  55896. /**
  55897. * Updates a GPU sampler for the given texture.
  55898. *
  55899. * @param {Texture} texture - The texture to update the sampler for.
  55900. * @return {string} The current sampler key.
  55901. */
  55902. updateSampler( texture ) {
  55903. return this.textureUtils.updateSampler( texture );
  55904. }
  55905. /**
  55906. * Creates a default texture for the given texture that can be used
  55907. * as a placeholder until the actual texture is ready for usage.
  55908. *
  55909. * @param {Texture} texture - The texture to create a default texture for.
  55910. * @return {boolean} Whether the sampler has been updated or not.
  55911. */
  55912. createDefaultTexture( texture ) {
  55913. return this.textureUtils.createDefaultTexture( texture );
  55914. }
  55915. /**
  55916. * Defines a texture on the GPU for the given texture object.
  55917. *
  55918. * @param {Texture} texture - The texture.
  55919. * @param {Object} [options={}] - Optional configuration parameter.
  55920. */
  55921. createTexture( texture, options ) {
  55922. this.textureUtils.createTexture( texture, options );
  55923. }
  55924. /**
  55925. * Uploads the updated texture data to the GPU.
  55926. *
  55927. * @param {Texture} texture - The texture.
  55928. * @param {Object} [options={}] - Optional configuration parameter.
  55929. */
  55930. updateTexture( texture, options ) {
  55931. this.textureUtils.updateTexture( texture, options );
  55932. }
  55933. /**
  55934. * Generates mipmaps for the given texture.
  55935. *
  55936. * @param {Texture} texture - The texture.
  55937. */
  55938. generateMipmaps( texture ) {
  55939. this.textureUtils.generateMipmaps( texture );
  55940. }
  55941. /**
  55942. * Destroys the GPU data for the given texture object.
  55943. *
  55944. * @param {Texture} texture - The texture.
  55945. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  55946. */
  55947. destroyTexture( texture, isDefaultTexture = false ) {
  55948. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  55949. }
  55950. /**
  55951. * Returns texture data as a typed array.
  55952. *
  55953. * @async
  55954. * @param {Texture} texture - The texture to copy.
  55955. * @param {number} x - The x coordinate of the copy origin.
  55956. * @param {number} y - The y coordinate of the copy origin.
  55957. * @param {number} width - The width of the copy.
  55958. * @param {number} height - The height of the copy.
  55959. * @param {number} faceIndex - The face index.
  55960. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  55961. */
  55962. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  55963. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  55964. }
  55965. /**
  55966. * Inits a time stamp query for the given render context.
  55967. *
  55968. * @param {string} type - The type of the timestamp query (e.g. 'render', 'compute').
  55969. * @param {number} uid - Unique id for the context (e.g. render context id).
  55970. * @param {Object} descriptor - The query descriptor.
  55971. */
  55972. initTimestampQuery( type, uid, descriptor ) {
  55973. if ( ! this.trackTimestamp ) return;
  55974. if ( ! this.timestampQueryPool[ type ] ) {
  55975. // TODO: Variable maxQueries?
  55976. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  55977. }
  55978. const timestampQueryPool = this.timestampQueryPool[ type ];
  55979. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  55980. descriptor.timestampWrites = {
  55981. querySet: timestampQueryPool.querySet,
  55982. beginningOfPassWriteIndex: baseOffset,
  55983. endOfPassWriteIndex: baseOffset + 1,
  55984. };
  55985. }
  55986. // node builder
  55987. /**
  55988. * Returns a node builder for the given render object.
  55989. *
  55990. * @param {RenderObject} object - The render object.
  55991. * @param {Renderer} renderer - The renderer.
  55992. * @return {WGSLNodeBuilder} The node builder.
  55993. */
  55994. createNodeBuilder( object, renderer ) {
  55995. return new WGSLNodeBuilder( object, renderer );
  55996. }
  55997. // program
  55998. /**
  55999. * Creates a shader program from the given programmable stage.
  56000. *
  56001. * @param {ProgrammableStage} program - The programmable stage.
  56002. */
  56003. createProgram( program ) {
  56004. const programGPU = this.get( program );
  56005. programGPU.module = {
  56006. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  56007. entryPoint: 'main'
  56008. };
  56009. }
  56010. /**
  56011. * Destroys the shader program of the given programmable stage.
  56012. *
  56013. * @param {ProgrammableStage} program - The programmable stage.
  56014. */
  56015. destroyProgram( program ) {
  56016. this.delete( program );
  56017. }
  56018. // pipelines
  56019. /**
  56020. * Creates a render pipeline for the given render object.
  56021. *
  56022. * @param {RenderObject} renderObject - The render object.
  56023. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  56024. */
  56025. createRenderPipeline( renderObject, promises ) {
  56026. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  56027. }
  56028. /**
  56029. * Creates a compute pipeline for the given compute node.
  56030. *
  56031. * @param {ComputePipeline} computePipeline - The compute pipeline.
  56032. * @param {Array<BindGroup>} bindings - The bindings.
  56033. */
  56034. createComputePipeline( computePipeline, bindings ) {
  56035. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  56036. }
  56037. /**
  56038. * Prepares the state for encoding render bundles.
  56039. *
  56040. * @param {RenderContext} renderContext - The render context.
  56041. */
  56042. beginBundle( renderContext ) {
  56043. const renderContextData = this.get( renderContext );
  56044. renderContextData._currentPass = renderContextData.currentPass;
  56045. renderContextData._currentSets = renderContextData.currentSets;
  56046. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  56047. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  56048. }
  56049. /**
  56050. * After processing render bundles this method finalizes related work.
  56051. *
  56052. * @param {RenderContext} renderContext - The render context.
  56053. * @param {RenderBundle} bundle - The render bundle.
  56054. */
  56055. finishBundle( renderContext, bundle ) {
  56056. const renderContextData = this.get( renderContext );
  56057. const bundleEncoder = renderContextData.currentPass;
  56058. const bundleGPU = bundleEncoder.finish();
  56059. this.get( bundle ).bundleGPU = bundleGPU;
  56060. // restore render pass state
  56061. renderContextData.currentSets = renderContextData._currentSets;
  56062. renderContextData.currentPass = renderContextData._currentPass;
  56063. }
  56064. /**
  56065. * Adds a render bundle to the render context data.
  56066. *
  56067. * @param {RenderContext} renderContext - The render context.
  56068. * @param {RenderBundle} bundle - The render bundle to add.
  56069. */
  56070. addBundle( renderContext, bundle ) {
  56071. const renderContextData = this.get( renderContext );
  56072. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  56073. }
  56074. // bindings
  56075. /**
  56076. * Creates bindings from the given bind group definition.
  56077. *
  56078. * @param {BindGroup} bindGroup - The bind group.
  56079. * @param {Array<BindGroup>} bindings - Array of bind groups.
  56080. * @param {number} cacheIndex - The cache index.
  56081. * @param {number} version - The version.
  56082. */
  56083. createBindings( bindGroup, bindings, cacheIndex, version ) {
  56084. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  56085. }
  56086. /**
  56087. * Updates the given bind group definition.
  56088. *
  56089. * @param {BindGroup} bindGroup - The bind group.
  56090. * @param {Array<BindGroup>} bindings - Array of bind groups.
  56091. * @param {number} cacheIndex - The cache index.
  56092. * @param {number} version - The version.
  56093. */
  56094. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  56095. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  56096. }
  56097. /**
  56098. * Updates a buffer binding.
  56099. *
  56100. * @param {Buffer} binding - The buffer binding to update.
  56101. */
  56102. updateBinding( binding ) {
  56103. this.bindingUtils.updateBinding( binding );
  56104. }
  56105. // attributes
  56106. /**
  56107. * Creates the buffer of an indexed shader attribute.
  56108. *
  56109. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  56110. */
  56111. createIndexAttribute( attribute ) {
  56112. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  56113. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  56114. usage |= GPUBufferUsage.STORAGE;
  56115. }
  56116. this.attributeUtils.createAttribute( attribute, usage );
  56117. }
  56118. /**
  56119. * Creates the GPU buffer of a shader attribute.
  56120. *
  56121. * @param {BufferAttribute} attribute - The buffer attribute.
  56122. */
  56123. createAttribute( attribute ) {
  56124. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  56125. }
  56126. /**
  56127. * Creates the GPU buffer of a storage attribute.
  56128. *
  56129. * @param {BufferAttribute} attribute - The buffer attribute.
  56130. */
  56131. createStorageAttribute( attribute ) {
  56132. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  56133. }
  56134. /**
  56135. * Creates the GPU buffer of an indirect storage attribute.
  56136. *
  56137. * @param {BufferAttribute} attribute - The buffer attribute.
  56138. */
  56139. createIndirectStorageAttribute( attribute ) {
  56140. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  56141. }
  56142. /**
  56143. * Updates the GPU buffer of a shader attribute.
  56144. *
  56145. * @param {BufferAttribute} attribute - The buffer attribute to update.
  56146. */
  56147. updateAttribute( attribute ) {
  56148. this.attributeUtils.updateAttribute( attribute );
  56149. }
  56150. /**
  56151. * Destroys the GPU buffer of a shader attribute.
  56152. *
  56153. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  56154. */
  56155. destroyAttribute( attribute ) {
  56156. this.attributeUtils.destroyAttribute( attribute );
  56157. }
  56158. // canvas
  56159. /**
  56160. * Triggers an update of the default render pass descriptor.
  56161. */
  56162. updateSize() {
  56163. this.delete( this.renderer.getCanvasTarget() );
  56164. }
  56165. // utils public
  56166. /**
  56167. * Returns the maximum anisotropy texture filtering value.
  56168. *
  56169. * @return {number} The maximum anisotropy texture filtering value.
  56170. */
  56171. getMaxAnisotropy() {
  56172. return 16;
  56173. }
  56174. /**
  56175. * Checks if the given feature is supported by the backend.
  56176. *
  56177. * @param {string} name - The feature's name.
  56178. * @return {boolean} Whether the feature is supported or not.
  56179. */
  56180. hasFeature( name ) {
  56181. if ( GPUFeatureMap[ name ] !== undefined ) name = GPUFeatureMap[ name ];
  56182. return this.device.features.has( name );
  56183. }
  56184. /**
  56185. * Copies data of the given source texture to the given destination texture.
  56186. *
  56187. * @param {Texture} srcTexture - The source texture.
  56188. * @param {Texture} dstTexture - The destination texture.
  56189. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  56190. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  56191. * @param {number} [srcLevel=0] - The mipmap level to copy.
  56192. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  56193. */
  56194. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  56195. let dstX = 0;
  56196. let dstY = 0;
  56197. let dstZ = 0;
  56198. let srcX = 0;
  56199. let srcY = 0;
  56200. let srcZ = 0;
  56201. let srcWidth = srcTexture.image.width;
  56202. let srcHeight = srcTexture.image.height;
  56203. let srcDepth = 1;
  56204. if ( srcRegion !== null ) {
  56205. if ( srcRegion.isBox3 === true ) {
  56206. srcX = srcRegion.min.x;
  56207. srcY = srcRegion.min.y;
  56208. srcZ = srcRegion.min.z;
  56209. srcWidth = srcRegion.max.x - srcRegion.min.x;
  56210. srcHeight = srcRegion.max.y - srcRegion.min.y;
  56211. srcDepth = srcRegion.max.z - srcRegion.min.z;
  56212. } else {
  56213. // Assume it's a Box2
  56214. srcX = srcRegion.min.x;
  56215. srcY = srcRegion.min.y;
  56216. srcWidth = srcRegion.max.x - srcRegion.min.x;
  56217. srcHeight = srcRegion.max.y - srcRegion.min.y;
  56218. srcDepth = 1;
  56219. }
  56220. }
  56221. if ( dstPosition !== null ) {
  56222. dstX = dstPosition.x;
  56223. dstY = dstPosition.y;
  56224. dstZ = dstPosition.z || 0;
  56225. }
  56226. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  56227. const sourceGPU = this.get( srcTexture ).texture;
  56228. const destinationGPU = this.get( dstTexture ).texture;
  56229. encoder.copyTextureToTexture(
  56230. {
  56231. texture: sourceGPU,
  56232. mipLevel: srcLevel,
  56233. origin: { x: srcX, y: srcY, z: srcZ }
  56234. },
  56235. {
  56236. texture: destinationGPU,
  56237. mipLevel: dstLevel,
  56238. origin: { x: dstX, y: dstY, z: dstZ }
  56239. },
  56240. [
  56241. srcWidth,
  56242. srcHeight,
  56243. srcDepth
  56244. ]
  56245. );
  56246. this.device.queue.submit( [ encoder.finish() ] );
  56247. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  56248. this.textureUtils.generateMipmaps( dstTexture );
  56249. }
  56250. }
  56251. /**
  56252. * Copies the current bound framebuffer to the given texture.
  56253. *
  56254. * @param {Texture} texture - The destination texture.
  56255. * @param {RenderContext} renderContext - The render context.
  56256. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  56257. */
  56258. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  56259. const renderContextData = this.get( renderContext );
  56260. let sourceGPU = null;
  56261. if ( renderContext.renderTarget ) {
  56262. if ( texture.isDepthTexture ) {
  56263. sourceGPU = this.get( renderContext.depthTexture ).texture;
  56264. } else {
  56265. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  56266. }
  56267. } else {
  56268. if ( texture.isDepthTexture ) {
  56269. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  56270. } else {
  56271. sourceGPU = this.context.getCurrentTexture();
  56272. }
  56273. }
  56274. const destinationGPU = this.get( texture ).texture;
  56275. if ( sourceGPU.format !== destinationGPU.format ) {
  56276. error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  56277. return;
  56278. }
  56279. let encoder;
  56280. if ( renderContextData.currentPass ) {
  56281. renderContextData.currentPass.end();
  56282. encoder = renderContextData.encoder;
  56283. } else {
  56284. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  56285. }
  56286. encoder.copyTextureToTexture(
  56287. {
  56288. texture: sourceGPU,
  56289. origin: [ rectangle.x, rectangle.y, 0 ],
  56290. },
  56291. {
  56292. texture: destinationGPU
  56293. },
  56294. [
  56295. rectangle.z,
  56296. rectangle.w
  56297. ]
  56298. );
  56299. // mipmaps must be genereated with the same encoder otherwise the copied texture data
  56300. // might be out-of-sync, see #31768
  56301. if ( texture.generateMipmaps ) {
  56302. this.textureUtils.generateMipmaps( texture, encoder );
  56303. }
  56304. if ( renderContextData.currentPass ) {
  56305. const { descriptor } = renderContextData;
  56306. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  56307. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  56308. }
  56309. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  56310. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  56311. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  56312. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  56313. if ( renderContext.viewport ) {
  56314. this.updateViewport( renderContext );
  56315. }
  56316. if ( renderContext.scissor ) {
  56317. this.updateScissor( renderContext );
  56318. }
  56319. } else {
  56320. this.device.queue.submit( [ encoder.finish() ] );
  56321. }
  56322. }
  56323. dispose() {
  56324. this.textureUtils.dispose();
  56325. }
  56326. }
  56327. /**
  56328. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  56329. *
  56330. * @augments SpotLight
  56331. */
  56332. class IESSpotLight extends SpotLight {
  56333. /**
  56334. * Constructs a new IES spot light.
  56335. *
  56336. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  56337. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  56338. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  56339. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  56340. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  56341. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  56342. */
  56343. constructor( color, intensity, distance, angle, penumbra, decay ) {
  56344. super( color, intensity, distance, angle, penumbra, decay );
  56345. /**
  56346. * TODO
  56347. *
  56348. * @type {?Texture}
  56349. * @default null
  56350. */
  56351. this.iesMap = null;
  56352. }
  56353. copy( source, recursive ) {
  56354. super.copy( source, recursive );
  56355. this.iesMap = source.iesMap;
  56356. return this;
  56357. }
  56358. }
  56359. /**
  56360. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  56361. *
  56362. * @augments SpotLight
  56363. */
  56364. class ProjectorLight extends SpotLight {
  56365. /**
  56366. * Constructs a new projector light.
  56367. *
  56368. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  56369. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  56370. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  56371. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  56372. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  56373. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  56374. */
  56375. constructor( color, intensity, distance, angle, penumbra, decay ) {
  56376. super( color, intensity, distance, angle, penumbra, decay );
  56377. /**
  56378. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  56379. *
  56380. * @type {?number}
  56381. * @default null
  56382. */
  56383. this.aspect = null;
  56384. }
  56385. copy( source, recursive ) {
  56386. super.copy( source, recursive );
  56387. this.aspect = source.aspect;
  56388. return this;
  56389. }
  56390. }
  56391. /**
  56392. * This version of a node library represents a basic version
  56393. * just focusing on lights and tone mapping techniques.
  56394. *
  56395. * @private
  56396. * @augments NodeLibrary
  56397. */
  56398. class BasicNodeLibrary extends NodeLibrary {
  56399. /**
  56400. * Constructs a new basic node library.
  56401. */
  56402. constructor() {
  56403. super();
  56404. this.addLight( PointLightNode, PointLight );
  56405. this.addLight( DirectionalLightNode, DirectionalLight );
  56406. this.addLight( RectAreaLightNode, RectAreaLight );
  56407. this.addLight( SpotLightNode, SpotLight );
  56408. this.addLight( AmbientLightNode, AmbientLight );
  56409. this.addLight( HemisphereLightNode, HemisphereLight );
  56410. this.addLight( LightProbeNode, LightProbe );
  56411. this.addLight( IESSpotLightNode, IESSpotLight );
  56412. this.addLight( ProjectorLightNode, ProjectorLight );
  56413. this.addToneMapping( linearToneMapping, LinearToneMapping );
  56414. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  56415. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  56416. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  56417. this.addToneMapping( agxToneMapping, AgXToneMapping );
  56418. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  56419. }
  56420. }
  56421. /**
  56422. * This alternative version of {@link WebGPURenderer} only supports node materials.
  56423. * So classes like `MeshBasicMaterial` are not compatible.
  56424. *
  56425. * @private
  56426. * @augments Renderer
  56427. */
  56428. class WebGPURenderer extends Renderer {
  56429. /**
  56430. * Constructs a new WebGPU renderer.
  56431. *
  56432. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  56433. */
  56434. constructor( parameters = {} ) {
  56435. let BackendClass;
  56436. if ( parameters.forceWebGL ) {
  56437. BackendClass = WebGLBackend;
  56438. } else {
  56439. BackendClass = WebGPUBackend;
  56440. parameters.getFallback = () => {
  56441. warn( 'WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  56442. return new WebGLBackend( parameters );
  56443. };
  56444. }
  56445. const backend = new BackendClass( parameters );
  56446. super( backend, parameters );
  56447. /**
  56448. * The generic default value is overwritten with the
  56449. * standard node library for type mapping. Material
  56450. * mapping is not supported with this version.
  56451. *
  56452. * @type {BasicNodeLibrary}
  56453. */
  56454. this.library = new BasicNodeLibrary();
  56455. /**
  56456. * This flag can be used for type testing.
  56457. *
  56458. * @type {boolean}
  56459. * @readonly
  56460. * @default true
  56461. */
  56462. this.isWebGPURenderer = true;
  56463. }
  56464. }
  56465. /**
  56466. * A specialized group which enables applications access to the
  56467. * Render Bundle API of WebGPU. The group with all its descendant nodes
  56468. * are considered as one render bundle and processed as such by
  56469. * the renderer.
  56470. *
  56471. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  56472. * With a WebGL backend, the group can technically be rendered but without
  56473. * any performance improvements.
  56474. *
  56475. * @augments Group
  56476. */
  56477. class BundleGroup extends Group {
  56478. /**
  56479. * Constructs a new bundle group.
  56480. */
  56481. constructor() {
  56482. super();
  56483. /**
  56484. * This flag can be used for type testing.
  56485. *
  56486. * @type {boolean}
  56487. * @readonly
  56488. * @default true
  56489. */
  56490. this.isBundleGroup = true;
  56491. /**
  56492. * This property is only relevant for detecting types
  56493. * during serialization/deserialization. It should always
  56494. * match the class name.
  56495. *
  56496. * @type {string}
  56497. * @readonly
  56498. * @default 'BundleGroup'
  56499. */
  56500. this.type = 'BundleGroup';
  56501. /**
  56502. * Whether the bundle is static or not. When set to `true`, the structure
  56503. * is assumed to be static and does not change. E.g. no new objects are
  56504. * added to the group
  56505. *
  56506. * If a change is required, an update can still be forced by setting the
  56507. * `needsUpdate` flag to `true`.
  56508. *
  56509. * @type {boolean}
  56510. * @default true
  56511. */
  56512. this.static = true;
  56513. /**
  56514. * The bundle group's version.
  56515. *
  56516. * @type {number}
  56517. * @readonly
  56518. * @default 0
  56519. */
  56520. this.version = 0;
  56521. }
  56522. /**
  56523. * Set this property to `true` when the bundle group has changed.
  56524. *
  56525. * @type {boolean}
  56526. * @default false
  56527. * @param {boolean} value
  56528. */
  56529. set needsUpdate( value ) {
  56530. if ( value === true ) this.version ++;
  56531. }
  56532. }
  56533. /**
  56534. * This module is responsible to manage the post processing setups in apps.
  56535. * You usually create a single instance of this class and use it to define
  56536. * the output of your post processing effect chain.
  56537. * ```js
  56538. * const postProcessing = new PostProcessing( renderer );
  56539. *
  56540. * const scenePass = pass( scene, camera );
  56541. *
  56542. * postProcessing.outputNode = scenePass;
  56543. * ```
  56544. *
  56545. * Note: This module can only be used with `WebGPURenderer`.
  56546. */
  56547. class PostProcessing {
  56548. /**
  56549. * Constructs a new post processing management module.
  56550. *
  56551. * @param {Renderer} renderer - A reference to the renderer.
  56552. * @param {Node<vec4>} outputNode - An optional output node.
  56553. */
  56554. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  56555. /**
  56556. * A reference to the renderer.
  56557. *
  56558. * @type {Renderer}
  56559. */
  56560. this.renderer = renderer;
  56561. /**
  56562. * A node which defines the final output of the post
  56563. * processing. This is usually the last node in a chain
  56564. * of effect nodes.
  56565. *
  56566. * @type {Node<vec4>}
  56567. */
  56568. this.outputNode = outputNode;
  56569. /**
  56570. * Whether the default output tone mapping and color
  56571. * space transformation should be enabled or not.
  56572. *
  56573. * It is enabled by default by it must be disabled when
  56574. * effects must be executed after tone mapping and color
  56575. * space conversion. A typical example is FXAA which
  56576. * requires sRGB input.
  56577. *
  56578. * When set to `false`, the app must control the output
  56579. * transformation with `RenderOutputNode`.
  56580. *
  56581. * ```js
  56582. * const outputPass = renderOutput( scenePass );
  56583. * ```
  56584. *
  56585. * @type {boolean}
  56586. */
  56587. this.outputColorTransform = true;
  56588. /**
  56589. * Must be set to `true` when the output node changes.
  56590. *
  56591. * @type {Node<vec4>}
  56592. */
  56593. this.needsUpdate = true;
  56594. const material = new NodeMaterial();
  56595. material.name = 'PostProcessing';
  56596. /**
  56597. * The full screen quad that is used to render
  56598. * the effects.
  56599. *
  56600. * @private
  56601. * @type {QuadMesh}
  56602. */
  56603. this._quadMesh = new QuadMesh( material );
  56604. this._quadMesh.name = 'Post-Processing';
  56605. /**
  56606. * The context of the post processing stack.
  56607. *
  56608. * @private
  56609. * @type {?Object}
  56610. * @default null
  56611. */
  56612. this._context = null;
  56613. }
  56614. /**
  56615. * When `PostProcessing` is used to apply post processing effects,
  56616. * the application must use this version of `render()` inside
  56617. * its animation loop (not the one from the renderer).
  56618. */
  56619. render() {
  56620. const renderer = this.renderer;
  56621. this._update();
  56622. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  56623. const toneMapping = renderer.toneMapping;
  56624. const outputColorSpace = renderer.outputColorSpace;
  56625. renderer.toneMapping = NoToneMapping;
  56626. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  56627. //
  56628. const currentXR = renderer.xr.enabled;
  56629. renderer.xr.enabled = false;
  56630. this._quadMesh.render( renderer );
  56631. renderer.xr.enabled = currentXR;
  56632. //
  56633. renderer.toneMapping = toneMapping;
  56634. renderer.outputColorSpace = outputColorSpace;
  56635. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  56636. }
  56637. /**
  56638. * Returns the current context of the post processing stack.
  56639. *
  56640. * @readonly
  56641. * @type {?Object}
  56642. */
  56643. get context() {
  56644. return this._context;
  56645. }
  56646. /**
  56647. * Frees internal resources.
  56648. */
  56649. dispose() {
  56650. this._quadMesh.material.dispose();
  56651. }
  56652. /**
  56653. * Updates the state of the module.
  56654. *
  56655. * @private
  56656. */
  56657. _update() {
  56658. if ( this.needsUpdate === true ) {
  56659. const renderer = this.renderer;
  56660. const toneMapping = renderer.toneMapping;
  56661. const outputColorSpace = renderer.outputColorSpace;
  56662. const context = {
  56663. postProcessing: this,
  56664. onBeforePostProcessing: null,
  56665. onAfterPostProcessing: null
  56666. };
  56667. let outputNode = this.outputNode;
  56668. if ( this.outputColorTransform === true ) {
  56669. outputNode = outputNode.context( context );
  56670. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  56671. } else {
  56672. context.toneMapping = toneMapping;
  56673. context.outputColorSpace = outputColorSpace;
  56674. outputNode = outputNode.context( context );
  56675. }
  56676. this._context = context;
  56677. this._quadMesh.material.fragmentNode = outputNode;
  56678. this._quadMesh.material.needsUpdate = true;
  56679. this.needsUpdate = false;
  56680. }
  56681. }
  56682. /**
  56683. * When `PostProcessing` is used to apply post processing effects,
  56684. * the application must use this version of `renderAsync()` inside
  56685. * its animation loop (not the one from the renderer).
  56686. *
  56687. * @async
  56688. * @deprecated
  56689. * @return {Promise} A Promise that resolves when the render has been finished.
  56690. */
  56691. async renderAsync() {
  56692. warnOnce( 'PostProcessing: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  56693. await this.renderer.init();
  56694. this.render();
  56695. }
  56696. }
  56697. /**
  56698. * This special type of texture is intended for compute shaders.
  56699. * It can be used to compute the data of a texture with a compute shader.
  56700. *
  56701. * Note: This type of texture can only be used with `WebGPURenderer`
  56702. * and a WebGPU backend.
  56703. *
  56704. * @augments Texture
  56705. */
  56706. class StorageTexture extends Texture {
  56707. /**
  56708. * Constructs a new storage texture.
  56709. *
  56710. * @param {number} [width=1] - The storage texture's width.
  56711. * @param {number} [height=1] - The storage texture's height.
  56712. */
  56713. constructor( width = 1, height = 1 ) {
  56714. super();
  56715. /**
  56716. * The image object which just represents the texture's dimension.
  56717. *
  56718. * @type {{width: number, height: number}}
  56719. */
  56720. this.image = { width, height };
  56721. /**
  56722. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  56723. *
  56724. * @type {number}
  56725. */
  56726. this.magFilter = LinearFilter;
  56727. /**
  56728. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  56729. *
  56730. * @type {number}
  56731. */
  56732. this.minFilter = LinearFilter;
  56733. /**
  56734. * This flag can be used for type testing.
  56735. *
  56736. * @type {boolean}
  56737. * @readonly
  56738. * @default true
  56739. */
  56740. this.isStorageTexture = true;
  56741. /**
  56742. * When `true`, mipmaps will be auto-generated after compute writes.
  56743. * When `false`, mipmaps must be written manually via compute shaders.
  56744. *
  56745. * @type {boolean}
  56746. * @default true
  56747. */
  56748. this.mipmapsAutoUpdate = true;
  56749. }
  56750. /**
  56751. * Sets the size of the storage texture.
  56752. *
  56753. * @param {number} width - The new width of the storage texture.
  56754. * @param {number} height - The new height of the storage texture.
  56755. */
  56756. setSize( width, height ) {
  56757. if ( this.image.width !== width || this.image.height !== height ) {
  56758. this.image.width = width;
  56759. this.image.height = height;
  56760. this.dispose();
  56761. }
  56762. }
  56763. }
  56764. /**
  56765. * This special type of buffer attribute is intended for compute shaders.
  56766. * It can be used to encode draw parameters for indirect draw calls.
  56767. *
  56768. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  56769. * and a WebGPU backend.
  56770. *
  56771. * @augments StorageBufferAttribute
  56772. */
  56773. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  56774. /**
  56775. * Constructs a new storage buffer attribute.
  56776. *
  56777. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  56778. * The subsequent parameter is then obsolete.
  56779. * @param {number} itemSize - The item size.
  56780. */
  56781. constructor( count, itemSize ) {
  56782. super( count, itemSize, Uint32Array );
  56783. /**
  56784. * This flag can be used for type testing.
  56785. *
  56786. * @type {boolean}
  56787. * @readonly
  56788. * @default true
  56789. */
  56790. this.isIndirectStorageBufferAttribute = true;
  56791. }
  56792. }
  56793. /**
  56794. * A loader for loading node objects in the three.js JSON Object/Scene format.
  56795. *
  56796. * @augments Loader
  56797. */
  56798. class NodeLoader extends Loader {
  56799. /**
  56800. * Constructs a new node loader.
  56801. *
  56802. * @param {LoadingManager} [manager] - A reference to a loading manager.
  56803. */
  56804. constructor( manager ) {
  56805. super( manager );
  56806. /**
  56807. * Represents a dictionary of textures.
  56808. *
  56809. * @type {Object<string,Texture>}
  56810. */
  56811. this.textures = {};
  56812. /**
  56813. * Represents a dictionary of node types.
  56814. *
  56815. * @type {Object<string,Node.constructor>}
  56816. */
  56817. this.nodes = {};
  56818. }
  56819. /**
  56820. * Loads the node definitions from the given URL.
  56821. *
  56822. * @param {string} url - The path/URL of the file to be loaded.
  56823. * @param {Function} onLoad - Will be called when load completes.
  56824. * @param {Function} onProgress - Will be called while load progresses.
  56825. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  56826. */
  56827. load( url, onLoad, onProgress, onError ) {
  56828. const loader = new FileLoader( this.manager );
  56829. loader.setPath( this.path );
  56830. loader.setRequestHeader( this.requestHeader );
  56831. loader.setWithCredentials( this.withCredentials );
  56832. loader.load( url, ( text ) => {
  56833. try {
  56834. onLoad( this.parse( JSON.parse( text ) ) );
  56835. } catch ( e ) {
  56836. if ( onError ) {
  56837. onError( e );
  56838. } else {
  56839. error( e );
  56840. }
  56841. this.manager.itemError( url );
  56842. }
  56843. }, onProgress, onError );
  56844. }
  56845. /**
  56846. * Parse the node dependencies for the loaded node.
  56847. *
  56848. * @param {Array<Object>} [json] - The JSON definition
  56849. * @return {Object<string,Node>} A dictionary with node dependencies.
  56850. */
  56851. parseNodes( json ) {
  56852. const nodes = {};
  56853. if ( json !== undefined ) {
  56854. for ( const nodeJSON of json ) {
  56855. const { uuid, type } = nodeJSON;
  56856. nodes[ uuid ] = this.createNodeFromType( type );
  56857. nodes[ uuid ].uuid = uuid;
  56858. }
  56859. const meta = { nodes, textures: this.textures };
  56860. for ( const nodeJSON of json ) {
  56861. nodeJSON.meta = meta;
  56862. const node = nodes[ nodeJSON.uuid ];
  56863. node.deserialize( nodeJSON );
  56864. delete nodeJSON.meta;
  56865. }
  56866. }
  56867. return nodes;
  56868. }
  56869. /**
  56870. * Parses the node from the given JSON.
  56871. *
  56872. * @param {Object} json - The JSON definition
  56873. * @param {string} json.type - The node type.
  56874. * @param {string} json.uuid - The node UUID.
  56875. * @param {Array<Object>} [json.nodes] - The node dependencies.
  56876. * @param {Object} [json.meta] - The meta data.
  56877. * @return {Node} The parsed node.
  56878. */
  56879. parse( json ) {
  56880. const node = this.createNodeFromType( json.type );
  56881. node.uuid = json.uuid;
  56882. const nodes = this.parseNodes( json.nodes );
  56883. const meta = { nodes, textures: this.textures };
  56884. json.meta = meta;
  56885. node.deserialize( json );
  56886. delete json.meta;
  56887. return node;
  56888. }
  56889. /**
  56890. * Defines the dictionary of textures.
  56891. *
  56892. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  56893. * @return {NodeLoader} A reference to this loader.
  56894. */
  56895. setTextures( value ) {
  56896. this.textures = value;
  56897. return this;
  56898. }
  56899. /**
  56900. * Defines the dictionary of node types.
  56901. *
  56902. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  56903. * @return {NodeLoader} A reference to this loader.
  56904. */
  56905. setNodes( value ) {
  56906. this.nodes = value;
  56907. return this;
  56908. }
  56909. /**
  56910. * Creates a node object from the given type.
  56911. *
  56912. * @param {string} type - The node type.
  56913. * @return {Node} The created node instance.
  56914. */
  56915. createNodeFromType( type ) {
  56916. if ( this.nodes[ type ] === undefined ) {
  56917. error( 'NodeLoader: Node type not found:', type );
  56918. return float();
  56919. }
  56920. return nodeObject( new this.nodes[ type ]() );
  56921. }
  56922. }
  56923. /**
  56924. * A special type of material loader for loading node materials.
  56925. *
  56926. * @augments MaterialLoader
  56927. */
  56928. class NodeMaterialLoader extends MaterialLoader {
  56929. /**
  56930. * Constructs a new node material loader.
  56931. *
  56932. * @param {LoadingManager} [manager] - A reference to a loading manager.
  56933. */
  56934. constructor( manager ) {
  56935. super( manager );
  56936. /**
  56937. * Represents a dictionary of node types.
  56938. *
  56939. * @type {Object<string,Node.constructor>}
  56940. */
  56941. this.nodes = {};
  56942. /**
  56943. * Represents a dictionary of node material types.
  56944. *
  56945. * @type {Object<string,NodeMaterial.constructor>}
  56946. */
  56947. this.nodeMaterials = {};
  56948. }
  56949. /**
  56950. * Parses the node material from the given JSON.
  56951. *
  56952. * @param {Object} json - The JSON definition
  56953. * @return {NodeMaterial}. The parsed material.
  56954. */
  56955. parse( json ) {
  56956. const material = super.parse( json );
  56957. const nodes = this.nodes;
  56958. const inputNodes = json.inputNodes;
  56959. for ( const property in inputNodes ) {
  56960. const uuid = inputNodes[ property ];
  56961. material[ property ] = nodes[ uuid ];
  56962. }
  56963. return material;
  56964. }
  56965. /**
  56966. * Defines the dictionary of node types.
  56967. *
  56968. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  56969. * @return {NodeLoader} A reference to this loader.
  56970. */
  56971. setNodes( value ) {
  56972. this.nodes = value;
  56973. return this;
  56974. }
  56975. /**
  56976. * Defines the dictionary of node material types.
  56977. *
  56978. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  56979. * @return {NodeLoader} A reference to this loader.
  56980. */
  56981. setNodeMaterials( value ) {
  56982. this.nodeMaterials = value;
  56983. return this;
  56984. }
  56985. /**
  56986. * Creates a node material from the given type.
  56987. *
  56988. * @param {string} type - The node material type.
  56989. * @return {Node} The created node material instance.
  56990. */
  56991. createMaterialFromType( type ) {
  56992. const materialClass = this.nodeMaterials[ type ];
  56993. if ( materialClass !== undefined ) {
  56994. return new materialClass();
  56995. }
  56996. return super.createMaterialFromType( type );
  56997. }
  56998. }
  56999. /**
  57000. * A special type of object loader for loading 3D objects using
  57001. * node materials.
  57002. *
  57003. * @augments ObjectLoader
  57004. */
  57005. class NodeObjectLoader extends ObjectLoader {
  57006. /**
  57007. * Constructs a new node object loader.
  57008. *
  57009. * @param {LoadingManager} [manager] - A reference to a loading manager.
  57010. */
  57011. constructor( manager ) {
  57012. super( manager );
  57013. /**
  57014. * Represents a dictionary of node types.
  57015. *
  57016. * @type {Object<string,Node.constructor>}
  57017. */
  57018. this.nodes = {};
  57019. /**
  57020. * Represents a dictionary of node material types.
  57021. *
  57022. * @type {Object<string,NodeMaterial.constructor>}
  57023. */
  57024. this.nodeMaterials = {};
  57025. /**
  57026. * A reference to hold the `nodes` JSON property.
  57027. *
  57028. * @private
  57029. * @type {?Object[]}
  57030. */
  57031. this._nodesJSON = null;
  57032. }
  57033. /**
  57034. * Defines the dictionary of node types.
  57035. *
  57036. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  57037. * @return {NodeObjectLoader} A reference to this loader.
  57038. */
  57039. setNodes( value ) {
  57040. this.nodes = value;
  57041. return this;
  57042. }
  57043. /**
  57044. * Defines the dictionary of node material types.
  57045. *
  57046. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  57047. * @return {NodeObjectLoader} A reference to this loader.
  57048. */
  57049. setNodeMaterials( value ) {
  57050. this.nodeMaterials = value;
  57051. return this;
  57052. }
  57053. /**
  57054. * Parses the node objects from the given JSON.
  57055. *
  57056. * @param {Object} json - The JSON definition
  57057. * @param {Function} onLoad - The onLoad callback function.
  57058. * @return {Object3D}. The parsed 3D object.
  57059. */
  57060. parse( json, onLoad ) {
  57061. this._nodesJSON = json.nodes;
  57062. const data = super.parse( json, onLoad );
  57063. this._nodesJSON = null; // dispose
  57064. return data;
  57065. }
  57066. /**
  57067. * Parses the node objects from the given JSON and textures.
  57068. *
  57069. * @param {Object[]} json - The JSON definition
  57070. * @param {Object<string,Texture>} textures - The texture library.
  57071. * @return {Object<string,Node>}. The parsed nodes.
  57072. */
  57073. parseNodes( json, textures ) {
  57074. if ( json !== undefined ) {
  57075. const loader = new NodeLoader();
  57076. loader.setNodes( this.nodes );
  57077. loader.setTextures( textures );
  57078. return loader.parseNodes( json );
  57079. }
  57080. return {};
  57081. }
  57082. /**
  57083. * Parses the node objects from the given JSON and textures.
  57084. *
  57085. * @param {Object} json - The JSON definition
  57086. * @param {Object<string,Texture>} textures - The texture library.
  57087. * @return {Object<string,NodeMaterial>}. The parsed materials.
  57088. */
  57089. parseMaterials( json, textures ) {
  57090. const materials = {};
  57091. if ( json !== undefined ) {
  57092. const nodes = this.parseNodes( this._nodesJSON, textures );
  57093. const loader = new NodeMaterialLoader();
  57094. loader.setTextures( textures );
  57095. loader.setNodes( nodes );
  57096. loader.setNodeMaterials( this.nodeMaterials );
  57097. for ( let i = 0, l = json.length; i < l; i ++ ) {
  57098. const data = json[ i ];
  57099. materials[ data.uuid ] = loader.parse( data );
  57100. }
  57101. }
  57102. return materials;
  57103. }
  57104. }
  57105. /**
  57106. * In earlier three.js versions, clipping was defined globally
  57107. * on the renderer or on material level. This special version of
  57108. * `THREE.Group` allows to encode the clipping state into the scene
  57109. * graph. Meaning if you create an instance of this group, all
  57110. * descendant 3D objects will be affected by the respective clipping
  57111. * planes.
  57112. *
  57113. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  57114. *
  57115. * @augments Group
  57116. */
  57117. class ClippingGroup extends Group {
  57118. /**
  57119. * Constructs a new clipping group.
  57120. */
  57121. constructor() {
  57122. super();
  57123. /**
  57124. * This flag can be used for type testing.
  57125. *
  57126. * @type {boolean}
  57127. * @readonly
  57128. * @default true
  57129. */
  57130. this.isClippingGroup = true;
  57131. /**
  57132. * An array with clipping planes.
  57133. *
  57134. * @type {Array<Plane>}
  57135. */
  57136. this.clippingPlanes = [];
  57137. /**
  57138. * Whether clipping should be enabled or not.
  57139. *
  57140. * @type {boolean}
  57141. * @default true
  57142. */
  57143. this.enabled = true;
  57144. /**
  57145. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  57146. *
  57147. * @type {boolean}
  57148. * @default false
  57149. */
  57150. this.clipIntersection = false;
  57151. /**
  57152. * Whether shadows should be clipped or not.
  57153. *
  57154. * @type {boolean}
  57155. * @default false
  57156. */
  57157. this.clipShadows = false;
  57158. }
  57159. }
  57160. 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, 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, StorageArrayElementNode, 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号