three.webgpu.js 1.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440
  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, InterleavedBuffer, InterleavedBufferAttribute, DynamicDrawUsage, NoColorSpace, log as log$1, warnOnce, Texture, UnsignedIntType, IntType, NearestFilter, Sphere, BackSide, DoubleSide, Euler, CubeTexture, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, ObjectSpaceNormalMap, 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, RGFormat, HalfFloatType, ClampToEdgeWrapping, OrthographicCamera, PerspectiveCamera, RenderTarget, LinearSRGBColorSpace, RGBAFormat, CubeUVReflectionMapping, BufferGeometry, 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, 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, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, MirroredRepeatWrapping, RepeatWrapping, NearestMipmapNearestFilter, NotEqualCompare, GreaterCompare, GreaterEqualCompare, EqualCompare, LessEqualCompare, AlwaysCompare, NeverCompare, LinearTransfer, getByteLength, 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.renderer.overrideNodes.modelViewMatrix !== null || builder.renderer.overrideNodes.modelNormalViewMatrix !== null )
  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. getMemberType( builder, name ) {
  2451. return this.getOutputNode( builder ).getMemberType( builder, name );
  2452. }
  2453. call( builder ) {
  2454. const { shaderNode, rawInputs } = this;
  2455. const properties = builder.getNodeProperties( shaderNode );
  2456. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2457. const subBuildProperty = subBuild || 'default';
  2458. if ( properties[ subBuildProperty ] ) {
  2459. return properties[ subBuildProperty ];
  2460. }
  2461. //
  2462. const previousSubBuildFn = builder.subBuildFn;
  2463. const previousFnCall = builder.fnCall;
  2464. builder.subBuildFn = subBuild;
  2465. builder.fnCall = this;
  2466. let result = null;
  2467. if ( shaderNode.layout ) {
  2468. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2469. if ( functionNodesCacheMap === undefined ) {
  2470. functionNodesCacheMap = new WeakMap();
  2471. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2472. }
  2473. let functionNode = functionNodesCacheMap.get( shaderNode );
  2474. if ( functionNode === undefined ) {
  2475. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2476. functionNodesCacheMap.set( shaderNode, functionNode );
  2477. }
  2478. builder.addInclude( functionNode );
  2479. //
  2480. const inputs = rawInputs ? getLayoutParameters( rawInputs ) : null;
  2481. result = nodeObject( functionNode.call( inputs ) );
  2482. } else {
  2483. const secureNodeBuilder = new Proxy( builder, {
  2484. get: ( target, property, receiver ) => {
  2485. let value;
  2486. if ( Symbol.iterator === property ) {
  2487. value = function* () {
  2488. yield undefined;
  2489. };
  2490. } else {
  2491. value = Reflect.get( target, property, receiver );
  2492. }
  2493. return value;
  2494. }
  2495. } );
  2496. //
  2497. const inputs = rawInputs ? getProxyParameters( rawInputs ) : null;
  2498. const hasParameters = Array.isArray( rawInputs ) ? rawInputs.length > 0 : rawInputs !== null;
  2499. const jsFunc = shaderNode.jsFunc;
  2500. const outputNode = hasParameters || jsFunc.length > 1 ? jsFunc( inputs, secureNodeBuilder ) : jsFunc( secureNodeBuilder );
  2501. result = nodeObject( outputNode );
  2502. }
  2503. builder.subBuildFn = previousSubBuildFn;
  2504. builder.fnCall = previousFnCall;
  2505. if ( shaderNode.once ) {
  2506. properties[ subBuildProperty ] = result;
  2507. }
  2508. return result;
  2509. }
  2510. setupOutput( builder ) {
  2511. builder.addStack();
  2512. builder.stack.outputNode = this.call( builder );
  2513. return builder.removeStack();
  2514. }
  2515. getOutputNode( builder ) {
  2516. const properties = builder.getNodeProperties( this );
  2517. const subBuildOutput = builder.getSubBuildOutput( this );
  2518. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2519. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2520. return properties[ subBuildOutput ];
  2521. }
  2522. build( builder, output = null ) {
  2523. let result = null;
  2524. const buildStage = builder.getBuildStage();
  2525. const properties = builder.getNodeProperties( this );
  2526. const subBuildOutput = builder.getSubBuildOutput( this );
  2527. const outputNode = this.getOutputNode( builder );
  2528. const previousFnCall = builder.fnCall;
  2529. builder.fnCall = this;
  2530. if ( buildStage === 'setup' ) {
  2531. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2532. if ( properties[ subBuildInitialized ] !== true ) {
  2533. properties[ subBuildInitialized ] = true;
  2534. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2535. properties[ subBuildOutput ].build( builder );
  2536. // If the shaderNode has subBuilds, add them to the chaining nodes
  2537. // so they can be built later in the build process.
  2538. if ( this.shaderNode.subBuilds ) {
  2539. for ( const node of builder.chaining ) {
  2540. const nodeData = builder.getDataFromNode( node, 'any' );
  2541. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2542. for ( const subBuild of this.shaderNode.subBuilds ) {
  2543. nodeData.subBuilds.add( subBuild );
  2544. }
  2545. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2546. }
  2547. }
  2548. }
  2549. result = properties[ subBuildOutput ];
  2550. } else if ( buildStage === 'analyze' ) {
  2551. outputNode.build( builder, output );
  2552. } else if ( buildStage === 'generate' ) {
  2553. result = outputNode.build( builder, output ) || '';
  2554. }
  2555. builder.fnCall = previousFnCall;
  2556. return result;
  2557. }
  2558. }
  2559. function getLayoutParameters( params ) {
  2560. let output;
  2561. nodeObjects( params );
  2562. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2563. if ( isArrayAsParameter ) {
  2564. output = [ ...params ];
  2565. } else {
  2566. output = params[ 0 ];
  2567. }
  2568. return output;
  2569. }
  2570. function getProxyParameters( params ) {
  2571. let index = 0;
  2572. nodeObjects( params );
  2573. return new Proxy( params, {
  2574. get: ( target, property, receiver ) => {
  2575. let value;
  2576. if ( property === 'length' ) {
  2577. value = params.length;
  2578. return value;
  2579. }
  2580. if ( Symbol.iterator === property ) {
  2581. value = function* () {
  2582. for ( const inputNode of params ) {
  2583. yield nodeObject( inputNode );
  2584. }
  2585. };
  2586. } else {
  2587. if ( params.length > 0 ) {
  2588. if ( Object.getPrototypeOf( params[ 0 ] ) === Object.prototype ) {
  2589. const objectTarget = params[ 0 ];
  2590. if ( objectTarget[ property ] === undefined ) {
  2591. value = objectTarget[ index ++ ];
  2592. } else {
  2593. value = Reflect.get( objectTarget, property, receiver );
  2594. }
  2595. } else if ( params[ 0 ] instanceof Node ) {
  2596. if ( params[ property ] === undefined ) {
  2597. value = params[ index ++ ];
  2598. } else {
  2599. value = Reflect.get( params, property, receiver );
  2600. }
  2601. }
  2602. } else {
  2603. value = Reflect.get( target, property, receiver );
  2604. }
  2605. value = nodeObject( value );
  2606. }
  2607. return value;
  2608. }
  2609. } );
  2610. }
  2611. class ShaderNodeInternal extends Node {
  2612. constructor( jsFunc, nodeType ) {
  2613. super( nodeType );
  2614. this.jsFunc = jsFunc;
  2615. this.layout = null;
  2616. this.global = true;
  2617. this.once = false;
  2618. }
  2619. setLayout( layout ) {
  2620. this.layout = layout;
  2621. return this;
  2622. }
  2623. getLayout() {
  2624. return this.layout;
  2625. }
  2626. call( rawInputs = null ) {
  2627. return new ShaderCallNodeInternal( this, rawInputs );
  2628. }
  2629. setup() {
  2630. return this.call();
  2631. }
  2632. }
  2633. const bools = [ false, true ];
  2634. const uints = [ 0, 1, 2, 3 ];
  2635. const ints = [ -1, -2 ];
  2636. 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 ];
  2637. const boolsCacheMap = new Map();
  2638. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2639. const uintsCacheMap = new Map();
  2640. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2641. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2642. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2643. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2644. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2645. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2646. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2647. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2648. const getConstNode = ( value, type ) => {
  2649. if ( constNodesCacheMap.has( value ) ) {
  2650. return constNodesCacheMap.get( value );
  2651. } else if ( value.isNode === true ) {
  2652. return value;
  2653. } else {
  2654. return new ConstNode( value, type );
  2655. }
  2656. };
  2657. const ConvertType = function ( type, cacheMap = null ) {
  2658. return ( ...params ) => {
  2659. for ( const param of params ) {
  2660. if ( param === undefined ) {
  2661. error( `TSL: Invalid parameter for the type "${ type }".` );
  2662. return nodeObject( new ConstNode( 0, type ) );
  2663. }
  2664. }
  2665. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => {
  2666. const paramType = typeof param;
  2667. return paramType !== 'object' && paramType !== 'function';
  2668. } ) ) ) {
  2669. params = [ getValueFromType( type, ...params ) ];
  2670. }
  2671. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2672. return nodeObjectIntent( cacheMap.get( params[ 0 ] ) );
  2673. }
  2674. if ( params.length === 1 ) {
  2675. const node = getConstNode( params[ 0 ], type );
  2676. if ( node.nodeType === type ) return nodeObjectIntent( node );
  2677. return nodeObjectIntent( new ConvertNode( node, type ) );
  2678. }
  2679. const nodes = params.map( param => getConstNode( param ) );
  2680. return nodeObjectIntent( new JoinNode( nodes, type ) );
  2681. };
  2682. };
  2683. // exports
  2684. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2685. // utils
  2686. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2687. // shader node base
  2688. function ShaderNode( jsFunc, nodeType ) {
  2689. return new ShaderNodeInternal( jsFunc, nodeType );
  2690. }
  2691. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2692. const nodeObjectIntent = ( val, altType = null ) => /* new */ nodeObject( val, altType ).toVarIntent();
  2693. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2694. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2695. const nodeProxy = ( NodeClass, scope = null, factor = null, settings = null ) => new ShaderNodeProxy( NodeClass, scope, factor, settings );
  2696. const nodeImmutable = ( NodeClass, ...params ) => new ShaderNodeImmutable( NodeClass, ...params );
  2697. const nodeProxyIntent = ( NodeClass, scope = null, factor = null, settings = {} ) => new ShaderNodeProxy( NodeClass, scope, factor, { ...settings, intent: true } );
  2698. let fnId = 0;
  2699. class FnNode extends Node {
  2700. constructor( jsFunc, layout = null ) {
  2701. super();
  2702. let nodeType = null;
  2703. if ( layout !== null ) {
  2704. if ( typeof layout === 'object' ) {
  2705. nodeType = layout.return;
  2706. } else {
  2707. if ( typeof layout === 'string' ) {
  2708. nodeType = layout;
  2709. } else {
  2710. error( 'TSL: Invalid layout type.' );
  2711. }
  2712. layout = null;
  2713. }
  2714. }
  2715. this.shaderNode = new ShaderNode( jsFunc, nodeType );
  2716. if ( layout !== null ) {
  2717. this.setLayout( layout );
  2718. }
  2719. this.isFn = true;
  2720. }
  2721. setLayout( layout ) {
  2722. const nodeType = this.shaderNode.nodeType;
  2723. if ( typeof layout.inputs !== 'object' ) {
  2724. const fullLayout = {
  2725. name: 'fn' + fnId ++,
  2726. type: nodeType,
  2727. inputs: []
  2728. };
  2729. for ( const name in layout ) {
  2730. if ( name === 'return' ) continue;
  2731. fullLayout.inputs.push( {
  2732. name: name,
  2733. type: layout[ name ]
  2734. } );
  2735. }
  2736. layout = fullLayout;
  2737. }
  2738. this.shaderNode.setLayout( layout );
  2739. return this;
  2740. }
  2741. getNodeType( builder ) {
  2742. return this.shaderNode.getNodeType( builder ) || 'float';
  2743. }
  2744. call( ...params ) {
  2745. const fnCall = this.shaderNode.call( params );
  2746. if ( this.shaderNode.nodeType === 'void' ) fnCall.toStack();
  2747. return fnCall.toVarIntent();
  2748. }
  2749. once( subBuilds = null ) {
  2750. this.shaderNode.once = true;
  2751. this.shaderNode.subBuilds = subBuilds;
  2752. return this;
  2753. }
  2754. generate( builder ) {
  2755. const type = this.getNodeType( builder );
  2756. error( 'TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".' );
  2757. return builder.generateConst( type );
  2758. }
  2759. }
  2760. function Fn( jsFunc, layout = null ) {
  2761. const instance = new FnNode( jsFunc, layout );
  2762. return new Proxy( () => {}, {
  2763. apply( target, thisArg, params ) {
  2764. return instance.call( ...params );
  2765. },
  2766. get( target, prop, receiver ) {
  2767. return Reflect.get( instance, prop, receiver );
  2768. },
  2769. set( target, prop, value, receiver ) {
  2770. return Reflect.set( instance, prop, value, receiver );
  2771. }
  2772. } );
  2773. }
  2774. //
  2775. const setCurrentStack = ( stack ) => {
  2776. currentStack = stack;
  2777. };
  2778. const getCurrentStack = () => currentStack;
  2779. /**
  2780. * Represent a conditional node using if/else statements.
  2781. *
  2782. * ```js
  2783. * If( condition, function )
  2784. * .ElseIf( condition, function )
  2785. * .Else( function )
  2786. * ```
  2787. * @tsl
  2788. * @function
  2789. * @param {...any} params - The parameters for the conditional node.
  2790. * @returns {StackNode} The conditional node.
  2791. */
  2792. const If = ( ...params ) => currentStack.If( ...params );
  2793. /**
  2794. * Represent a conditional node using switch/case statements.
  2795. *
  2796. * ```js
  2797. * Switch( value )
  2798. * .Case( 1, function )
  2799. * .Case( 2, 3, 4, function )
  2800. * .Default( function )
  2801. * ```
  2802. * @tsl
  2803. * @function
  2804. * @param {...any} params - The parameters for the conditional node.
  2805. * @returns {StackNode} The conditional node.
  2806. */
  2807. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2808. /**
  2809. * Add the given node to the current stack.
  2810. *
  2811. * @param {Node} node - The node to add.
  2812. * @returns {Node} The node that was added to the stack.
  2813. */
  2814. function Stack( node ) {
  2815. if ( currentStack ) currentStack.addToStack( node );
  2816. return node;
  2817. }
  2818. addMethodChaining( 'toStack', Stack );
  2819. // types
  2820. const color = new ConvertType( 'color' );
  2821. const float = new ConvertType( 'float', cacheMaps.float );
  2822. const int = new ConvertType( 'int', cacheMaps.ints );
  2823. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2824. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2825. const vec2 = new ConvertType( 'vec2' );
  2826. const ivec2 = new ConvertType( 'ivec2' );
  2827. const uvec2 = new ConvertType( 'uvec2' );
  2828. const bvec2 = new ConvertType( 'bvec2' );
  2829. const vec3 = new ConvertType( 'vec3' );
  2830. const ivec3 = new ConvertType( 'ivec3' );
  2831. const uvec3 = new ConvertType( 'uvec3' );
  2832. const bvec3 = new ConvertType( 'bvec3' );
  2833. const vec4 = new ConvertType( 'vec4' );
  2834. const ivec4 = new ConvertType( 'ivec4' );
  2835. const uvec4 = new ConvertType( 'uvec4' );
  2836. const bvec4 = new ConvertType( 'bvec4' );
  2837. const mat2 = new ConvertType( 'mat2' );
  2838. const mat3 = new ConvertType( 'mat3' );
  2839. const mat4 = new ConvertType( 'mat4' );
  2840. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2841. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2842. addMethodChaining( 'toColor', color );
  2843. addMethodChaining( 'toFloat', float );
  2844. addMethodChaining( 'toInt', int );
  2845. addMethodChaining( 'toUint', uint );
  2846. addMethodChaining( 'toBool', bool );
  2847. addMethodChaining( 'toVec2', vec2 );
  2848. addMethodChaining( 'toIVec2', ivec2 );
  2849. addMethodChaining( 'toUVec2', uvec2 );
  2850. addMethodChaining( 'toBVec2', bvec2 );
  2851. addMethodChaining( 'toVec3', vec3 );
  2852. addMethodChaining( 'toIVec3', ivec3 );
  2853. addMethodChaining( 'toUVec3', uvec3 );
  2854. addMethodChaining( 'toBVec3', bvec3 );
  2855. addMethodChaining( 'toVec4', vec4 );
  2856. addMethodChaining( 'toIVec4', ivec4 );
  2857. addMethodChaining( 'toUVec4', uvec4 );
  2858. addMethodChaining( 'toBVec4', bvec4 );
  2859. addMethodChaining( 'toMat2', mat2 );
  2860. addMethodChaining( 'toMat3', mat3 );
  2861. addMethodChaining( 'toMat4', mat4 );
  2862. // basic nodes
  2863. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2864. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2865. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2866. addMethodChaining( 'element', element );
  2867. addMethodChaining( 'convert', convert );
  2868. // deprecated
  2869. /**
  2870. * @tsl
  2871. * @function
  2872. * @deprecated since r176. Use {@link Stack} instead.
  2873. *
  2874. * @param {Node} node - The node to add.
  2875. * @returns {Function}
  2876. */
  2877. const append = ( node ) => { // @deprecated, r176
  2878. warn( 'TSL: append() has been renamed to Stack().' );
  2879. return Stack( node );
  2880. };
  2881. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2882. warn( 'TSL: .append() has been renamed to .toStack().' );
  2883. return Stack( node );
  2884. } );
  2885. /**
  2886. * This class represents a shader property. It can be used
  2887. * to explicitly define a property and assign a value to it.
  2888. *
  2889. * ```js
  2890. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2891. *```
  2892. * `PropertyNode` is used by the engine to predefined common material properties
  2893. * for TSL code.
  2894. *
  2895. * @augments Node
  2896. */
  2897. class PropertyNode extends Node {
  2898. static get type() {
  2899. return 'PropertyNode';
  2900. }
  2901. /**
  2902. * Constructs a new property node.
  2903. *
  2904. * @param {string} nodeType - The type of the node.
  2905. * @param {?string} [name=null] - The name of the property in the shader.
  2906. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2907. */
  2908. constructor( nodeType, name = null, varying = false ) {
  2909. super( nodeType );
  2910. /**
  2911. * The name of the property in the shader. If no name is defined,
  2912. * the node system auto-generates one.
  2913. *
  2914. * @type {?string}
  2915. * @default null
  2916. */
  2917. this.name = name;
  2918. /**
  2919. * Whether this property is a varying or not.
  2920. *
  2921. * @type {boolean}
  2922. * @default false
  2923. */
  2924. this.varying = varying;
  2925. /**
  2926. * This flag can be used for type testing.
  2927. *
  2928. * @type {boolean}
  2929. * @readonly
  2930. * @default true
  2931. */
  2932. this.isPropertyNode = true;
  2933. /**
  2934. * This flag is used for global cache.
  2935. *
  2936. * @type {boolean}
  2937. * @default true
  2938. */
  2939. this.global = true;
  2940. }
  2941. customCacheKey() {
  2942. return hashString( this.type + ':' + ( this.name || '' ) + ':' + ( this.varying ? '1' : '0' ) );
  2943. }
  2944. getHash( builder ) {
  2945. return this.name || super.getHash( builder );
  2946. }
  2947. generate( builder ) {
  2948. let nodeVar;
  2949. if ( this.varying === true ) {
  2950. nodeVar = builder.getVaryingFromNode( this, this.name );
  2951. nodeVar.needsInterpolation = true;
  2952. } else {
  2953. nodeVar = builder.getVarFromNode( this, this.name );
  2954. }
  2955. return builder.getPropertyName( nodeVar );
  2956. }
  2957. }
  2958. /**
  2959. * TSL function for creating a property node.
  2960. *
  2961. * @tsl
  2962. * @function
  2963. * @param {string} type - The type of the node.
  2964. * @param {?string} [name=null] - The name of the property in the shader.
  2965. * @returns {PropertyNode}
  2966. */
  2967. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2968. /**
  2969. * TSL function for creating a varying property node.
  2970. *
  2971. * @tsl
  2972. * @function
  2973. * @param {string} type - The type of the node.
  2974. * @param {?string} [name=null] - The name of the varying in the shader.
  2975. * @returns {PropertyNode}
  2976. */
  2977. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2978. /**
  2979. * TSL object that represents the shader variable `DiffuseColor`.
  2980. *
  2981. * @tsl
  2982. * @type {PropertyNode<vec4>}
  2983. */
  2984. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2985. /**
  2986. * TSL object that represents the shader variable `EmissiveColor`.
  2987. *
  2988. * @tsl
  2989. * @type {PropertyNode<vec3>}
  2990. */
  2991. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2992. /**
  2993. * TSL object that represents the shader variable `Roughness`.
  2994. *
  2995. * @tsl
  2996. * @type {PropertyNode<float>}
  2997. */
  2998. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2999. /**
  3000. * TSL object that represents the shader variable `Metalness`.
  3001. *
  3002. * @tsl
  3003. * @type {PropertyNode<float>}
  3004. */
  3005. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  3006. /**
  3007. * TSL object that represents the shader variable `Clearcoat`.
  3008. *
  3009. * @tsl
  3010. * @type {PropertyNode<float>}
  3011. */
  3012. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  3013. /**
  3014. * TSL object that represents the shader variable `ClearcoatRoughness`.
  3015. *
  3016. * @tsl
  3017. * @type {PropertyNode<float>}
  3018. */
  3019. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  3020. /**
  3021. * TSL object that represents the shader variable `Sheen`.
  3022. *
  3023. * @tsl
  3024. * @type {PropertyNode<vec3>}
  3025. */
  3026. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  3027. /**
  3028. * TSL object that represents the shader variable `SheenRoughness`.
  3029. *
  3030. * @tsl
  3031. * @type {PropertyNode<float>}
  3032. */
  3033. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  3034. /**
  3035. * TSL object that represents the shader variable `Iridescence`.
  3036. *
  3037. * @tsl
  3038. * @type {PropertyNode<float>}
  3039. */
  3040. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  3041. /**
  3042. * TSL object that represents the shader variable `IridescenceIOR`.
  3043. *
  3044. * @tsl
  3045. * @type {PropertyNode<float>}
  3046. */
  3047. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  3048. /**
  3049. * TSL object that represents the shader variable `IridescenceThickness`.
  3050. *
  3051. * @tsl
  3052. * @type {PropertyNode<float>}
  3053. */
  3054. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  3055. /**
  3056. * TSL object that represents the shader variable `AlphaT`.
  3057. *
  3058. * @tsl
  3059. * @type {PropertyNode<float>}
  3060. */
  3061. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  3062. /**
  3063. * TSL object that represents the shader variable `Anisotropy`.
  3064. *
  3065. * @tsl
  3066. * @type {PropertyNode<float>}
  3067. */
  3068. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  3069. /**
  3070. * TSL object that represents the shader variable `AnisotropyT`.
  3071. *
  3072. * @tsl
  3073. * @type {PropertyNode<vec3>}
  3074. */
  3075. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  3076. /**
  3077. * TSL object that represents the shader variable `AnisotropyB`.
  3078. *
  3079. * @tsl
  3080. * @type {PropertyNode<vec3>}
  3081. */
  3082. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  3083. /**
  3084. * TSL object that represents the shader variable `SpecularColor`.
  3085. *
  3086. * @tsl
  3087. * @type {PropertyNode<color>}
  3088. */
  3089. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  3090. /**
  3091. * TSL object that represents the shader variable `SpecularF90`.
  3092. *
  3093. * @tsl
  3094. * @type {PropertyNode<float>}
  3095. */
  3096. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  3097. /**
  3098. * TSL object that represents the shader variable `Shininess`.
  3099. *
  3100. * @tsl
  3101. * @type {PropertyNode<float>}
  3102. */
  3103. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  3104. /**
  3105. * TSL object that represents the shader variable `Output`.
  3106. *
  3107. * @tsl
  3108. * @type {PropertyNode<vec4>}
  3109. */
  3110. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  3111. /**
  3112. * TSL object that represents the shader variable `dashSize`.
  3113. *
  3114. * @tsl
  3115. * @type {PropertyNode<float>}
  3116. */
  3117. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  3118. /**
  3119. * TSL object that represents the shader variable `gapSize`.
  3120. *
  3121. * @tsl
  3122. * @type {PropertyNode<float>}
  3123. */
  3124. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  3125. /**
  3126. * TSL object that represents the shader variable `pointWidth`.
  3127. *
  3128. * @tsl
  3129. * @type {PropertyNode<float>}
  3130. */
  3131. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  3132. /**
  3133. * TSL object that represents the shader variable `IOR`.
  3134. *
  3135. * @tsl
  3136. * @type {PropertyNode<float>}
  3137. */
  3138. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  3139. /**
  3140. * TSL object that represents the shader variable `Transmission`.
  3141. *
  3142. * @tsl
  3143. * @type {PropertyNode<float>}
  3144. */
  3145. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  3146. /**
  3147. * TSL object that represents the shader variable `Thickness`.
  3148. *
  3149. * @tsl
  3150. * @type {PropertyNode<float>}
  3151. */
  3152. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  3153. /**
  3154. * TSL object that represents the shader variable `AttenuationDistance`.
  3155. *
  3156. * @tsl
  3157. * @type {PropertyNode<float>}
  3158. */
  3159. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  3160. /**
  3161. * TSL object that represents the shader variable `AttenuationColor`.
  3162. *
  3163. * @tsl
  3164. * @type {PropertyNode<color>}
  3165. */
  3166. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  3167. /**
  3168. * TSL object that represents the shader variable `Dispersion`.
  3169. *
  3170. * @tsl
  3171. * @type {PropertyNode<float>}
  3172. */
  3173. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  3174. /**
  3175. * This node can be used to group single instances of {@link UniformNode}
  3176. * and manage them as a uniform buffer.
  3177. *
  3178. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  3179. * will be used when defining the {@link UniformNode#groupNode} property.
  3180. *
  3181. * - `objectGroup`: Uniform buffer per object.
  3182. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  3183. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  3184. *
  3185. * @augments Node
  3186. */
  3187. class UniformGroupNode extends Node {
  3188. static get type() {
  3189. return 'UniformGroupNode';
  3190. }
  3191. /**
  3192. * Constructs a new uniform group node.
  3193. *
  3194. * @param {string} name - The name of the uniform group node.
  3195. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  3196. * @param {number} [order=1] - Influences the internal sorting.
  3197. */
  3198. constructor( name, shared = false, order = 1 ) {
  3199. super( 'string' );
  3200. /**
  3201. * The name of the uniform group node.
  3202. *
  3203. * @type {string}
  3204. */
  3205. this.name = name;
  3206. /**
  3207. * Whether this uniform group node is shared or not.
  3208. *
  3209. * @type {boolean}
  3210. * @default false
  3211. */
  3212. this.shared = shared;
  3213. /**
  3214. * Influences the internal sorting.
  3215. * TODO: Add details when this property should be changed.
  3216. *
  3217. * @type {number}
  3218. * @default 1
  3219. */
  3220. this.order = order;
  3221. /**
  3222. * This flag can be used for type testing.
  3223. *
  3224. * @type {boolean}
  3225. * @readonly
  3226. * @default true
  3227. */
  3228. this.isUniformGroup = true;
  3229. }
  3230. serialize( data ) {
  3231. super.serialize( data );
  3232. data.name = this.name;
  3233. data.version = this.version;
  3234. data.shared = this.shared;
  3235. }
  3236. deserialize( data ) {
  3237. super.deserialize( data );
  3238. this.name = data.name;
  3239. this.version = data.version;
  3240. this.shared = data.shared;
  3241. }
  3242. }
  3243. /**
  3244. * TSL function for creating a uniform group node with the given name.
  3245. *
  3246. * @tsl
  3247. * @function
  3248. * @param {string} name - The name of the uniform group node.
  3249. * @returns {UniformGroupNode}
  3250. */
  3251. const uniformGroup = ( name ) => new UniformGroupNode( name );
  3252. /**
  3253. * TSL function for creating a shared uniform group node with the given name and order.
  3254. *
  3255. * @tsl
  3256. * @function
  3257. * @param {string} name - The name of the uniform group node.
  3258. * @param {number} [order=0] - Influences the internal sorting.
  3259. * @returns {UniformGroupNode}
  3260. */
  3261. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  3262. /**
  3263. * TSL object that represents a shared uniform group node which is updated once per frame.
  3264. *
  3265. * @tsl
  3266. * @type {UniformGroupNode}
  3267. */
  3268. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  3269. /**
  3270. * TSL object that represents a shared uniform group node which is updated once per render.
  3271. *
  3272. * @tsl
  3273. * @type {UniformGroupNode}
  3274. */
  3275. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  3276. /**
  3277. * TSL object that represents a uniform group node which is updated once per object.
  3278. *
  3279. * @tsl
  3280. * @type {UniformGroupNode}
  3281. */
  3282. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  3283. /**
  3284. * Class for representing a uniform.
  3285. *
  3286. * @augments InputNode
  3287. */
  3288. class UniformNode extends InputNode {
  3289. static get type() {
  3290. return 'UniformNode';
  3291. }
  3292. /**
  3293. * Constructs a new uniform node.
  3294. *
  3295. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3296. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3297. */
  3298. constructor( value, nodeType = null ) {
  3299. super( value, nodeType );
  3300. /**
  3301. * This flag can be used for type testing.
  3302. *
  3303. * @type {boolean}
  3304. * @readonly
  3305. * @default true
  3306. */
  3307. this.isUniformNode = true;
  3308. /**
  3309. * The name or label of the uniform.
  3310. *
  3311. * @type {string}
  3312. * @default ''
  3313. */
  3314. this.name = '';
  3315. /**
  3316. * The uniform group of this uniform. By default, uniforms are
  3317. * managed per object but they might belong to a shared group
  3318. * which is updated per frame or render call.
  3319. *
  3320. * @type {UniformGroupNode}
  3321. */
  3322. this.groupNode = objectGroup;
  3323. }
  3324. /**
  3325. * Sets the {@link UniformNode#name} property.
  3326. *
  3327. * @param {string} name - The name of the uniform.
  3328. * @return {UniformNode} A reference to this node.
  3329. */
  3330. setName( name ) {
  3331. this.name = name;
  3332. return this;
  3333. }
  3334. /**
  3335. * Sets the {@link UniformNode#name} property.
  3336. *
  3337. * @deprecated
  3338. * @param {string} name - The name of the uniform.
  3339. * @return {UniformNode} A reference to this node.
  3340. */
  3341. label( name ) {
  3342. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  3343. return this.setName( name );
  3344. }
  3345. /**
  3346. * Sets the {@link UniformNode#groupNode} property.
  3347. *
  3348. * @param {UniformGroupNode} group - The uniform group.
  3349. * @return {UniformNode} A reference to this node.
  3350. */
  3351. setGroup( group ) {
  3352. this.groupNode = group;
  3353. return this;
  3354. }
  3355. /**
  3356. * Returns the {@link UniformNode#groupNode}.
  3357. *
  3358. * @return {UniformGroupNode} The uniform group.
  3359. */
  3360. getGroup() {
  3361. return this.groupNode;
  3362. }
  3363. /**
  3364. * By default, this method returns the result of {@link Node#getHash} but derived
  3365. * classes might overwrite this method with a different implementation.
  3366. *
  3367. * @param {NodeBuilder} builder - The current node builder.
  3368. * @return {string} The uniform hash.
  3369. */
  3370. getUniformHash( builder ) {
  3371. return this.getHash( builder );
  3372. }
  3373. onUpdate( callback, updateType ) {
  3374. callback = callback.bind( this );
  3375. return super.onUpdate( ( frame ) => {
  3376. const value = callback( frame, this );
  3377. if ( value !== undefined ) {
  3378. this.value = value;
  3379. }
  3380. }, updateType );
  3381. }
  3382. getInputType( builder ) {
  3383. let type = super.getInputType( builder );
  3384. if ( type === 'bool' ) {
  3385. type = 'uint';
  3386. }
  3387. return type;
  3388. }
  3389. generate( builder, output ) {
  3390. const type = this.getNodeType( builder );
  3391. const hash = this.getUniformHash( builder );
  3392. let sharedNode = builder.getNodeFromHash( hash );
  3393. if ( sharedNode === undefined ) {
  3394. builder.setHashNode( this, hash );
  3395. sharedNode = this;
  3396. }
  3397. const sharedNodeType = sharedNode.getInputType( builder );
  3398. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.nodeName );
  3399. const uniformName = builder.getPropertyName( nodeUniform );
  3400. if ( builder.context.nodeName !== undefined ) delete builder.context.nodeName;
  3401. //
  3402. let snippet = uniformName;
  3403. if ( type === 'bool' ) {
  3404. // cache to variable
  3405. const nodeData = builder.getDataFromNode( this );
  3406. let propertyName = nodeData.propertyName;
  3407. if ( propertyName === undefined ) {
  3408. const nodeVar = builder.getVarFromNode( this, null, 'bool' );
  3409. propertyName = builder.getPropertyName( nodeVar );
  3410. nodeData.propertyName = propertyName;
  3411. snippet = builder.format( uniformName, sharedNodeType, type );
  3412. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  3413. }
  3414. snippet = propertyName;
  3415. }
  3416. return builder.format( snippet, type, output );
  3417. }
  3418. }
  3419. /**
  3420. * TSL function for creating a uniform node.
  3421. *
  3422. * @tsl
  3423. * @function
  3424. * @param {any|string} value - The value of this uniform or your type. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3425. * @param {string} [type] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3426. * @returns {UniformNode}
  3427. */
  3428. const uniform = ( value, type ) => {
  3429. const nodeType = getConstNodeType( type || value );
  3430. if ( nodeType === value ) {
  3431. // if the value is a type but no having a value
  3432. value = getValueFromType( nodeType );
  3433. }
  3434. // @TODO: get ConstNode from .traverse() in the future
  3435. value = ( value && value.isNode === true ) ? ( value.node && value.node.value ) || value.value : value;
  3436. return nodeObject( new UniformNode( value, nodeType ) );
  3437. };
  3438. /**
  3439. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3440. * ```js
  3441. * const colors = array( [
  3442. * vec3( 1, 0, 0 ),
  3443. * vec3( 0, 1, 0 ),
  3444. * vec3( 0, 0, 1 )
  3445. * ] );
  3446. *
  3447. * const redColor = tintColors.element( 0 );
  3448. * ```
  3449. *
  3450. * @augments TempNode
  3451. */
  3452. class ArrayNode extends TempNode {
  3453. static get type() {
  3454. return 'ArrayNode';
  3455. }
  3456. /**
  3457. * Constructs a new array node.
  3458. *
  3459. * @param {?string} nodeType - The data type of the elements.
  3460. * @param {number} count - Size of the array.
  3461. * @param {?Array<Node>} [values=null] - Array default values.
  3462. */
  3463. constructor( nodeType, count, values = null ) {
  3464. super( nodeType );
  3465. /**
  3466. * Array size.
  3467. *
  3468. * @type {number}
  3469. */
  3470. this.count = count;
  3471. /**
  3472. * Array default values.
  3473. *
  3474. * @type {?Array<Node>}
  3475. */
  3476. this.values = values;
  3477. /**
  3478. * This flag can be used for type testing.
  3479. *
  3480. * @type {boolean}
  3481. * @readonly
  3482. * @default true
  3483. */
  3484. this.isArrayNode = true;
  3485. }
  3486. /**
  3487. * Returns the number of elements in the node array.
  3488. *
  3489. * @param {NodeBuilder} builder - The current node builder.
  3490. * @return {number} The number of elements in the node array.
  3491. */
  3492. getArrayCount( /*builder*/ ) {
  3493. return this.count;
  3494. }
  3495. /**
  3496. * Returns the node's type.
  3497. *
  3498. * @param {NodeBuilder} builder - The current node builder.
  3499. * @return {string} The type of the node.
  3500. */
  3501. getNodeType( builder ) {
  3502. if ( this.nodeType === null ) {
  3503. this.nodeType = this.values[ 0 ].getNodeType( builder );
  3504. }
  3505. return this.nodeType;
  3506. }
  3507. /**
  3508. * Returns the node's type.
  3509. *
  3510. * @param {NodeBuilder} builder - The current node builder.
  3511. * @return {string} The type of the node.
  3512. */
  3513. getElementType( builder ) {
  3514. return this.getNodeType( builder );
  3515. }
  3516. /**
  3517. * This method builds the output node and returns the resulting array as a shader string.
  3518. *
  3519. * @param {NodeBuilder} builder - The current node builder.
  3520. * @return {string} The generated shader string.
  3521. */
  3522. generate( builder ) {
  3523. const type = this.getNodeType( builder );
  3524. return builder.generateArray( type, this.count, this.values );
  3525. }
  3526. }
  3527. /**
  3528. * TSL function for creating an array node.
  3529. *
  3530. * @tsl
  3531. * @function
  3532. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3533. * or an array containing the default values (e.g., [ vec3() ]).
  3534. * @param {?number} [count] - Size of the array.
  3535. * @returns {ArrayNode}
  3536. */
  3537. const array = ( ...params ) => {
  3538. let node;
  3539. if ( params.length === 1 ) {
  3540. const values = params[ 0 ];
  3541. node = new ArrayNode( null, values.length, values );
  3542. } else {
  3543. const nodeType = params[ 0 ];
  3544. const count = params[ 1 ];
  3545. node = new ArrayNode( nodeType, count );
  3546. }
  3547. return nodeObject( node );
  3548. };
  3549. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3550. /**
  3551. * These node represents an assign operation. Meaning a node is assigned
  3552. * to another node.
  3553. *
  3554. * @augments TempNode
  3555. */
  3556. class AssignNode extends TempNode {
  3557. static get type() {
  3558. return 'AssignNode';
  3559. }
  3560. /**
  3561. * Constructs a new assign node.
  3562. *
  3563. * @param {Node} targetNode - The target node.
  3564. * @param {Node} sourceNode - The source type.
  3565. */
  3566. constructor( targetNode, sourceNode ) {
  3567. super();
  3568. /**
  3569. * The target node.
  3570. *
  3571. * @type {Node}
  3572. */
  3573. this.targetNode = targetNode;
  3574. /**
  3575. * The source node.
  3576. *
  3577. * @type {Node}
  3578. */
  3579. this.sourceNode = sourceNode;
  3580. /**
  3581. * This flag can be used for type testing.
  3582. *
  3583. * @type {boolean}
  3584. * @readonly
  3585. * @default true
  3586. */
  3587. this.isAssignNode = true;
  3588. }
  3589. /**
  3590. * Whether this node is used more than once in context of other nodes. This method
  3591. * is overwritten since it always returns `false` (assigns are unique).
  3592. *
  3593. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3594. */
  3595. hasDependencies() {
  3596. return false;
  3597. }
  3598. getNodeType( builder, output ) {
  3599. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3600. }
  3601. /**
  3602. * Whether a split is required when assigning source to target. This can happen when the component length of
  3603. * target and source data type does not match.
  3604. *
  3605. * @param {NodeBuilder} builder - The current node builder.
  3606. * @return {boolean} Whether a split is required when assigning source to target.
  3607. */
  3608. needsSplitAssign( builder ) {
  3609. const { targetNode } = this;
  3610. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3611. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3612. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3613. return assignDifferentVector;
  3614. }
  3615. return false;
  3616. }
  3617. setup( builder ) {
  3618. const { targetNode, sourceNode } = this;
  3619. const scope = targetNode.getScope();
  3620. const targetProperties = builder.getNodeProperties( scope );
  3621. targetProperties.assign = true;
  3622. const properties = builder.getNodeProperties( this );
  3623. properties.sourceNode = sourceNode;
  3624. properties.targetNode = targetNode.context( { assign: true } );
  3625. }
  3626. generate( builder, output ) {
  3627. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3628. const needsSplitAssign = this.needsSplitAssign( builder );
  3629. const target = targetNode.build( builder );
  3630. const targetType = targetNode.getNodeType( builder );
  3631. const source = sourceNode.build( builder, targetType );
  3632. const sourceType = sourceNode.getNodeType( builder );
  3633. const nodeData = builder.getDataFromNode( this );
  3634. //
  3635. let snippet;
  3636. if ( nodeData.initialized === true ) {
  3637. if ( output !== 'void' ) {
  3638. snippet = target;
  3639. }
  3640. } else if ( needsSplitAssign ) {
  3641. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3642. const sourceProperty = builder.getPropertyName( sourceVar );
  3643. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3644. const splitNode = targetNode.node;
  3645. const splitTargetNode = splitNode.node.context( { assign: true } );
  3646. const targetRoot = splitTargetNode.build( builder );
  3647. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3648. const component = splitNode.components[ i ];
  3649. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3650. }
  3651. if ( output !== 'void' ) {
  3652. snippet = target;
  3653. }
  3654. } else {
  3655. snippet = `${ target } = ${ source }`;
  3656. if ( output === 'void' || sourceType === 'void' ) {
  3657. builder.addLineFlowCode( snippet, this );
  3658. if ( output !== 'void' ) {
  3659. snippet = target;
  3660. }
  3661. }
  3662. }
  3663. nodeData.initialized = true;
  3664. return builder.format( snippet, targetType, output );
  3665. }
  3666. }
  3667. /**
  3668. * TSL function for creating an assign node.
  3669. *
  3670. * @tsl
  3671. * @function
  3672. * @param {Node} targetNode - The target node.
  3673. * @param {Node} sourceNode - The source type.
  3674. * @returns {AssignNode}
  3675. */
  3676. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3677. addMethodChaining( 'assign', assign );
  3678. /**
  3679. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3680. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3681. * this logic.
  3682. *
  3683. * @augments TempNode
  3684. */
  3685. class FunctionCallNode extends TempNode {
  3686. static get type() {
  3687. return 'FunctionCallNode';
  3688. }
  3689. /**
  3690. * Constructs a new function call node.
  3691. *
  3692. * @param {?FunctionNode} functionNode - The function node.
  3693. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3694. */
  3695. constructor( functionNode = null, parameters = {} ) {
  3696. super();
  3697. /**
  3698. * The function node.
  3699. *
  3700. * @type {?FunctionNode}
  3701. * @default null
  3702. */
  3703. this.functionNode = functionNode;
  3704. /**
  3705. * The parameters of the function call.
  3706. *
  3707. * @type {Object<string, Node>}
  3708. * @default {}
  3709. */
  3710. this.parameters = parameters;
  3711. }
  3712. /**
  3713. * Sets the parameters of the function call node.
  3714. *
  3715. * @param {Object<string, Node>} parameters - The parameters to set.
  3716. * @return {FunctionCallNode} A reference to this node.
  3717. */
  3718. setParameters( parameters ) {
  3719. this.parameters = parameters;
  3720. return this;
  3721. }
  3722. /**
  3723. * Returns the parameters of the function call node.
  3724. *
  3725. * @return {Object<string, Node>} The parameters of this node.
  3726. */
  3727. getParameters() {
  3728. return this.parameters;
  3729. }
  3730. /**
  3731. * Returns the type of this function call node.
  3732. *
  3733. * @param {NodeBuilder} builder - The current node builder.
  3734. * @returns {string} The type of this node.
  3735. */
  3736. getNodeType( builder ) {
  3737. return this.functionNode.getNodeType( builder );
  3738. }
  3739. /**
  3740. * Returns the function node of this function call node.
  3741. *
  3742. * @param {NodeBuilder} builder - The current node builder.
  3743. * @param {string} [name] - The name of the member.
  3744. * @returns {string} The type of the member.
  3745. */
  3746. getMemberType( builder, name ) {
  3747. return this.functionNode.getMemberType( builder, name );
  3748. }
  3749. generate( builder ) {
  3750. const params = [];
  3751. const functionNode = this.functionNode;
  3752. const inputs = functionNode.getInputs( builder );
  3753. const parameters = this.parameters;
  3754. const generateInput = ( node, inputNode ) => {
  3755. const type = inputNode.type;
  3756. const pointer = type === 'pointer';
  3757. let output;
  3758. if ( pointer ) output = '&' + node.build( builder );
  3759. else output = node.build( builder, type );
  3760. return output;
  3761. };
  3762. if ( Array.isArray( parameters ) ) {
  3763. if ( parameters.length > inputs.length ) {
  3764. error( 'TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3765. parameters.length = inputs.length;
  3766. } else if ( parameters.length < inputs.length ) {
  3767. error( 'TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3768. while ( parameters.length < inputs.length ) {
  3769. parameters.push( float( 0 ) );
  3770. }
  3771. }
  3772. for ( let i = 0; i < parameters.length; i ++ ) {
  3773. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3774. }
  3775. } else {
  3776. for ( const inputNode of inputs ) {
  3777. const node = parameters[ inputNode.name ];
  3778. if ( node !== undefined ) {
  3779. params.push( generateInput( node, inputNode ) );
  3780. } else {
  3781. error( `TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3782. params.push( generateInput( float( 0 ), inputNode ) );
  3783. }
  3784. }
  3785. }
  3786. const functionName = functionNode.build( builder, 'property' );
  3787. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3788. }
  3789. }
  3790. const call = ( func, ...params ) => {
  3791. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3792. return new FunctionCallNode( nodeObject( func ), params );
  3793. };
  3794. addMethodChaining( 'call', call );
  3795. const _vectorOperators = {
  3796. '==': 'equal',
  3797. '!=': 'notEqual',
  3798. '<': 'lessThan',
  3799. '>': 'greaterThan',
  3800. '<=': 'lessThanEqual',
  3801. '>=': 'greaterThanEqual',
  3802. '%': 'mod'
  3803. };
  3804. /**
  3805. * This node represents basic mathematical and logical operations like addition,
  3806. * subtraction or comparisons (e.g. `equal()`).
  3807. *
  3808. * @augments TempNode
  3809. */
  3810. class OperatorNode extends TempNode {
  3811. static get type() {
  3812. return 'OperatorNode';
  3813. }
  3814. /**
  3815. * Constructs a new operator node.
  3816. *
  3817. * @param {string} op - The operator.
  3818. * @param {Node} aNode - The first input.
  3819. * @param {Node} bNode - The second input.
  3820. * @param {...Node} params - Additional input parameters.
  3821. */
  3822. constructor( op, aNode, bNode, ...params ) {
  3823. super();
  3824. if ( params.length > 0 ) {
  3825. let finalOp = new OperatorNode( op, aNode, bNode );
  3826. for ( let i = 0; i < params.length - 1; i ++ ) {
  3827. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3828. }
  3829. aNode = finalOp;
  3830. bNode = params[ params.length - 1 ];
  3831. }
  3832. /**
  3833. * The operator.
  3834. *
  3835. * @type {string}
  3836. */
  3837. this.op = op;
  3838. /**
  3839. * The first input.
  3840. *
  3841. * @type {Node}
  3842. */
  3843. this.aNode = aNode;
  3844. /**
  3845. * The second input.
  3846. *
  3847. * @type {Node}
  3848. */
  3849. this.bNode = bNode;
  3850. /**
  3851. * This flag can be used for type testing.
  3852. *
  3853. * @type {boolean}
  3854. * @readonly
  3855. * @default true
  3856. */
  3857. this.isOperatorNode = true;
  3858. }
  3859. /**
  3860. * Returns the operator method name.
  3861. *
  3862. * @param {NodeBuilder} builder - The current node builder.
  3863. * @param {string} output - The output type.
  3864. * @returns {string} The operator method name.
  3865. */
  3866. getOperatorMethod( builder, output ) {
  3867. return builder.getMethod( _vectorOperators[ this.op ], output );
  3868. }
  3869. /**
  3870. * This method is overwritten since the node type is inferred from the operator
  3871. * and the input node types.
  3872. *
  3873. * @param {NodeBuilder} builder - The current node builder.
  3874. * @param {?string} [output=null] - The output type.
  3875. * @return {string} The node type.
  3876. */
  3877. getNodeType( builder, output = null ) {
  3878. const op = this.op;
  3879. const aNode = this.aNode;
  3880. const bNode = this.bNode;
  3881. const typeA = aNode.getNodeType( builder );
  3882. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  3883. if ( typeA === 'void' || typeB === 'void' ) {
  3884. return output || 'void';
  3885. } else if ( op === '%' ) {
  3886. return typeA;
  3887. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3888. return builder.getIntegerType( typeA );
  3889. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3890. return 'bool';
  3891. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3892. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3893. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3894. } else {
  3895. // Handle matrix operations
  3896. if ( builder.isMatrix( typeA ) ) {
  3897. if ( typeB === 'float' ) {
  3898. return typeA; // matrix * scalar = matrix
  3899. } else if ( builder.isVector( typeB ) ) {
  3900. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3901. } else if ( builder.isMatrix( typeB ) ) {
  3902. return typeA; // matrix * matrix
  3903. }
  3904. } else if ( builder.isMatrix( typeB ) ) {
  3905. if ( typeA === 'float' ) {
  3906. return typeB; // scalar * matrix = matrix
  3907. } else if ( builder.isVector( typeA ) ) {
  3908. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3909. }
  3910. }
  3911. // Handle non-matrix cases
  3912. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3913. // anytype x anytype: use the greater length vector
  3914. return typeB;
  3915. }
  3916. return typeA;
  3917. }
  3918. }
  3919. generate( builder, output ) {
  3920. const op = this.op;
  3921. const { aNode, bNode } = this;
  3922. const type = this.getNodeType( builder, output );
  3923. let typeA = null;
  3924. let typeB = null;
  3925. if ( type !== 'void' ) {
  3926. typeA = aNode.getNodeType( builder );
  3927. typeB = bNode ? bNode.getNodeType( builder ) : null;
  3928. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3929. if ( builder.isVector( typeA ) ) {
  3930. typeB = typeA;
  3931. } else if ( builder.isVector( typeB ) ) {
  3932. typeA = typeB;
  3933. } else if ( typeA !== typeB ) {
  3934. typeA = typeB = 'float';
  3935. }
  3936. } else if ( op === '>>' || op === '<<' ) {
  3937. typeA = type;
  3938. typeB = builder.changeComponentType( typeB, 'uint' );
  3939. } else if ( op === '%' ) {
  3940. typeA = type;
  3941. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3942. } else if ( builder.isMatrix( typeA ) ) {
  3943. if ( typeB === 'float' ) {
  3944. // Keep matrix type for typeA, but ensure typeB stays float
  3945. typeB = 'float';
  3946. } else if ( builder.isVector( typeB ) ) {
  3947. // matrix x vector
  3948. typeB = builder.getVectorFromMatrix( typeA );
  3949. } else if ( builder.isMatrix( typeB ) ) ; else {
  3950. typeA = typeB = type;
  3951. }
  3952. } else if ( builder.isMatrix( typeB ) ) {
  3953. if ( typeA === 'float' ) {
  3954. // Keep matrix type for typeB, but ensure typeA stays float
  3955. typeA = 'float';
  3956. } else if ( builder.isVector( typeA ) ) {
  3957. // vector x matrix
  3958. typeA = builder.getVectorFromMatrix( typeB );
  3959. } else {
  3960. typeA = typeB = type;
  3961. }
  3962. } else {
  3963. // anytype x anytype
  3964. typeA = typeB = type;
  3965. }
  3966. } else {
  3967. typeA = typeB = type;
  3968. }
  3969. const a = aNode.build( builder, typeA );
  3970. const b = bNode ? bNode.build( builder, typeB ) : null;
  3971. const fnOpSnippet = builder.getFunctionOperator( op );
  3972. if ( output !== 'void' ) {
  3973. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  3974. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3975. if ( isGLSL ) {
  3976. if ( builder.isVector( typeA ) ) {
  3977. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  3978. } else {
  3979. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3980. }
  3981. } else {
  3982. // WGSL
  3983. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3984. }
  3985. } else if ( op === '%' ) {
  3986. if ( builder.isInteger( typeB ) ) {
  3987. return builder.format( `( ${ a } % ${ b } )`, type, output );
  3988. } else {
  3989. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  3990. }
  3991. } else if ( op === '!' || op === '~' ) {
  3992. return builder.format( `(${op}${a})`, typeA, output );
  3993. } else if ( fnOpSnippet ) {
  3994. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3995. } else {
  3996. // Handle matrix operations
  3997. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3998. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  3999. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  4000. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4001. } else {
  4002. let snippet = `( ${ a } ${ op } ${ b } )`;
  4003. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  4004. snippet = `all${ snippet }`;
  4005. }
  4006. return builder.format( snippet, type, output );
  4007. }
  4008. }
  4009. } else if ( typeA !== 'void' ) {
  4010. if ( fnOpSnippet ) {
  4011. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4012. } else {
  4013. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4014. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  4015. } else {
  4016. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4017. }
  4018. }
  4019. }
  4020. }
  4021. serialize( data ) {
  4022. super.serialize( data );
  4023. data.op = this.op;
  4024. }
  4025. deserialize( data ) {
  4026. super.deserialize( data );
  4027. this.op = data.op;
  4028. }
  4029. }
  4030. /**
  4031. * Returns the addition of two or more value.
  4032. *
  4033. * @tsl
  4034. * @function
  4035. * @param {Node} a - The first input.
  4036. * @param {Node} b - The second input.
  4037. * @param {...Node} params - Additional input parameters.
  4038. * @returns {OperatorNode}
  4039. */
  4040. const add = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  4041. /**
  4042. * Returns the subtraction of two or more value.
  4043. *
  4044. * @tsl
  4045. * @function
  4046. * @param {Node} a - The first input.
  4047. * @param {Node} b - The second input.
  4048. * @param {...Node} params - Additional input parameters.
  4049. * @returns {OperatorNode}
  4050. */
  4051. const sub = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  4052. /**
  4053. * Returns the multiplication of two or more value.
  4054. *
  4055. * @tsl
  4056. * @function
  4057. * @param {Node} a - The first input.
  4058. * @param {Node} b - The second input.
  4059. * @param {...Node} params - Additional input parameters.
  4060. * @returns {OperatorNode}
  4061. */
  4062. const mul = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  4063. /**
  4064. * Returns the division of two or more value.
  4065. *
  4066. * @tsl
  4067. * @function
  4068. * @param {Node} a - The first input.
  4069. * @param {Node} b - The second input.
  4070. * @param {...Node} params - Additional input parameters.
  4071. * @returns {OperatorNode}
  4072. */
  4073. const div = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  4074. /**
  4075. * Computes the remainder of dividing the first node by the second one.
  4076. *
  4077. * @tsl
  4078. * @function
  4079. * @param {Node} a - The first input.
  4080. * @param {Node} b - The second input.
  4081. * @returns {OperatorNode}
  4082. */
  4083. const mod = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  4084. /**
  4085. * Checks if two nodes are equal.
  4086. *
  4087. * @tsl
  4088. * @function
  4089. * @param {Node} a - The first input.
  4090. * @param {Node} b - The second input.
  4091. * @returns {OperatorNode}
  4092. */
  4093. const equal = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  4094. /**
  4095. * Checks if two nodes are not equal.
  4096. *
  4097. * @tsl
  4098. * @function
  4099. * @param {Node} a - The first input.
  4100. * @param {Node} b - The second input.
  4101. * @returns {OperatorNode}
  4102. */
  4103. const notEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  4104. /**
  4105. * Checks if the first node is less than the second.
  4106. *
  4107. * @tsl
  4108. * @function
  4109. * @param {Node} a - The first input.
  4110. * @param {Node} b - The second input.
  4111. * @returns {OperatorNode}
  4112. */
  4113. const lessThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  4114. /**
  4115. * Checks if the first node is greater than the second.
  4116. *
  4117. * @tsl
  4118. * @function
  4119. * @param {Node} a - The first input.
  4120. * @param {Node} b - The second input.
  4121. * @returns {OperatorNode}
  4122. */
  4123. const greaterThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  4124. /**
  4125. * Checks if the first node is less than or equal to the second.
  4126. *
  4127. * @tsl
  4128. * @function
  4129. * @param {Node} a - The first input.
  4130. * @param {Node} b - The second input.
  4131. * @returns {OperatorNode}
  4132. */
  4133. const lessThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  4134. /**
  4135. * Checks if the first node is greater than or equal to the second.
  4136. *
  4137. * @tsl
  4138. * @function
  4139. * @param {Node} a - The first input.
  4140. * @param {Node} b - The second input.
  4141. * @returns {OperatorNode}
  4142. */
  4143. const greaterThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  4144. /**
  4145. * Performs a logical AND operation on multiple nodes.
  4146. *
  4147. * @tsl
  4148. * @function
  4149. * @param {...Node} nodes - The input nodes to be combined using AND.
  4150. * @returns {OperatorNode}
  4151. */
  4152. const and = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  4153. /**
  4154. * Performs a logical OR operation on multiple nodes.
  4155. *
  4156. * @tsl
  4157. * @function
  4158. * @param {...Node} nodes - The input nodes to be combined using OR.
  4159. * @returns {OperatorNode}
  4160. */
  4161. const or = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  4162. /**
  4163. * Performs logical NOT on a node.
  4164. *
  4165. * @tsl
  4166. * @function
  4167. * @param {Node} value - The value.
  4168. * @returns {OperatorNode}
  4169. */
  4170. const not = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  4171. /**
  4172. * Performs logical XOR on two nodes.
  4173. *
  4174. * @tsl
  4175. * @function
  4176. * @param {Node} a - The first input.
  4177. * @param {Node} b - The second input.
  4178. * @returns {OperatorNode}
  4179. */
  4180. const xor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  4181. /**
  4182. * Performs bitwise AND on two nodes.
  4183. *
  4184. * @tsl
  4185. * @function
  4186. * @param {Node} a - The first input.
  4187. * @param {Node} b - The second input.
  4188. * @returns {OperatorNode}
  4189. */
  4190. const bitAnd = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  4191. /**
  4192. * Performs bitwise NOT on a node.
  4193. *
  4194. * @tsl
  4195. * @function
  4196. * @param {Node} a - The first input.
  4197. * @param {Node} b - The second input.
  4198. * @returns {OperatorNode}
  4199. */
  4200. const bitNot = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '~' ).setParameterLength( 1 ).setName( 'bitNot' );
  4201. /**
  4202. * Performs bitwise OR on two nodes.
  4203. *
  4204. * @tsl
  4205. * @function
  4206. * @param {Node} a - The first input.
  4207. * @param {Node} b - The second input.
  4208. * @returns {OperatorNode}
  4209. */
  4210. const bitOr = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  4211. /**
  4212. * Performs bitwise XOR on two nodes.
  4213. *
  4214. * @tsl
  4215. * @function
  4216. * @param {Node} a - The first input.
  4217. * @param {Node} b - The second input.
  4218. * @returns {OperatorNode}
  4219. */
  4220. const bitXor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  4221. /**
  4222. * Shifts a node to the left.
  4223. *
  4224. * @tsl
  4225. * @function
  4226. * @param {Node} a - The node to shift.
  4227. * @param {Node} b - The value to shift.
  4228. * @returns {OperatorNode}
  4229. */
  4230. const shiftLeft = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  4231. /**
  4232. * Shifts a node to the right.
  4233. *
  4234. * @tsl
  4235. * @function
  4236. * @param {Node} a - The node to shift.
  4237. * @param {Node} b - The value to shift.
  4238. * @returns {OperatorNode}
  4239. */
  4240. const shiftRight = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  4241. /**
  4242. * Increments a node by 1.
  4243. *
  4244. * @tsl
  4245. * @function
  4246. * @param {Node} a - The node to increment.
  4247. * @returns {OperatorNode}
  4248. */
  4249. const incrementBefore = Fn( ( [ a ] ) => {
  4250. a.addAssign( 1 );
  4251. return a;
  4252. } );
  4253. /**
  4254. * Decrements a node by 1.
  4255. *
  4256. * @tsl
  4257. * @function
  4258. * @param {Node} a - The node to decrement.
  4259. * @returns {OperatorNode}
  4260. */
  4261. const decrementBefore = Fn( ( [ a ] ) => {
  4262. a.subAssign( 1 );
  4263. return a;
  4264. } );
  4265. /**
  4266. * Increments a node by 1 and returns the previous value.
  4267. *
  4268. * @tsl
  4269. * @function
  4270. * @param {Node} a - The node to increment.
  4271. * @returns {OperatorNode}
  4272. */
  4273. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4274. const temp = int( a ).toConst();
  4275. a.addAssign( 1 );
  4276. return temp;
  4277. } );
  4278. /**
  4279. * Decrements a node by 1 and returns the previous value.
  4280. *
  4281. * @tsl
  4282. * @function
  4283. * @param {Node} a - The node to decrement.
  4284. * @returns {OperatorNode}
  4285. */
  4286. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4287. const temp = int( a ).toConst();
  4288. a.subAssign( 1 );
  4289. return temp;
  4290. } );
  4291. addMethodChaining( 'add', add );
  4292. addMethodChaining( 'sub', sub );
  4293. addMethodChaining( 'mul', mul );
  4294. addMethodChaining( 'div', div );
  4295. addMethodChaining( 'mod', mod );
  4296. addMethodChaining( 'equal', equal );
  4297. addMethodChaining( 'notEqual', notEqual );
  4298. addMethodChaining( 'lessThan', lessThan );
  4299. addMethodChaining( 'greaterThan', greaterThan );
  4300. addMethodChaining( 'lessThanEqual', lessThanEqual );
  4301. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  4302. addMethodChaining( 'and', and );
  4303. addMethodChaining( 'or', or );
  4304. addMethodChaining( 'not', not );
  4305. addMethodChaining( 'xor', xor );
  4306. addMethodChaining( 'bitAnd', bitAnd );
  4307. addMethodChaining( 'bitNot', bitNot );
  4308. addMethodChaining( 'bitOr', bitOr );
  4309. addMethodChaining( 'bitXor', bitXor );
  4310. addMethodChaining( 'shiftLeft', shiftLeft );
  4311. addMethodChaining( 'shiftRight', shiftRight );
  4312. addMethodChaining( 'incrementBefore', incrementBefore );
  4313. addMethodChaining( 'decrementBefore', decrementBefore );
  4314. addMethodChaining( 'increment', increment );
  4315. addMethodChaining( 'decrement', decrement );
  4316. /**
  4317. * @tsl
  4318. * @function
  4319. * @deprecated since r175. Use {@link mod} instead.
  4320. *
  4321. * @param {Node} a - The first input.
  4322. * @param {Node} b - The second input.
  4323. * @returns {OperatorNode}
  4324. */
  4325. const modInt = ( a, b ) => { // @deprecated, r175
  4326. warn( 'TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  4327. return mod( int( a ), int( b ) );
  4328. };
  4329. addMethodChaining( 'modInt', modInt );
  4330. /**
  4331. * This node represents a variety of mathematical methods available in shaders.
  4332. * They are divided into three categories:
  4333. *
  4334. * - Methods with one input like `sin`, `cos` or `normalize`.
  4335. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4336. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4337. *
  4338. * @augments TempNode
  4339. */
  4340. class MathNode extends TempNode {
  4341. static get type() {
  4342. return 'MathNode';
  4343. }
  4344. /**
  4345. * Constructs a new math node.
  4346. *
  4347. * @param {string} method - The method name.
  4348. * @param {Node} aNode - The first input.
  4349. * @param {?Node} [bNode=null] - The second input.
  4350. * @param {?Node} [cNode=null] - The third input.
  4351. */
  4352. constructor( method, aNode, bNode = null, cNode = null ) {
  4353. super();
  4354. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4355. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4356. let finalOp = new MathNode( method, aNode, bNode );
  4357. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  4358. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4359. }
  4360. aNode = finalOp;
  4361. bNode = arguments[ arguments.length - 1 ];
  4362. cNode = null;
  4363. }
  4364. /**
  4365. * The method name.
  4366. *
  4367. * @type {string}
  4368. */
  4369. this.method = method;
  4370. /**
  4371. * The first input.
  4372. *
  4373. * @type {Node}
  4374. */
  4375. this.aNode = aNode;
  4376. /**
  4377. * The second input.
  4378. *
  4379. * @type {?Node}
  4380. * @default null
  4381. */
  4382. this.bNode = bNode;
  4383. /**
  4384. * The third input.
  4385. *
  4386. * @type {?Node}
  4387. * @default null
  4388. */
  4389. this.cNode = cNode;
  4390. /**
  4391. * This flag can be used for type testing.
  4392. *
  4393. * @type {boolean}
  4394. * @readonly
  4395. * @default true
  4396. */
  4397. this.isMathNode = true;
  4398. }
  4399. /**
  4400. * The input type is inferred from the node types of the input nodes.
  4401. *
  4402. * @param {NodeBuilder} builder - The current node builder.
  4403. * @return {string} The input type.
  4404. */
  4405. getInputType( builder ) {
  4406. const aType = this.aNode.getNodeType( builder );
  4407. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4408. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4409. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4410. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4411. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4412. if ( aLen > bLen && aLen > cLen ) {
  4413. return aType;
  4414. } else if ( bLen > cLen ) {
  4415. return bType;
  4416. } else if ( cLen > aLen ) {
  4417. return cType;
  4418. }
  4419. return aType;
  4420. }
  4421. /**
  4422. * The selected method as well as the input type determine the node type of this node.
  4423. *
  4424. * @param {NodeBuilder} builder - The current node builder.
  4425. * @return {string} The node type.
  4426. */
  4427. getNodeType( builder ) {
  4428. const method = this.method;
  4429. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4430. return 'float';
  4431. } else if ( method === MathNode.CROSS ) {
  4432. return 'vec3';
  4433. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4434. return 'bool';
  4435. } else if ( method === MathNode.EQUALS ) {
  4436. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4437. } else {
  4438. return this.getInputType( builder );
  4439. }
  4440. }
  4441. setup( builder ) {
  4442. const { aNode, bNode, method } = this;
  4443. let outputNode = null;
  4444. if ( method === MathNode.ONE_MINUS ) {
  4445. outputNode = sub( 1.0, aNode );
  4446. } else if ( method === MathNode.RECIPROCAL ) {
  4447. outputNode = div( 1.0, aNode );
  4448. } else if ( method === MathNode.DIFFERENCE ) {
  4449. outputNode = abs( sub( aNode, bNode ) );
  4450. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4451. // dir can be either a direction vector or a normal vector
  4452. // upper-left 3x3 of matrix is assumed to be orthogonal
  4453. let tA = aNode;
  4454. let tB = bNode;
  4455. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4456. tB = vec4( vec3( tB ), 0.0 );
  4457. } else {
  4458. tA = vec4( vec3( tA ), 0.0 );
  4459. }
  4460. const mulNode = mul( tA, tB ).xyz;
  4461. outputNode = normalize( mulNode );
  4462. }
  4463. if ( outputNode !== null ) {
  4464. return outputNode;
  4465. } else {
  4466. return super.setup( builder );
  4467. }
  4468. }
  4469. generate( builder, output ) {
  4470. const properties = builder.getNodeProperties( this );
  4471. if ( properties.outputNode ) {
  4472. return super.generate( builder, output );
  4473. }
  4474. let method = this.method;
  4475. const type = this.getNodeType( builder );
  4476. const inputType = this.getInputType( builder );
  4477. const a = this.aNode;
  4478. const b = this.bNode;
  4479. const c = this.cNode;
  4480. const coordinateSystem = builder.renderer.coordinateSystem;
  4481. if ( method === MathNode.NEGATE ) {
  4482. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4483. } else {
  4484. const params = [];
  4485. if ( method === MathNode.CROSS ) {
  4486. params.push(
  4487. a.build( builder, type ),
  4488. b.build( builder, type )
  4489. );
  4490. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4491. params.push(
  4492. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4493. b.build( builder, inputType )
  4494. );
  4495. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4496. params.push(
  4497. a.build( builder, inputType ),
  4498. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4499. );
  4500. } else if ( method === MathNode.REFRACT ) {
  4501. params.push(
  4502. a.build( builder, inputType ),
  4503. b.build( builder, inputType ),
  4504. c.build( builder, 'float' )
  4505. );
  4506. } else if ( method === MathNode.MIX ) {
  4507. params.push(
  4508. a.build( builder, inputType ),
  4509. b.build( builder, inputType ),
  4510. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4511. );
  4512. } else {
  4513. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4514. method = 'atan2';
  4515. }
  4516. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4517. warn( `TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4518. method = '/*' + method + '*/';
  4519. }
  4520. params.push( a.build( builder, inputType ) );
  4521. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4522. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4523. }
  4524. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4525. }
  4526. }
  4527. serialize( data ) {
  4528. super.serialize( data );
  4529. data.method = this.method;
  4530. }
  4531. deserialize( data ) {
  4532. super.deserialize( data );
  4533. this.method = data.method;
  4534. }
  4535. }
  4536. // 1 input
  4537. MathNode.ALL = 'all';
  4538. MathNode.ANY = 'any';
  4539. MathNode.RADIANS = 'radians';
  4540. MathNode.DEGREES = 'degrees';
  4541. MathNode.EXP = 'exp';
  4542. MathNode.EXP2 = 'exp2';
  4543. MathNode.LOG = 'log';
  4544. MathNode.LOG2 = 'log2';
  4545. MathNode.SQRT = 'sqrt';
  4546. MathNode.INVERSE_SQRT = 'inversesqrt';
  4547. MathNode.FLOOR = 'floor';
  4548. MathNode.CEIL = 'ceil';
  4549. MathNode.NORMALIZE = 'normalize';
  4550. MathNode.FRACT = 'fract';
  4551. MathNode.SIN = 'sin';
  4552. MathNode.COS = 'cos';
  4553. MathNode.TAN = 'tan';
  4554. MathNode.ASIN = 'asin';
  4555. MathNode.ACOS = 'acos';
  4556. MathNode.ATAN = 'atan';
  4557. MathNode.ABS = 'abs';
  4558. MathNode.SIGN = 'sign';
  4559. MathNode.LENGTH = 'length';
  4560. MathNode.NEGATE = 'negate';
  4561. MathNode.ONE_MINUS = 'oneMinus';
  4562. MathNode.DFDX = 'dFdx';
  4563. MathNode.DFDY = 'dFdy';
  4564. MathNode.ROUND = 'round';
  4565. MathNode.RECIPROCAL = 'reciprocal';
  4566. MathNode.TRUNC = 'trunc';
  4567. MathNode.FWIDTH = 'fwidth';
  4568. MathNode.TRANSPOSE = 'transpose';
  4569. MathNode.DETERMINANT = 'determinant';
  4570. MathNode.INVERSE = 'inverse';
  4571. // 2 inputs
  4572. MathNode.EQUALS = 'equals';
  4573. MathNode.MIN = 'min';
  4574. MathNode.MAX = 'max';
  4575. MathNode.STEP = 'step';
  4576. MathNode.REFLECT = 'reflect';
  4577. MathNode.DISTANCE = 'distance';
  4578. MathNode.DIFFERENCE = 'difference';
  4579. MathNode.DOT = 'dot';
  4580. MathNode.CROSS = 'cross';
  4581. MathNode.POW = 'pow';
  4582. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4583. // 3 inputs
  4584. MathNode.MIX = 'mix';
  4585. MathNode.CLAMP = 'clamp';
  4586. MathNode.REFRACT = 'refract';
  4587. MathNode.SMOOTHSTEP = 'smoothstep';
  4588. MathNode.FACEFORWARD = 'faceforward';
  4589. // 1 inputs
  4590. /**
  4591. * A small value used to handle floating-point precision errors.
  4592. *
  4593. * @tsl
  4594. * @type {Node<float>}
  4595. */
  4596. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4597. /**
  4598. * Represents infinity.
  4599. *
  4600. * @tsl
  4601. * @type {Node<float>}
  4602. */
  4603. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4604. /**
  4605. * Represents PI.
  4606. *
  4607. * @tsl
  4608. * @type {Node<float>}
  4609. */
  4610. const PI = /*@__PURE__*/ float( Math.PI );
  4611. /**
  4612. * Represents PI * 2. Please use the non-deprecated version `TWO_PI`.
  4613. *
  4614. * @tsl
  4615. * @deprecated
  4616. * @type {Node<float>}
  4617. */
  4618. const PI2 = /*@__PURE__*/ float( Math.PI * 2 ); // @deprecated r181
  4619. /**
  4620. * Represents PI * 2.
  4621. *
  4622. * @tsl
  4623. * @type {Node<float>}
  4624. */
  4625. const TWO_PI = /*@__PURE__*/ float( Math.PI * 2 );
  4626. /**
  4627. * Represents PI / 2.
  4628. *
  4629. * @tsl
  4630. * @type {Node<float>}
  4631. */
  4632. const HALF_PI = /*@__PURE__*/ float( Math.PI * 0.5 );
  4633. /**
  4634. * Returns `true` if all components of `x` are `true`.
  4635. *
  4636. * @tsl
  4637. * @function
  4638. * @param {Node | number} x - The parameter.
  4639. * @returns {Node<bool>}
  4640. */
  4641. const all = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4642. /**
  4643. * Returns `true` if any components of `x` are `true`.
  4644. *
  4645. * @tsl
  4646. * @function
  4647. * @param {Node | number} x - The parameter.
  4648. * @returns {Node<bool>}
  4649. */
  4650. const any = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4651. /**
  4652. * Converts a quantity in degrees to radians.
  4653. *
  4654. * @tsl
  4655. * @function
  4656. * @param {Node | number} x - The input in degrees.
  4657. * @returns {Node}
  4658. */
  4659. const radians = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4660. /**
  4661. * Convert a quantity in radians to degrees.
  4662. *
  4663. * @tsl
  4664. * @function
  4665. * @param {Node | number} x - The input in radians.
  4666. * @returns {Node}
  4667. */
  4668. const degrees = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4669. /**
  4670. * Returns the natural exponentiation of the parameter.
  4671. *
  4672. * @tsl
  4673. * @function
  4674. * @param {Node | number} x - The parameter.
  4675. * @returns {Node}
  4676. */
  4677. const exp = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4678. /**
  4679. * Returns 2 raised to the power of the parameter.
  4680. *
  4681. * @tsl
  4682. * @function
  4683. * @param {Node | number} x - The parameter.
  4684. * @returns {Node}
  4685. */
  4686. const exp2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4687. /**
  4688. * Returns the natural logarithm of the parameter.
  4689. *
  4690. * @tsl
  4691. * @function
  4692. * @param {Node | number} x - The parameter.
  4693. * @returns {Node}
  4694. */
  4695. const log = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4696. /**
  4697. * Returns the base 2 logarithm of the parameter.
  4698. *
  4699. * @tsl
  4700. * @function
  4701. * @param {Node | number} x - The parameter.
  4702. * @returns {Node}
  4703. */
  4704. const log2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4705. /**
  4706. * Returns the square root of the parameter.
  4707. *
  4708. * @tsl
  4709. * @function
  4710. * @param {Node | number} x - The parameter.
  4711. * @returns {Node}
  4712. */
  4713. const sqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4714. /**
  4715. * Returns the inverse of the square root of the parameter.
  4716. *
  4717. * @tsl
  4718. * @function
  4719. * @param {Node | number} x - The parameter.
  4720. * @returns {Node}
  4721. */
  4722. const inverseSqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4723. /**
  4724. * Finds the nearest integer less than or equal to the parameter.
  4725. *
  4726. * @tsl
  4727. * @function
  4728. * @param {Node | number} x - The parameter.
  4729. * @returns {Node}
  4730. */
  4731. const floor = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4732. /**
  4733. * Finds the nearest integer that is greater than or equal to the parameter.
  4734. *
  4735. * @tsl
  4736. * @function
  4737. * @param {Node | number} x - The parameter.
  4738. * @returns {Node}
  4739. */
  4740. const ceil = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4741. /**
  4742. * Calculates the unit vector in the same direction as the original vector.
  4743. *
  4744. * @tsl
  4745. * @function
  4746. * @param {Node} x - The input vector.
  4747. * @returns {Node}
  4748. */
  4749. const normalize = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4750. /**
  4751. * Computes the fractional part of the parameter.
  4752. *
  4753. * @tsl
  4754. * @function
  4755. * @param {Node | number} x - The parameter.
  4756. * @returns {Node}
  4757. */
  4758. const fract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4759. /**
  4760. * Returns the sine of the parameter.
  4761. *
  4762. * @tsl
  4763. * @function
  4764. * @param {Node | number} x - The parameter.
  4765. * @returns {Node}
  4766. */
  4767. const sin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4768. /**
  4769. * Returns the cosine of the parameter.
  4770. *
  4771. * @tsl
  4772. * @function
  4773. * @param {Node | number} x - The parameter.
  4774. * @returns {Node}
  4775. */
  4776. const cos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COS ).setParameterLength( 1 );
  4777. /**
  4778. * Returns the tangent of the parameter.
  4779. *
  4780. * @tsl
  4781. * @function
  4782. * @param {Node | number} x - The parameter.
  4783. * @returns {Node}
  4784. */
  4785. const tan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4786. /**
  4787. * Returns the arcsine of the parameter.
  4788. *
  4789. * @tsl
  4790. * @function
  4791. * @param {Node | number} x - The parameter.
  4792. * @returns {Node}
  4793. */
  4794. const asin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4795. /**
  4796. * Returns the arccosine of the parameter.
  4797. *
  4798. * @tsl
  4799. * @function
  4800. * @param {Node | number} x - The parameter.
  4801. * @returns {Node}
  4802. */
  4803. const acos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4804. /**
  4805. * Returns the arc-tangent of the parameter.
  4806. * If two parameters are provided, the result is `atan2(y/x)`.
  4807. *
  4808. * @tsl
  4809. * @function
  4810. * @param {Node | number} y - The y parameter.
  4811. * @param {?(Node | number)} x - The x parameter.
  4812. * @returns {Node}
  4813. */
  4814. const atan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4815. /**
  4816. * Returns the absolute value of the parameter.
  4817. *
  4818. * @tsl
  4819. * @function
  4820. * @param {Node | number} x - The parameter.
  4821. * @returns {Node}
  4822. */
  4823. const abs = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4824. /**
  4825. * Extracts the sign of the parameter.
  4826. *
  4827. * @tsl
  4828. * @function
  4829. * @param {Node | number} x - The parameter.
  4830. * @returns {Node}
  4831. */
  4832. const sign = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4833. /**
  4834. * Calculates the length of a vector.
  4835. *
  4836. * @tsl
  4837. * @function
  4838. * @param {Node} x - The parameter.
  4839. * @returns {Node<float>}
  4840. */
  4841. const length = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4842. /**
  4843. * Negates the value of the parameter (-x).
  4844. *
  4845. * @tsl
  4846. * @function
  4847. * @param {Node | number} x - The parameter.
  4848. * @returns {Node}
  4849. */
  4850. const negate = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4851. /**
  4852. * Return `1` minus the parameter.
  4853. *
  4854. * @tsl
  4855. * @function
  4856. * @param {Node | number} x - The parameter.
  4857. * @returns {Node}
  4858. */
  4859. const oneMinus = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4860. /**
  4861. * Returns the partial derivative of the parameter with respect to x.
  4862. *
  4863. * @tsl
  4864. * @function
  4865. * @param {Node | number} x - The parameter.
  4866. * @returns {Node}
  4867. */
  4868. const dFdx = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4869. /**
  4870. * Returns the partial derivative of the parameter with respect to y.
  4871. *
  4872. * @tsl
  4873. * @function
  4874. * @param {Node | number} x - The parameter.
  4875. * @returns {Node}
  4876. */
  4877. const dFdy = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4878. /**
  4879. * Rounds the parameter to the nearest integer.
  4880. *
  4881. * @tsl
  4882. * @function
  4883. * @param {Node | number} x - The parameter.
  4884. * @returns {Node}
  4885. */
  4886. const round = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4887. /**
  4888. * Returns the reciprocal of the parameter `(1/x)`.
  4889. *
  4890. * @tsl
  4891. * @function
  4892. * @param {Node | number} x - The parameter.
  4893. * @returns {Node}
  4894. */
  4895. const reciprocal = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4896. /**
  4897. * Truncates the parameter, removing the fractional part.
  4898. *
  4899. * @tsl
  4900. * @function
  4901. * @param {Node | number} x - The parameter.
  4902. * @returns {Node}
  4903. */
  4904. const trunc = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4905. /**
  4906. * Returns the sum of the absolute derivatives in x and y.
  4907. *
  4908. * @tsl
  4909. * @function
  4910. * @param {Node | number} x - The parameter.
  4911. * @returns {Node}
  4912. */
  4913. const fwidth = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4914. /**
  4915. * Returns the transpose of a matrix.
  4916. *
  4917. * @tsl
  4918. * @function
  4919. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4920. * @returns {Node}
  4921. */
  4922. const transpose = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4923. /**
  4924. * Returns the determinant of a matrix.
  4925. *
  4926. * @tsl
  4927. * @function
  4928. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4929. * @returns {Node<float>}
  4930. */
  4931. const determinant = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DETERMINANT ).setParameterLength( 1 );
  4932. /**
  4933. * Returns the inverse of a matrix.
  4934. *
  4935. * @tsl
  4936. * @function
  4937. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4938. * @returns {Node<mat2|mat3|mat4>}
  4939. */
  4940. const inverse = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE ).setParameterLength( 1 );
  4941. // 2 inputs
  4942. /**
  4943. * Returns `true` if `x` equals `y`.
  4944. *
  4945. * @tsl
  4946. * @function
  4947. * @param {Node | number} x - The first parameter.
  4948. * @param {Node | number} y - The second parameter.
  4949. * @deprecated since r175. Use {@link equal} instead.
  4950. * @returns {Node<bool>}
  4951. */
  4952. const equals = ( x, y ) => { // @deprecated, r172
  4953. warn( 'TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"' );
  4954. return equal( x, y );
  4955. };
  4956. /**
  4957. * Returns the least of the given values.
  4958. *
  4959. * @tsl
  4960. * @function
  4961. * @param {...(Node | number)} values - The values to compare.
  4962. * @returns {Node}
  4963. */
  4964. const min$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  4965. /**
  4966. * Returns the greatest of the given values.
  4967. *
  4968. * @tsl
  4969. * @function
  4970. * @param {...(Node | number)} values - The values to compare.
  4971. * @returns {Node}
  4972. */
  4973. const max$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  4974. /**
  4975. * Generate a step function by comparing two values.
  4976. *
  4977. * @tsl
  4978. * @function
  4979. * @param {Node | number} x - The y parameter.
  4980. * @param {Node | number} y - The x parameter.
  4981. * @returns {Node}
  4982. */
  4983. const step = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.STEP ).setParameterLength( 2 );
  4984. /**
  4985. * Calculates the reflection direction for an incident vector.
  4986. *
  4987. * @tsl
  4988. * @function
  4989. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4990. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4991. * @returns {Node<vec2|vec3|vec4>}
  4992. */
  4993. const reflect = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  4994. /**
  4995. * Calculates the distance between two points.
  4996. *
  4997. * @tsl
  4998. * @function
  4999. * @param {Node<vec2|vec3|vec4>} x - The first point.
  5000. * @param {Node<vec2|vec3|vec4>} y - The second point.
  5001. * @returns {Node<float>}
  5002. */
  5003. const distance = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  5004. /**
  5005. * Calculates the absolute difference between two values.
  5006. *
  5007. * @tsl
  5008. * @function
  5009. * @param {Node | number} x - The first parameter.
  5010. * @param {Node | number} y - The second parameter.
  5011. * @returns {Node}
  5012. */
  5013. const difference = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  5014. /**
  5015. * Calculates the dot product of two vectors.
  5016. *
  5017. * @tsl
  5018. * @function
  5019. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  5020. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  5021. * @returns {Node<float>}
  5022. */
  5023. const dot = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DOT ).setParameterLength( 2 );
  5024. /**
  5025. * Calculates the cross product of two vectors.
  5026. *
  5027. * @tsl
  5028. * @function
  5029. * @param {Node<vec2|vec3>} x - The first vector.
  5030. * @param {Node<vec2|vec3>} y - The second vector.
  5031. * @returns {Node<float|vec3>}
  5032. */
  5033. const cross = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  5034. /**
  5035. * Return the value of the first parameter raised to the power of the second one.
  5036. *
  5037. * @tsl
  5038. * @function
  5039. * @param {Node | number} x - The first parameter.
  5040. * @param {Node | number} y - The second parameter.
  5041. * @returns {Node}
  5042. */
  5043. const pow = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW ).setParameterLength( 2 );
  5044. /**
  5045. * Returns the square of the parameter.
  5046. *
  5047. * @tsl
  5048. * @function
  5049. * @param {Node | number} x - The first parameter.
  5050. * @returns {Node}
  5051. */
  5052. const pow2 = ( x ) => mul( x, x );
  5053. /**
  5054. * Returns the cube of the parameter.
  5055. *
  5056. * @tsl
  5057. * @function
  5058. * @param {Node | number} x - The first parameter.
  5059. * @returns {Node}
  5060. */
  5061. const pow3 = ( x ) => mul( x, x, x );
  5062. /**
  5063. * Returns the fourth power of the parameter.
  5064. *
  5065. * @tsl
  5066. * @function
  5067. * @param {Node | number} x - The first parameter.
  5068. * @returns {Node}
  5069. */
  5070. const pow4 = ( x ) => mul( x, x, x, x );
  5071. /**
  5072. * Transforms the direction of a vector by a matrix and then normalizes the result.
  5073. *
  5074. * @tsl
  5075. * @function
  5076. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  5077. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  5078. * @returns {Node}
  5079. */
  5080. const transformDirection = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  5081. /**
  5082. * Returns the cube root of a number.
  5083. *
  5084. * @tsl
  5085. * @function
  5086. * @param {Node | number} a - The first parameter.
  5087. * @returns {Node}
  5088. */
  5089. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  5090. /**
  5091. * Calculate the squared length of a vector.
  5092. *
  5093. * @tsl
  5094. * @function
  5095. * @param {Node<vec2|vec3|vec4>} a - The vector.
  5096. * @returns {Node<float>}
  5097. */
  5098. const lengthSq = ( a ) => dot( a, a );
  5099. /**
  5100. * Linearly interpolates between two values.
  5101. *
  5102. * @tsl
  5103. * @function
  5104. * @param {Node | number} a - The first parameter.
  5105. * @param {Node | number} b - The second parameter.
  5106. * @param {Node | number} t - The interpolation value.
  5107. * @returns {Node}
  5108. */
  5109. const mix = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIX ).setParameterLength( 3 );
  5110. /**
  5111. * Constrains a value to lie between two further values.
  5112. *
  5113. * @tsl
  5114. * @function
  5115. * @param {Node | number} value - The value to constrain.
  5116. * @param {Node | number} [low=0] - The lower bound.
  5117. * @param {Node | number} [high=1] - The upper bound.
  5118. * @returns {Node}
  5119. */
  5120. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  5121. /**
  5122. * Constrains a value between `0` and `1`.
  5123. *
  5124. * @tsl
  5125. * @function
  5126. * @param {Node | number} value - The value to constrain.
  5127. * @returns {Node}
  5128. */
  5129. const saturate = ( value ) => clamp( value );
  5130. /**
  5131. * Calculates the refraction direction for an incident vector.
  5132. *
  5133. * @tsl
  5134. * @function
  5135. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5136. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5137. * @param {Node<float>} eta - The ratio of indices of refraction.
  5138. * @returns {Node<vec2|vec3|vec4>}
  5139. */
  5140. const refract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  5141. /**
  5142. * Performs a Hermite interpolation between two values.
  5143. *
  5144. * @tsl
  5145. * @function
  5146. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5147. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5148. * @param {Node | number} x - The source value for interpolation.
  5149. * @returns {Node}
  5150. */
  5151. const smoothstep = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  5152. /**
  5153. * Returns a vector pointing in the same direction as another.
  5154. *
  5155. * @tsl
  5156. * @function
  5157. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  5158. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5159. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  5160. * @returns {Node<vec2|vec3|vec4>}
  5161. */
  5162. const faceForward = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  5163. /**
  5164. * Returns a random value for the given uv.
  5165. *
  5166. * @tsl
  5167. * @function
  5168. * @param {Node<vec2>} uv - The uv node.
  5169. * @returns {Node<float>}
  5170. */
  5171. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  5172. const a = 12.9898, b = 78.233, c = 43758.5453;
  5173. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  5174. return fract( sin( sn ).mul( c ) );
  5175. } );
  5176. /**
  5177. * Alias for `mix()` with a different parameter order.
  5178. *
  5179. * @tsl
  5180. * @function
  5181. * @param {Node | number} t - The interpolation value.
  5182. * @param {Node | number} e1 - The first parameter.
  5183. * @param {Node | number} e2 - The second parameter.
  5184. * @returns {Node}
  5185. */
  5186. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  5187. /**
  5188. * Alias for `smoothstep()` with a different parameter order.
  5189. *
  5190. * @tsl
  5191. * @function
  5192. * @param {Node | number} x - The source value for interpolation.
  5193. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5194. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5195. * @returns {Node}
  5196. */
  5197. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  5198. /**
  5199. * Alias for `step()` with a different parameter order.
  5200. *
  5201. * @tsl
  5202. * @function
  5203. * @param {Node | number} x - The source value for interpolation.
  5204. * @param {Node | number} edge - The edge value.
  5205. * @returns {Node}
  5206. */
  5207. const stepElement = ( x, edge ) => step( edge, x );
  5208. /**
  5209. * Returns the arc-tangent of the quotient of its parameters.
  5210. *
  5211. * @tsl
  5212. * @function
  5213. * @deprecated since r172. Use {@link atan} instead.
  5214. *
  5215. * @param {Node | number} y - The y parameter.
  5216. * @param {Node | number} x - The x parameter.
  5217. * @returns {Node}
  5218. */
  5219. const atan2 = ( y, x ) => { // @deprecated, r172
  5220. warn( 'TSL: "atan2" is overloaded. Use "atan" instead.' );
  5221. return atan( y, x );
  5222. };
  5223. // GLSL alias function
  5224. const faceforward = faceForward;
  5225. const inversesqrt = inverseSqrt;
  5226. // Method chaining
  5227. addMethodChaining( 'all', all );
  5228. addMethodChaining( 'any', any );
  5229. addMethodChaining( 'equals', equals );
  5230. addMethodChaining( 'radians', radians );
  5231. addMethodChaining( 'degrees', degrees );
  5232. addMethodChaining( 'exp', exp );
  5233. addMethodChaining( 'exp2', exp2 );
  5234. addMethodChaining( 'log', log );
  5235. addMethodChaining( 'log2', log2 );
  5236. addMethodChaining( 'sqrt', sqrt );
  5237. addMethodChaining( 'inverseSqrt', inverseSqrt );
  5238. addMethodChaining( 'floor', floor );
  5239. addMethodChaining( 'ceil', ceil );
  5240. addMethodChaining( 'normalize', normalize );
  5241. addMethodChaining( 'fract', fract );
  5242. addMethodChaining( 'sin', sin );
  5243. addMethodChaining( 'cos', cos );
  5244. addMethodChaining( 'tan', tan );
  5245. addMethodChaining( 'asin', asin );
  5246. addMethodChaining( 'acos', acos );
  5247. addMethodChaining( 'atan', atan );
  5248. addMethodChaining( 'abs', abs );
  5249. addMethodChaining( 'sign', sign );
  5250. addMethodChaining( 'length', length );
  5251. addMethodChaining( 'lengthSq', lengthSq );
  5252. addMethodChaining( 'negate', negate );
  5253. addMethodChaining( 'oneMinus', oneMinus );
  5254. addMethodChaining( 'dFdx', dFdx );
  5255. addMethodChaining( 'dFdy', dFdy );
  5256. addMethodChaining( 'round', round );
  5257. addMethodChaining( 'reciprocal', reciprocal );
  5258. addMethodChaining( 'trunc', trunc );
  5259. addMethodChaining( 'fwidth', fwidth );
  5260. addMethodChaining( 'atan2', atan2 );
  5261. addMethodChaining( 'min', min$1 );
  5262. addMethodChaining( 'max', max$1 );
  5263. addMethodChaining( 'step', stepElement );
  5264. addMethodChaining( 'reflect', reflect );
  5265. addMethodChaining( 'distance', distance );
  5266. addMethodChaining( 'dot', dot );
  5267. addMethodChaining( 'cross', cross );
  5268. addMethodChaining( 'pow', pow );
  5269. addMethodChaining( 'pow2', pow2 );
  5270. addMethodChaining( 'pow3', pow3 );
  5271. addMethodChaining( 'pow4', pow4 );
  5272. addMethodChaining( 'transformDirection', transformDirection );
  5273. addMethodChaining( 'mix', mixElement );
  5274. addMethodChaining( 'clamp', clamp );
  5275. addMethodChaining( 'refract', refract );
  5276. addMethodChaining( 'smoothstep', smoothstepElement );
  5277. addMethodChaining( 'faceForward', faceForward );
  5278. addMethodChaining( 'difference', difference );
  5279. addMethodChaining( 'saturate', saturate );
  5280. addMethodChaining( 'cbrt', cbrt );
  5281. addMethodChaining( 'transpose', transpose );
  5282. addMethodChaining( 'determinant', determinant );
  5283. addMethodChaining( 'inverse', inverse );
  5284. addMethodChaining( 'rand', rand );
  5285. /**
  5286. * Represents a logical `if/else` statement. Can be used as an alternative
  5287. * to the `If()`/`Else()` syntax.
  5288. *
  5289. * The corresponding TSL `select()` looks like so:
  5290. * ```js
  5291. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  5292. * ```
  5293. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  5294. * determine the outcome of the entire statement.
  5295. *
  5296. * @augments Node
  5297. */
  5298. class ConditionalNode extends Node {
  5299. static get type() {
  5300. return 'ConditionalNode';
  5301. }
  5302. /**
  5303. * Constructs a new conditional node.
  5304. *
  5305. * @param {Node} condNode - The node that defines the condition.
  5306. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5307. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5308. */
  5309. constructor( condNode, ifNode, elseNode = null ) {
  5310. super();
  5311. /**
  5312. * The node that defines the condition.
  5313. *
  5314. * @type {Node}
  5315. */
  5316. this.condNode = condNode;
  5317. /**
  5318. * The node that is evaluate when the condition ends up `true`.
  5319. *
  5320. * @type {Node}
  5321. */
  5322. this.ifNode = ifNode;
  5323. /**
  5324. * The node that is evaluate when the condition ends up `false`.
  5325. *
  5326. * @type {?Node}
  5327. * @default null
  5328. */
  5329. this.elseNode = elseNode;
  5330. }
  5331. /**
  5332. * This method is overwritten since the node type is inferred from the if/else
  5333. * nodes.
  5334. *
  5335. * @param {NodeBuilder} builder - The current node builder.
  5336. * @return {string} The node type.
  5337. */
  5338. getNodeType( builder ) {
  5339. const { ifNode, elseNode } = builder.getNodeProperties( this );
  5340. if ( ifNode === undefined ) {
  5341. // fallback setup
  5342. builder.flowBuildStage( this, 'setup' );
  5343. return this.getNodeType( builder );
  5344. }
  5345. const ifType = ifNode.getNodeType( builder );
  5346. if ( elseNode !== null ) {
  5347. const elseType = elseNode.getNodeType( builder );
  5348. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5349. return elseType;
  5350. }
  5351. }
  5352. return ifType;
  5353. }
  5354. setup( builder ) {
  5355. const condNode = this.condNode;
  5356. const ifNode = this.ifNode.isolate();
  5357. const elseNode = this.elseNode ? this.elseNode.isolate() : null;
  5358. //
  5359. const currentNodeBlock = builder.context.nodeBlock;
  5360. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5361. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5362. //
  5363. const isUniformFlow = builder.context.uniformFlow;
  5364. const properties = builder.getNodeProperties( this );
  5365. properties.condNode = condNode;
  5366. properties.ifNode = isUniformFlow ? ifNode : ifNode.context( { nodeBlock: ifNode } );
  5367. properties.elseNode = elseNode ? ( isUniformFlow ? elseNode : elseNode.context( { nodeBlock: elseNode } ) ) : null;
  5368. }
  5369. generate( builder, output ) {
  5370. const type = this.getNodeType( builder );
  5371. const nodeData = builder.getDataFromNode( this );
  5372. if ( nodeData.nodeProperty !== undefined ) {
  5373. return nodeData.nodeProperty;
  5374. }
  5375. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5376. const functionNode = builder.currentFunctionNode;
  5377. const needsOutput = output !== 'void';
  5378. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5379. nodeData.nodeProperty = nodeProperty;
  5380. const nodeSnippet = condNode.build( builder, 'bool' );
  5381. const isUniformFlow = builder.context.uniformFlow;
  5382. if ( isUniformFlow && elseNode !== null ) {
  5383. const ifSnippet = ifNode.build( builder, type );
  5384. const elseSnippet = elseNode.build( builder, type );
  5385. const mathSnippet = builder.getTernary( nodeSnippet, ifSnippet, elseSnippet );
  5386. // TODO: If node property already exists return something else
  5387. return builder.format( mathSnippet, type, output );
  5388. }
  5389. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5390. let ifSnippet = ifNode.build( builder, type );
  5391. if ( ifSnippet ) {
  5392. if ( needsOutput ) {
  5393. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5394. } else {
  5395. ifSnippet = 'return ' + ifSnippet + ';';
  5396. if ( functionNode === null ) {
  5397. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5398. ifSnippet = '// ' + ifSnippet;
  5399. }
  5400. }
  5401. }
  5402. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5403. if ( elseNode !== null ) {
  5404. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5405. let elseSnippet = elseNode.build( builder, type );
  5406. if ( elseSnippet ) {
  5407. if ( needsOutput ) {
  5408. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5409. } else {
  5410. elseSnippet = 'return ' + elseSnippet + ';';
  5411. if ( functionNode === null ) {
  5412. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5413. elseSnippet = '// ' + elseSnippet;
  5414. }
  5415. }
  5416. }
  5417. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5418. } else {
  5419. builder.addFlowCode( '\n\n' );
  5420. }
  5421. return builder.format( nodeProperty, type, output );
  5422. }
  5423. }
  5424. /**
  5425. * TSL function for creating a conditional node.
  5426. *
  5427. * @tsl
  5428. * @function
  5429. * @param {Node} condNode - The node that defines the condition.
  5430. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5431. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5432. * @returns {ConditionalNode}
  5433. */
  5434. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5435. addMethodChaining( 'select', select );
  5436. /**
  5437. * This node can be used as a context management component for another node.
  5438. * {@link NodeBuilder} performs its node building process in a specific context and
  5439. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5440. *
  5441. * ```js
  5442. *node.context( { getUV: () => customCoord } );
  5443. *```
  5444. * @augments Node
  5445. */
  5446. class ContextNode extends Node {
  5447. static get type() {
  5448. return 'ContextNode';
  5449. }
  5450. /**
  5451. * Constructs a new context node.
  5452. *
  5453. * @param {Node} node - The node whose context should be modified.
  5454. * @param {Object} [value={}] - The modified context data.
  5455. */
  5456. constructor( node, value = {} ) {
  5457. super();
  5458. /**
  5459. * This flag can be used for type testing.
  5460. *
  5461. * @type {boolean}
  5462. * @readonly
  5463. * @default true
  5464. */
  5465. this.isContextNode = true;
  5466. /**
  5467. * The node whose context should be modified.
  5468. *
  5469. * @type {Node}
  5470. */
  5471. this.node = node;
  5472. /**
  5473. * The modified context data.
  5474. *
  5475. * @type {Object}
  5476. * @default {}
  5477. */
  5478. this.value = value;
  5479. }
  5480. /**
  5481. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5482. *
  5483. * @return {Node} A reference to {@link ContextNode#node}.
  5484. */
  5485. getScope() {
  5486. return this.node.getScope();
  5487. }
  5488. /**
  5489. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5490. *
  5491. * @param {NodeBuilder} builder - The current node builder.
  5492. * @return {string} The node type.
  5493. */
  5494. getNodeType( builder ) {
  5495. return this.node.getNodeType( builder );
  5496. }
  5497. /**
  5498. * This method is overwritten to ensure it returns the member type of {@link ContextNode#node}.
  5499. *
  5500. * @param {NodeBuilder} builder - The current node builder.
  5501. * @param {string} name - The member name.
  5502. * @returns {string} The member type.
  5503. */
  5504. getMemberType( builder, name ) {
  5505. return this.node.getMemberType( builder, name );
  5506. }
  5507. analyze( builder ) {
  5508. const previousContext = builder.addContext( this.value );
  5509. this.node.build( builder );
  5510. builder.setContext( previousContext );
  5511. }
  5512. setup( builder ) {
  5513. const previousContext = builder.addContext( this.value );
  5514. this.node.build( builder );
  5515. builder.setContext( previousContext );
  5516. }
  5517. generate( builder, output ) {
  5518. const previousContext = builder.addContext( this.value );
  5519. const snippet = this.node.build( builder, output );
  5520. builder.setContext( previousContext );
  5521. return snippet;
  5522. }
  5523. }
  5524. /**
  5525. * TSL function for creating a context node.
  5526. *
  5527. * @tsl
  5528. * @function
  5529. * @param {Node} node - The node whose context should be modified.
  5530. * @param {Object} [value={}] - The modified context data.
  5531. * @returns {ContextNode}
  5532. */
  5533. const context = /*@__PURE__*/ nodeProxy( ContextNode ).setParameterLength( 1, 2 );
  5534. /**
  5535. * TSL function for defining a uniformFlow context value for a given node.
  5536. *
  5537. * @tsl
  5538. * @function
  5539. * @param {Node} node - The node whose dependencies should all execute within a uniform control-flow path.
  5540. * @returns {ContextNode}
  5541. */
  5542. const uniformFlow = ( node ) => context( node, { uniformFlow: true } );
  5543. /**
  5544. * TSL function for defining a name for the context value for a given node.
  5545. *
  5546. * @tsl
  5547. * @function
  5548. * @param {Node} node - The node whose context should be modified.
  5549. * @param {string} name - The name to set.
  5550. * @returns {ContextNode}
  5551. */
  5552. const setName = ( node, name ) => context( node, { nodeName: name } );
  5553. /**
  5554. * TSL function for defining a label context value for a given node.
  5555. *
  5556. * @tsl
  5557. * @function
  5558. * @deprecated
  5559. * @param {Node} node - The node whose context should be modified.
  5560. * @param {string} name - The name/label to set.
  5561. * @returns {ContextNode}
  5562. */
  5563. function label( node, name ) {
  5564. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  5565. return setName( node, name );
  5566. }
  5567. addMethodChaining( 'context', context );
  5568. addMethodChaining( 'label', label );
  5569. addMethodChaining( 'uniformFlow', uniformFlow );
  5570. addMethodChaining( 'setName', setName );
  5571. /**
  5572. * Class for representing shader variables as nodes. Variables are created from
  5573. * existing nodes like the following:
  5574. *
  5575. * ```js
  5576. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5577. * ```
  5578. *
  5579. * @augments Node
  5580. */
  5581. class VarNode extends Node {
  5582. static get type() {
  5583. return 'VarNode';
  5584. }
  5585. /**
  5586. * Constructs a new variable node.
  5587. *
  5588. * @param {Node} node - The node for which a variable should be created.
  5589. * @param {?string} [name=null] - The name of the variable in the shader.
  5590. * @param {boolean} [readOnly=false] - The read-only flag.
  5591. */
  5592. constructor( node, name = null, readOnly = false ) {
  5593. super();
  5594. /**
  5595. * The node for which a variable should be created.
  5596. *
  5597. * @type {Node}
  5598. */
  5599. this.node = node;
  5600. /**
  5601. * The name of the variable in the shader. If no name is defined,
  5602. * the node system auto-generates one.
  5603. *
  5604. * @type {?string}
  5605. * @default null
  5606. */
  5607. this.name = name;
  5608. /**
  5609. * `VarNode` sets this property to `true` by default.
  5610. *
  5611. * @type {boolean}
  5612. * @default true
  5613. */
  5614. this.global = true;
  5615. /**
  5616. * This flag can be used for type testing.
  5617. *
  5618. * @type {boolean}
  5619. * @readonly
  5620. * @default true
  5621. */
  5622. this.isVarNode = true;
  5623. /**
  5624. *
  5625. * The read-only flag.
  5626. *
  5627. * @type {boolean}
  5628. * @default false
  5629. */
  5630. this.readOnly = readOnly;
  5631. /**
  5632. *
  5633. * Add this flag to the node system to indicate that this node require parents.
  5634. *
  5635. * @type {boolean}
  5636. * @default true
  5637. */
  5638. this.parents = true;
  5639. /**
  5640. * This flag is used to indicate that this node is used for intent.
  5641. *
  5642. * @type {boolean}
  5643. * @default false
  5644. */
  5645. this.intent = false;
  5646. }
  5647. /**
  5648. * Sets the intent flag for this node.
  5649. *
  5650. * This flag is used to indicate that this node is used for intent
  5651. * and should not be built directly. Instead, it is used to indicate that
  5652. * the node should be treated as a variable intent.
  5653. *
  5654. * It's useful for assigning variables without needing creating a new variable node.
  5655. *
  5656. * @param {boolean} value - The value to set for the intent flag.
  5657. * @returns {VarNode} This node.
  5658. */
  5659. setIntent( value ) {
  5660. this.intent = value;
  5661. return this;
  5662. }
  5663. /**
  5664. * Returns the intent flag of this node.
  5665. *
  5666. * @return {boolean} The intent flag.
  5667. */
  5668. getIntent() {
  5669. return this.intent;
  5670. }
  5671. getMemberType( builder, name ) {
  5672. return this.node.getMemberType( builder, name );
  5673. }
  5674. getElementType( builder ) {
  5675. return this.node.getElementType( builder );
  5676. }
  5677. getNodeType( builder ) {
  5678. return this.node.getNodeType( builder );
  5679. }
  5680. getArrayCount( builder ) {
  5681. return this.node.getArrayCount( builder );
  5682. }
  5683. isAssign( builder ) {
  5684. const properties = builder.getNodeProperties( this );
  5685. let assign = properties.assign;
  5686. if ( assign !== true ) {
  5687. if ( this.node.isShaderCallNodeInternal && this.node.shaderNode.getLayout() === null ) {
  5688. if ( builder.fnCall && builder.fnCall.shaderNode ) {
  5689. const shaderNodeData = builder.getDataFromNode( this.node.shaderNode );
  5690. if ( shaderNodeData.hasLoop ) {
  5691. assign = true;
  5692. }
  5693. }
  5694. }
  5695. }
  5696. return assign;
  5697. }
  5698. build( ...params ) {
  5699. const builder = params[ 0 ];
  5700. if ( this._hasStack( builder ) === false && builder.buildStage === 'setup' ) {
  5701. if ( builder.context.nodeLoop || builder.context.nodeBlock ) {
  5702. builder.getBaseStack().addToStack( this );
  5703. }
  5704. }
  5705. if ( this.intent === true ) {
  5706. if ( this.isAssign( builder ) !== true ) {
  5707. return this.node.build( ...params );
  5708. }
  5709. }
  5710. return super.build( ...params );
  5711. }
  5712. generate( builder ) {
  5713. const { node, name, readOnly } = this;
  5714. const { renderer } = builder;
  5715. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5716. let isDeterministic = false;
  5717. let shouldTreatAsReadOnly = false;
  5718. if ( readOnly ) {
  5719. isDeterministic = builder.isDeterministic( node );
  5720. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5721. }
  5722. const nodeType = this.getNodeType( builder );
  5723. if ( nodeType == 'void' ) {
  5724. if ( this.intent !== true ) {
  5725. error( 'TSL: ".toVar()" can not be used with void type.' );
  5726. }
  5727. const snippet = node.build( builder );
  5728. return snippet;
  5729. }
  5730. const vectorType = builder.getVectorType( nodeType );
  5731. const snippet = node.build( builder, vectorType );
  5732. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5733. const propertyName = builder.getPropertyName( nodeVar );
  5734. let declarationPrefix = propertyName;
  5735. if ( shouldTreatAsReadOnly ) {
  5736. if ( isWebGPUBackend ) {
  5737. declarationPrefix = isDeterministic
  5738. ? `const ${ propertyName }`
  5739. : `let ${ propertyName }`;
  5740. } else {
  5741. const count = node.getArrayCount( builder );
  5742. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5743. }
  5744. }
  5745. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5746. return propertyName;
  5747. }
  5748. _hasStack( builder ) {
  5749. const nodeData = builder.getDataFromNode( this );
  5750. return nodeData.stack !== undefined;
  5751. }
  5752. }
  5753. /**
  5754. * TSL function for creating a var node.
  5755. *
  5756. * @tsl
  5757. * @function
  5758. * @param {Node} node - The node for which a variable should be created.
  5759. * @param {?string} name - The name of the variable in the shader.
  5760. * @returns {VarNode}
  5761. */
  5762. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5763. /**
  5764. * TSL function for creating a var node.
  5765. *
  5766. * @tsl
  5767. * @function
  5768. * @param {Node} node - The node for which a variable should be created.
  5769. * @param {?string} name - The name of the variable in the shader.
  5770. * @returns {VarNode}
  5771. */
  5772. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5773. /**
  5774. * TSL function for creating a const node.
  5775. *
  5776. * @tsl
  5777. * @function
  5778. * @param {Node} node - The node for which a constant should be created.
  5779. * @param {?string} name - The name of the constant in the shader.
  5780. * @returns {VarNode}
  5781. */
  5782. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5783. //
  5784. //
  5785. /**
  5786. * TSL function for creating a var intent node.
  5787. *
  5788. * @tsl
  5789. * @function
  5790. * @param {Node} node - The node for which a variable should be created.
  5791. * @param {?string} name - The name of the variable in the shader.
  5792. * @returns {VarNode}
  5793. */
  5794. const VarIntent = ( node ) => {
  5795. return createVar( node ).setIntent( true ).toStack();
  5796. };
  5797. // Method chaining
  5798. addMethodChaining( 'toVar', Var );
  5799. addMethodChaining( 'toConst', Const );
  5800. addMethodChaining( 'toVarIntent', VarIntent );
  5801. /**
  5802. * This node is used to build a sub-build in the node system.
  5803. *
  5804. * @augments Node
  5805. * @param {Node} node - The node to be built in the sub-build.
  5806. * @param {string} name - The name of the sub-build.
  5807. * @param {?string} [nodeType=null] - The type of the node, if known.
  5808. */
  5809. class SubBuildNode extends Node {
  5810. static get type() {
  5811. return 'SubBuild';
  5812. }
  5813. constructor( node, name, nodeType = null ) {
  5814. super( nodeType );
  5815. /**
  5816. * The node to be built in the sub-build.
  5817. *
  5818. * @type {Node}
  5819. */
  5820. this.node = node;
  5821. /**
  5822. * The name of the sub-build.
  5823. *
  5824. * @type {string}
  5825. */
  5826. this.name = name;
  5827. /**
  5828. * This flag can be used for type testing.
  5829. *
  5830. * @type {boolean}
  5831. * @readonly
  5832. * @default true
  5833. */
  5834. this.isSubBuildNode = true;
  5835. }
  5836. getNodeType( builder ) {
  5837. if ( this.nodeType !== null ) return this.nodeType;
  5838. builder.addSubBuild( this.name );
  5839. const nodeType = this.node.getNodeType( builder );
  5840. builder.removeSubBuild();
  5841. return nodeType;
  5842. }
  5843. build( builder, ...params ) {
  5844. builder.addSubBuild( this.name );
  5845. const data = this.node.build( builder, ...params );
  5846. builder.removeSubBuild();
  5847. return data;
  5848. }
  5849. }
  5850. /**
  5851. * Creates a new sub-build node.
  5852. *
  5853. * @tsl
  5854. * @function
  5855. * @param {Node} node - The node to be built in the sub-build.
  5856. * @param {string} name - The name of the sub-build.
  5857. * @param {?string} [type=null] - The type of the node, if known.
  5858. * @returns {Node} A node object wrapping the SubBuildNode instance.
  5859. */
  5860. const subBuild = ( node, name, type = null ) => nodeObject( new SubBuildNode( nodeObject( node ), name, type ) );
  5861. /**
  5862. * Class for representing shader varyings as nodes. Varyings are create from
  5863. * existing nodes like the following:
  5864. *
  5865. * ```js
  5866. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5867. * ```
  5868. *
  5869. * @augments Node
  5870. */
  5871. class VaryingNode extends Node {
  5872. static get type() {
  5873. return 'VaryingNode';
  5874. }
  5875. /**
  5876. * Constructs a new varying node.
  5877. *
  5878. * @param {Node} node - The node for which a varying should be created.
  5879. * @param {?string} name - The name of the varying in the shader.
  5880. */
  5881. constructor( node, name = null ) {
  5882. super();
  5883. /**
  5884. * The node for which a varying should be created.
  5885. *
  5886. * @type {Node}
  5887. */
  5888. this.node = node;
  5889. /**
  5890. * The name of the varying in the shader. If no name is defined,
  5891. * the node system auto-generates one.
  5892. *
  5893. * @type {?string}
  5894. * @default null
  5895. */
  5896. this.name = name;
  5897. /**
  5898. * This flag can be used for type testing.
  5899. *
  5900. * @type {boolean}
  5901. * @readonly
  5902. * @default true
  5903. */
  5904. this.isVaryingNode = true;
  5905. /**
  5906. * The interpolation type of the varying data.
  5907. *
  5908. * @type {?string}
  5909. * @default null
  5910. */
  5911. this.interpolationType = null;
  5912. /**
  5913. * The interpolation sampling type of varying data.
  5914. *
  5915. * @type {?string}
  5916. * @default null
  5917. */
  5918. this.interpolationSampling = null;
  5919. /**
  5920. * This flag is used for global cache.
  5921. *
  5922. * @type {boolean}
  5923. * @default true
  5924. */
  5925. this.global = true;
  5926. }
  5927. /**
  5928. * Defines the interpolation type of the varying.
  5929. *
  5930. * @param {string} type - The interpolation type.
  5931. * @param {?string} sampling - The interpolation sampling type
  5932. * @return {VaryingNode} A reference to this node.
  5933. */
  5934. setInterpolation( type, sampling = null ) {
  5935. this.interpolationType = type;
  5936. this.interpolationSampling = sampling;
  5937. return this;
  5938. }
  5939. getHash( builder ) {
  5940. return this.name || super.getHash( builder );
  5941. }
  5942. getNodeType( builder ) {
  5943. // VaryingNode is auto type
  5944. return this.node.getNodeType( builder );
  5945. }
  5946. /**
  5947. * This method performs the setup of a varying node with the current node builder.
  5948. *
  5949. * @param {NodeBuilder} builder - The current node builder.
  5950. * @return {NodeVarying} The node varying from the node builder.
  5951. */
  5952. setupVarying( builder ) {
  5953. const properties = builder.getNodeProperties( this );
  5954. let varying = properties.varying;
  5955. if ( varying === undefined ) {
  5956. const name = this.name;
  5957. const type = this.getNodeType( builder );
  5958. const interpolationType = this.interpolationType;
  5959. const interpolationSampling = this.interpolationSampling;
  5960. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  5961. properties.node = subBuild( this.node, 'VERTEX' );
  5962. }
  5963. // this property can be used to check if the varying can be optimized for a variable
  5964. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  5965. return varying;
  5966. }
  5967. setup( builder ) {
  5968. this.setupVarying( builder );
  5969. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5970. }
  5971. analyze( builder ) {
  5972. this.setupVarying( builder );
  5973. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5974. }
  5975. generate( builder ) {
  5976. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  5977. const properties = builder.getNodeProperties( this );
  5978. const varying = this.setupVarying( builder );
  5979. if ( properties[ propertyKey ] === undefined ) {
  5980. const type = this.getNodeType( builder );
  5981. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  5982. // force node run in vertex stage
  5983. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  5984. properties[ propertyKey ] = propertyName;
  5985. }
  5986. return builder.getPropertyName( varying );
  5987. }
  5988. }
  5989. /**
  5990. * TSL function for creating a varying node.
  5991. *
  5992. * @tsl
  5993. * @function
  5994. * @param {Node} node - The node for which a varying should be created.
  5995. * @param {?string} name - The name of the varying in the shader.
  5996. * @returns {VaryingNode}
  5997. */
  5998. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  5999. /**
  6000. * Computes a node in the vertex stage.
  6001. *
  6002. * @tsl
  6003. * @function
  6004. * @param {Node} node - The node which should be executed in the vertex stage.
  6005. * @returns {VaryingNode}
  6006. */
  6007. const vertexStage = ( node ) => varying( node );
  6008. addMethodChaining( 'toVarying', varying );
  6009. addMethodChaining( 'toVertexStage', vertexStage );
  6010. // Deprecated
  6011. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  6012. warn( 'TSL: .varying() has been renamed to .toVarying().' );
  6013. return varying( ...params );
  6014. } );
  6015. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  6016. warn( 'TSL: .vertexStage() has been renamed to .toVertexStage().' );
  6017. return varying( ...params );
  6018. } );
  6019. /**
  6020. * Converts the given color value from sRGB to linear-sRGB color space.
  6021. *
  6022. * @tsl
  6023. * @function
  6024. * @param {Node<vec3>} color - The sRGB color.
  6025. * @return {Node<vec3>} The linear-sRGB color.
  6026. */
  6027. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6028. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  6029. const b = color.mul( 0.0773993808 );
  6030. const factor = color.lessThanEqual( 0.04045 );
  6031. const rgbResult = mix( a, b, factor );
  6032. return rgbResult;
  6033. } ).setLayout( {
  6034. name: 'sRGBTransferEOTF',
  6035. type: 'vec3',
  6036. inputs: [
  6037. { name: 'color', type: 'vec3' }
  6038. ]
  6039. } );
  6040. /**
  6041. * Converts the given color value from linear-sRGB to sRGB color space.
  6042. *
  6043. * @tsl
  6044. * @function
  6045. * @param {Node<vec3>} color - The linear-sRGB color.
  6046. * @return {Node<vec3>} The sRGB color.
  6047. */
  6048. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6049. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  6050. const b = color.mul( 12.92 );
  6051. const factor = color.lessThanEqual( 0.0031308 );
  6052. const rgbResult = mix( a, b, factor );
  6053. return rgbResult;
  6054. } ).setLayout( {
  6055. name: 'sRGBTransferOETF',
  6056. type: 'vec3',
  6057. inputs: [
  6058. { name: 'color', type: 'vec3' }
  6059. ]
  6060. } );
  6061. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  6062. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  6063. /**
  6064. * This node represents a color space conversion. Meaning it converts
  6065. * a color value from a source to a target color space.
  6066. *
  6067. * @augments TempNode
  6068. */
  6069. class ColorSpaceNode extends TempNode {
  6070. static get type() {
  6071. return 'ColorSpaceNode';
  6072. }
  6073. /**
  6074. * Constructs a new color space node.
  6075. *
  6076. * @param {Node} colorNode - Represents the color to convert.
  6077. * @param {string} source - The source color space.
  6078. * @param {string} target - The target color space.
  6079. */
  6080. constructor( colorNode, source, target ) {
  6081. super( 'vec4' );
  6082. /**
  6083. * Represents the color to convert.
  6084. *
  6085. * @type {Node}
  6086. */
  6087. this.colorNode = colorNode;
  6088. /**
  6089. * The source color space.
  6090. *
  6091. * @type {string}
  6092. */
  6093. this.source = source;
  6094. /**
  6095. * The target color space.
  6096. *
  6097. * @type {string}
  6098. */
  6099. this.target = target;
  6100. }
  6101. /**
  6102. * This method resolves the constants `WORKING_COLOR_SPACE` and
  6103. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  6104. * color management and renderer.
  6105. *
  6106. * @param {NodeBuilder} builder - The current node builder.
  6107. * @param {string} colorSpace - The color space to resolve.
  6108. * @return {string} The resolved color space.
  6109. */
  6110. resolveColorSpace( builder, colorSpace ) {
  6111. if ( colorSpace === WORKING_COLOR_SPACE ) {
  6112. return ColorManagement.workingColorSpace;
  6113. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  6114. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  6115. }
  6116. return colorSpace;
  6117. }
  6118. setup( builder ) {
  6119. const { colorNode } = this;
  6120. const source = this.resolveColorSpace( builder, this.source );
  6121. const target = this.resolveColorSpace( builder, this.target );
  6122. let outputNode = colorNode;
  6123. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  6124. return outputNode;
  6125. }
  6126. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  6127. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  6128. }
  6129. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  6130. outputNode = vec4(
  6131. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  6132. outputNode.a
  6133. );
  6134. }
  6135. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  6136. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  6137. }
  6138. return outputNode;
  6139. }
  6140. }
  6141. /**
  6142. * TSL function for converting a given color node from the current working color space to the given color space.
  6143. *
  6144. * @tsl
  6145. * @function
  6146. * @param {Node} node - Represents the node to convert.
  6147. * @param {string} targetColorSpace - The target color space.
  6148. * @returns {ColorSpaceNode}
  6149. */
  6150. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  6151. /**
  6152. * TSL function for converting a given color node from the given color space to the current working color space.
  6153. *
  6154. * @tsl
  6155. * @function
  6156. * @param {Node} node - Represents the node to convert.
  6157. * @param {string} sourceColorSpace - The source color space.
  6158. * @returns {ColorSpaceNode}
  6159. */
  6160. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  6161. /**
  6162. * TSL function for converting a given color node from one color space to another one.
  6163. *
  6164. * @tsl
  6165. * @function
  6166. * @param {Node} node - Represents the node to convert.
  6167. * @param {string} sourceColorSpace - The source color space.
  6168. * @param {string} targetColorSpace - The target color space.
  6169. * @returns {ColorSpaceNode}
  6170. */
  6171. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  6172. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  6173. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  6174. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  6175. /**
  6176. * This class is only relevant if the referenced property is array-like.
  6177. * In this case, `ReferenceElementNode` allows to refer to a specific
  6178. * element inside the data structure via an index.
  6179. *
  6180. * @augments ArrayElementNode
  6181. */
  6182. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  6183. static get type() {
  6184. return 'ReferenceElementNode';
  6185. }
  6186. /**
  6187. * Constructs a new reference element node.
  6188. *
  6189. * @param {ReferenceBaseNode} referenceNode - The reference node.
  6190. * @param {Node} indexNode - The index node that defines the element access.
  6191. */
  6192. constructor( referenceNode, indexNode ) {
  6193. super( referenceNode, indexNode );
  6194. /**
  6195. * Similar to {@link ReferenceBaseNode#reference}, an additional
  6196. * property references to the current node.
  6197. *
  6198. * @type {?ReferenceBaseNode}
  6199. * @default null
  6200. */
  6201. this.referenceNode = referenceNode;
  6202. /**
  6203. * This flag can be used for type testing.
  6204. *
  6205. * @type {boolean}
  6206. * @readonly
  6207. * @default true
  6208. */
  6209. this.isReferenceElementNode = true;
  6210. }
  6211. /**
  6212. * This method is overwritten since the node type is inferred from
  6213. * the uniform type of the reference node.
  6214. *
  6215. * @return {string} The node type.
  6216. */
  6217. getNodeType() {
  6218. return this.referenceNode.uniformType;
  6219. }
  6220. generate( builder ) {
  6221. const snippet = super.generate( builder );
  6222. const arrayType = this.referenceNode.getNodeType();
  6223. const elementType = this.getNodeType();
  6224. return builder.format( snippet, arrayType, elementType );
  6225. }
  6226. };
  6227. /**
  6228. * Base class for nodes which establishes a reference to a property of another object.
  6229. * In this way, the value of the node is automatically linked to the value of
  6230. * referenced object. Reference nodes internally represent the linked value
  6231. * as a uniform.
  6232. *
  6233. * @augments Node
  6234. */
  6235. class ReferenceBaseNode extends Node {
  6236. static get type() {
  6237. return 'ReferenceBaseNode';
  6238. }
  6239. /**
  6240. * Constructs a new reference base node.
  6241. *
  6242. * @param {string} property - The name of the property the node refers to.
  6243. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6244. * @param {?Object} [object=null] - The object the property belongs to.
  6245. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6246. */
  6247. constructor( property, uniformType, object = null, count = null ) {
  6248. super();
  6249. /**
  6250. * The name of the property the node refers to.
  6251. *
  6252. * @type {string}
  6253. */
  6254. this.property = property;
  6255. /**
  6256. * The uniform type that should be used to represent the property value.
  6257. *
  6258. * @type {string}
  6259. */
  6260. this.uniformType = uniformType;
  6261. /**
  6262. * The object the property belongs to.
  6263. *
  6264. * @type {?Object}
  6265. * @default null
  6266. */
  6267. this.object = object;
  6268. /**
  6269. * When the linked property is an array, this parameter defines its length.
  6270. *
  6271. * @type {?number}
  6272. * @default null
  6273. */
  6274. this.count = count;
  6275. /**
  6276. * The property name might have dots so nested properties can be referred.
  6277. * The hierarchy of the names is stored inside this array.
  6278. *
  6279. * @type {Array<string>}
  6280. */
  6281. this.properties = property.split( '.' );
  6282. /**
  6283. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6284. * since the final reference might be updated from calling code.
  6285. *
  6286. * @type {?Object}
  6287. * @default null
  6288. */
  6289. this.reference = object;
  6290. /**
  6291. * The uniform node that holds the value of the reference node.
  6292. *
  6293. * @type {UniformNode}
  6294. * @default null
  6295. */
  6296. this.node = null;
  6297. /**
  6298. * The uniform group of the internal uniform.
  6299. *
  6300. * @type {UniformGroupNode}
  6301. * @default null
  6302. */
  6303. this.group = null;
  6304. /**
  6305. * Overwritten since reference nodes are updated per object.
  6306. *
  6307. * @type {string}
  6308. * @default 'object'
  6309. */
  6310. this.updateType = NodeUpdateType.OBJECT;
  6311. }
  6312. /**
  6313. * Sets the uniform group for this reference node.
  6314. *
  6315. * @param {UniformGroupNode} group - The uniform group to set.
  6316. * @return {ReferenceBaseNode} A reference to this node.
  6317. */
  6318. setGroup( group ) {
  6319. this.group = group;
  6320. return this;
  6321. }
  6322. /**
  6323. * When the referred property is array-like, this method can be used
  6324. * to access elements via an index node.
  6325. *
  6326. * @param {IndexNode} indexNode - indexNode.
  6327. * @return {ReferenceElementNode} A reference to an element.
  6328. */
  6329. element( indexNode ) {
  6330. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  6331. }
  6332. /**
  6333. * Sets the node type which automatically defines the internal
  6334. * uniform type.
  6335. *
  6336. * @param {string} uniformType - The type to set.
  6337. */
  6338. setNodeType( uniformType ) {
  6339. const node = uniform( null, uniformType );
  6340. if ( this.group !== null ) {
  6341. node.setGroup( this.group );
  6342. }
  6343. this.node = node;
  6344. }
  6345. /**
  6346. * This method is overwritten since the node type is inferred from
  6347. * the type of the reference node.
  6348. *
  6349. * @param {NodeBuilder} builder - The current node builder.
  6350. * @return {string} The node type.
  6351. */
  6352. getNodeType( builder ) {
  6353. if ( this.node === null ) {
  6354. this.updateReference( builder );
  6355. this.updateValue();
  6356. }
  6357. return this.node.getNodeType( builder );
  6358. }
  6359. /**
  6360. * Returns the property value from the given referred object.
  6361. *
  6362. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6363. * @return {any} The value.
  6364. */
  6365. getValueFromReference( object = this.reference ) {
  6366. const { properties } = this;
  6367. let value = object[ properties[ 0 ] ];
  6368. for ( let i = 1; i < properties.length; i ++ ) {
  6369. value = value[ properties[ i ] ];
  6370. }
  6371. return value;
  6372. }
  6373. /**
  6374. * Allows to update the reference based on the given state. The state is only
  6375. * evaluated {@link ReferenceBaseNode#object} is not set.
  6376. *
  6377. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6378. * @return {Object} The updated reference.
  6379. */
  6380. updateReference( state ) {
  6381. this.reference = this.object !== null ? this.object : state.object;
  6382. return this.reference;
  6383. }
  6384. /**
  6385. * The output of the reference node is the internal uniform node.
  6386. *
  6387. * @return {UniformNode} The output node.
  6388. */
  6389. setup() {
  6390. this.updateValue();
  6391. return this.node;
  6392. }
  6393. /**
  6394. * Overwritten to update the internal uniform value.
  6395. *
  6396. * @param {NodeFrame} frame - A reference to the current node frame.
  6397. */
  6398. update( /*frame*/ ) {
  6399. this.updateValue();
  6400. }
  6401. /**
  6402. * Retrieves the value from the referred object property and uses it
  6403. * to updated the internal uniform.
  6404. */
  6405. updateValue() {
  6406. if ( this.node === null ) this.setNodeType( this.uniformType );
  6407. const value = this.getValueFromReference();
  6408. if ( Array.isArray( value ) ) {
  6409. this.node.array = value;
  6410. } else {
  6411. this.node.value = value;
  6412. }
  6413. }
  6414. }
  6415. /**
  6416. * TSL function for creating a reference base node.
  6417. *
  6418. * @tsl
  6419. * @function
  6420. * @param {string} name - The name of the property the node refers to.
  6421. * @param {string} type - The uniform type that should be used to represent the property value.
  6422. * @param {Object} object - The object the property belongs to.
  6423. * @returns {ReferenceBaseNode}
  6424. */
  6425. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  6426. /**
  6427. * This node is a special type of reference node which is intended
  6428. * for linking renderer properties with node values.
  6429. * ```js
  6430. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6431. * ```
  6432. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6433. * automatically be updated.
  6434. *
  6435. * @augments ReferenceBaseNode
  6436. */
  6437. class RendererReferenceNode extends ReferenceBaseNode {
  6438. static get type() {
  6439. return 'RendererReferenceNode';
  6440. }
  6441. /**
  6442. * Constructs a new renderer reference node.
  6443. *
  6444. * @param {string} property - The name of the property the node refers to.
  6445. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6446. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6447. * the node refers to the renderer of the current state.
  6448. */
  6449. constructor( property, inputType, renderer = null ) {
  6450. super( property, inputType, renderer );
  6451. /**
  6452. * The renderer the property belongs to. When no renderer is set,
  6453. * the node refers to the renderer of the current state.
  6454. *
  6455. * @type {?Renderer}
  6456. * @default null
  6457. */
  6458. this.renderer = renderer;
  6459. this.setGroup( renderGroup );
  6460. }
  6461. /**
  6462. * Updates the reference based on the given state. The state is only evaluated
  6463. * {@link RendererReferenceNode#renderer} is not set.
  6464. *
  6465. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6466. * @return {Object} The updated reference.
  6467. */
  6468. updateReference( state ) {
  6469. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6470. return this.reference;
  6471. }
  6472. }
  6473. /**
  6474. * TSL function for creating a renderer reference node.
  6475. *
  6476. * @tsl
  6477. * @function
  6478. * @param {string} name - The name of the property the node refers to.
  6479. * @param {string} type - The uniform type that should be used to represent the property value.
  6480. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6481. * the node refers to the renderer of the current state.
  6482. * @returns {RendererReferenceNode}
  6483. */
  6484. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  6485. /**
  6486. * This node represents a tone mapping operation.
  6487. *
  6488. * @augments TempNode
  6489. */
  6490. class ToneMappingNode extends TempNode {
  6491. static get type() {
  6492. return 'ToneMappingNode';
  6493. }
  6494. /**
  6495. * Constructs a new tone mapping node.
  6496. *
  6497. * @param {number} toneMapping - The tone mapping type.
  6498. * @param {Node} exposureNode - The tone mapping exposure.
  6499. * @param {Node} [colorNode=null] - The color node to process.
  6500. */
  6501. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6502. super( 'vec3' );
  6503. /**
  6504. * The tone mapping type.
  6505. *
  6506. * @private
  6507. * @type {number}
  6508. */
  6509. this._toneMapping = toneMapping;
  6510. /**
  6511. * The tone mapping exposure.
  6512. *
  6513. * @type {Node}
  6514. * @default null
  6515. */
  6516. this.exposureNode = exposureNode;
  6517. /**
  6518. * Represents the color to process.
  6519. *
  6520. * @type {?Node}
  6521. * @default null
  6522. */
  6523. this.colorNode = colorNode;
  6524. }
  6525. /**
  6526. * Overwrites the default `customCacheKey()` implementation by including the tone
  6527. * mapping type into the cache key.
  6528. *
  6529. * @return {number} The hash.
  6530. */
  6531. customCacheKey() {
  6532. return hash$1( this._toneMapping );
  6533. }
  6534. /**
  6535. * Sets the tone mapping type.
  6536. *
  6537. * @param {number} value - The tone mapping type.
  6538. * @return {ToneMappingNode} A reference to this node.
  6539. */
  6540. setToneMapping( value ) {
  6541. this._toneMapping = value;
  6542. return this;
  6543. }
  6544. /**
  6545. * Gets the tone mapping type.
  6546. *
  6547. * @returns {number} The tone mapping type.
  6548. */
  6549. getToneMapping() {
  6550. return this._toneMapping;
  6551. }
  6552. setup( builder ) {
  6553. const colorNode = this.colorNode || builder.context.color;
  6554. const toneMapping = this._toneMapping;
  6555. if ( toneMapping === NoToneMapping ) return colorNode;
  6556. let outputNode = null;
  6557. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6558. if ( toneMappingFn !== null ) {
  6559. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6560. } else {
  6561. error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6562. outputNode = colorNode;
  6563. }
  6564. return outputNode;
  6565. }
  6566. }
  6567. /**
  6568. * TSL function for creating a tone mapping node.
  6569. *
  6570. * @tsl
  6571. * @function
  6572. * @param {number} mapping - The tone mapping type.
  6573. * @param {Node<float> | number} exposure - The tone mapping exposure.
  6574. * @param {Node<vec3> | Color} color - The color node to process.
  6575. * @returns {ToneMappingNode<vec3>}
  6576. */
  6577. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6578. /**
  6579. * TSL object that represents the global tone mapping exposure of the renderer.
  6580. *
  6581. * @tsl
  6582. * @type {RendererReferenceNode<vec3>}
  6583. */
  6584. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6585. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6586. /**
  6587. * In earlier `three.js` versions it was only possible to define attribute data
  6588. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6589. * on the node level.
  6590. * ```js
  6591. * const geometry = new THREE.PlaneGeometry();
  6592. * const positionAttribute = geometry.getAttribute( 'position' );
  6593. *
  6594. * const colors = [];
  6595. * for ( let i = 0; i < position.count; i ++ ) {
  6596. * colors.push( 1, 0, 0 );
  6597. * }
  6598. *
  6599. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6600. * ```
  6601. * This new approach is especially interesting when geometry data are generated via
  6602. * compute shaders. The below line converts a storage buffer into an attribute node.
  6603. * ```js
  6604. * material.positionNode = positionBuffer.toAttribute();
  6605. * ```
  6606. * @augments InputNode
  6607. */
  6608. class BufferAttributeNode extends InputNode {
  6609. static get type() {
  6610. return 'BufferAttributeNode';
  6611. }
  6612. /**
  6613. * Constructs a new buffer attribute node.
  6614. *
  6615. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6616. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6617. * @param {number} [bufferStride=0] - The buffer stride.
  6618. * @param {number} [bufferOffset=0] - The buffer offset.
  6619. */
  6620. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6621. super( value, bufferType );
  6622. /**
  6623. * This flag can be used for type testing.
  6624. *
  6625. * @type {boolean}
  6626. * @readonly
  6627. * @default true
  6628. */
  6629. this.isBufferNode = true;
  6630. /**
  6631. * The buffer type (e.g. `'vec3'`).
  6632. *
  6633. * @type {?string}
  6634. * @default null
  6635. */
  6636. this.bufferType = bufferType;
  6637. /**
  6638. * The buffer stride.
  6639. *
  6640. * @type {number}
  6641. * @default 0
  6642. */
  6643. this.bufferStride = bufferStride;
  6644. /**
  6645. * The buffer offset.
  6646. *
  6647. * @type {number}
  6648. * @default 0
  6649. */
  6650. this.bufferOffset = bufferOffset;
  6651. /**
  6652. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6653. * if you are planning to update the attribute data per frame.
  6654. *
  6655. * @type {number}
  6656. * @default StaticDrawUsage
  6657. */
  6658. this.usage = StaticDrawUsage;
  6659. /**
  6660. * Whether the attribute is instanced or not.
  6661. *
  6662. * @type {boolean}
  6663. * @default false
  6664. */
  6665. this.instanced = false;
  6666. /**
  6667. * A reference to the buffer attribute.
  6668. *
  6669. * @type {?BufferAttribute}
  6670. * @default null
  6671. */
  6672. this.attribute = null;
  6673. /**
  6674. * `BufferAttributeNode` sets this property to `true` by default.
  6675. *
  6676. * @type {boolean}
  6677. * @default true
  6678. */
  6679. this.global = true;
  6680. if ( value && value.isBufferAttribute === true ) {
  6681. this.attribute = value;
  6682. this.usage = value.usage;
  6683. this.instanced = value.isInstancedBufferAttribute;
  6684. }
  6685. }
  6686. /**
  6687. * This method is overwritten since the attribute data might be shared
  6688. * and thus the hash should be shared as well.
  6689. *
  6690. * @param {NodeBuilder} builder - The current node builder.
  6691. * @return {string} The hash.
  6692. */
  6693. getHash( builder ) {
  6694. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6695. let bufferData = builder.globalCache.getData( this.value );
  6696. if ( bufferData === undefined ) {
  6697. bufferData = {
  6698. node: this
  6699. };
  6700. builder.globalCache.setData( this.value, bufferData );
  6701. }
  6702. return bufferData.node.uuid;
  6703. }
  6704. return this.uuid;
  6705. }
  6706. /**
  6707. * This method is overwritten since the node type is inferred from
  6708. * the buffer attribute.
  6709. *
  6710. * @param {NodeBuilder} builder - The current node builder.
  6711. * @return {string} The node type.
  6712. */
  6713. getNodeType( builder ) {
  6714. if ( this.bufferType === null ) {
  6715. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6716. }
  6717. return this.bufferType;
  6718. }
  6719. /**
  6720. * Depending on which value was passed to the node, `setup()` behaves
  6721. * differently. If no instance of `BufferAttribute` was passed, the method
  6722. * creates an internal attribute and configures it respectively.
  6723. *
  6724. * @param {NodeBuilder} builder - The current node builder.
  6725. */
  6726. setup( builder ) {
  6727. if ( this.attribute !== null ) return;
  6728. const type = this.getNodeType( builder );
  6729. const array = this.value;
  6730. const itemSize = builder.getTypeLength( type );
  6731. const stride = this.bufferStride || itemSize;
  6732. const offset = this.bufferOffset;
  6733. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  6734. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6735. buffer.setUsage( this.usage );
  6736. this.attribute = bufferAttribute;
  6737. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6738. }
  6739. /**
  6740. * Generates the code snippet of the buffer attribute node.
  6741. *
  6742. * @param {NodeBuilder} builder - The current node builder.
  6743. * @return {string} The generated code snippet.
  6744. */
  6745. generate( builder ) {
  6746. const nodeType = this.getNodeType( builder );
  6747. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6748. const propertyName = builder.getPropertyName( nodeAttribute );
  6749. let output = null;
  6750. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6751. this.name = propertyName;
  6752. output = propertyName;
  6753. } else {
  6754. const nodeVarying = varying( this );
  6755. output = nodeVarying.build( builder, nodeType );
  6756. }
  6757. return output;
  6758. }
  6759. /**
  6760. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6761. *
  6762. * @param {NodeBuilder} builder - The current node builder.
  6763. * @return {string} The input type.
  6764. */
  6765. getInputType( /*builder*/ ) {
  6766. return 'bufferAttribute';
  6767. }
  6768. /**
  6769. * Sets the `usage` property to the given value.
  6770. *
  6771. * @param {number} value - The usage to set.
  6772. * @return {BufferAttributeNode} A reference to this node.
  6773. */
  6774. setUsage( value ) {
  6775. this.usage = value;
  6776. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6777. this.attribute.usage = value;
  6778. }
  6779. return this;
  6780. }
  6781. /**
  6782. * Sets the `instanced` property to the given value.
  6783. *
  6784. * @param {boolean} value - The value to set.
  6785. * @return {BufferAttributeNode} A reference to this node.
  6786. */
  6787. setInstanced( value ) {
  6788. this.instanced = value;
  6789. return this;
  6790. }
  6791. }
  6792. /**
  6793. * TSL function for creating a buffer attribute node.
  6794. *
  6795. * @tsl
  6796. * @function
  6797. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6798. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6799. * @param {number} [stride=0] - The buffer stride.
  6800. * @param {number} [offset=0] - The buffer offset.
  6801. * @returns {BufferAttributeNode}
  6802. */
  6803. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  6804. /**
  6805. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6806. * Use this function if attribute data are updated per frame.
  6807. *
  6808. * @tsl
  6809. * @function
  6810. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6811. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6812. * @param {number} [stride=0] - The buffer stride.
  6813. * @param {number} [offset=0] - The buffer offset.
  6814. * @returns {BufferAttributeNode}
  6815. */
  6816. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  6817. /**
  6818. * TSL function for creating a buffer attribute node but with enabled instancing
  6819. *
  6820. * @tsl
  6821. * @function
  6822. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6823. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6824. * @param {number} [stride=0] - The buffer stride.
  6825. * @param {number} [offset=0] - The buffer offset.
  6826. * @returns {BufferAttributeNode}
  6827. */
  6828. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  6829. /**
  6830. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6831. *
  6832. * @tsl
  6833. * @function
  6834. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6835. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6836. * @param {number} [stride=0] - The buffer stride.
  6837. * @param {number} [offset=0] - The buffer offset.
  6838. * @returns {BufferAttributeNode}
  6839. */
  6840. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  6841. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6842. /**
  6843. * TODO
  6844. *
  6845. * @augments Node
  6846. */
  6847. class ComputeNode extends Node {
  6848. static get type() {
  6849. return 'ComputeNode';
  6850. }
  6851. /**
  6852. * Constructs a new compute node.
  6853. *
  6854. * @param {Node} computeNode - TODO
  6855. * @param {Array<number>} workgroupSize - TODO.
  6856. */
  6857. constructor( computeNode, workgroupSize ) {
  6858. super( 'void' );
  6859. /**
  6860. * This flag can be used for type testing.
  6861. *
  6862. * @type {boolean}
  6863. * @readonly
  6864. * @default true
  6865. */
  6866. this.isComputeNode = true;
  6867. /**
  6868. * TODO
  6869. *
  6870. * @type {Node}
  6871. */
  6872. this.computeNode = computeNode;
  6873. /**
  6874. * TODO
  6875. *
  6876. * @type {Array<number>}
  6877. * @default [ 64 ]
  6878. */
  6879. this.workgroupSize = workgroupSize;
  6880. /**
  6881. * TODO
  6882. *
  6883. * @type {number|Array<number>}
  6884. */
  6885. this.count = null;
  6886. /**
  6887. * TODO
  6888. *
  6889. * @type {number}
  6890. */
  6891. this.version = 1;
  6892. /**
  6893. * The name or label of the uniform.
  6894. *
  6895. * @type {string}
  6896. * @default ''
  6897. */
  6898. this.name = '';
  6899. /**
  6900. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  6901. * is executed once per object by default.
  6902. *
  6903. * @type {string}
  6904. * @default 'object'
  6905. */
  6906. this.updateBeforeType = NodeUpdateType.OBJECT;
  6907. /**
  6908. * TODO
  6909. *
  6910. * @type {?Function}
  6911. */
  6912. this.onInitFunction = null;
  6913. }
  6914. /**
  6915. * TODO
  6916. *
  6917. * @param {number|Array<number>} count - Array with [ x, y, z ] values for dispatch or a single number for the count
  6918. * @return {ComputeNode}
  6919. */
  6920. setCount( count ) {
  6921. this.count = count;
  6922. return this;
  6923. }
  6924. /**
  6925. * TODO
  6926. *
  6927. * @return {number|Array<number>}
  6928. */
  6929. getCount() {
  6930. return this.count;
  6931. }
  6932. /**
  6933. * Executes the `dispose` event for this node.
  6934. */
  6935. dispose() {
  6936. this.dispatchEvent( { type: 'dispose' } );
  6937. }
  6938. /**
  6939. * Sets the {@link ComputeNode#name} property.
  6940. *
  6941. * @param {string} name - The name of the uniform.
  6942. * @return {ComputeNode} A reference to this node.
  6943. */
  6944. setName( name ) {
  6945. this.name = name;
  6946. return this;
  6947. }
  6948. /**
  6949. * Sets the {@link ComputeNode#name} property.
  6950. *
  6951. * @deprecated
  6952. * @param {string} name - The name of the uniform.
  6953. * @return {ComputeNode} A reference to this node.
  6954. */
  6955. label( name ) {
  6956. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  6957. return this.setName( name );
  6958. }
  6959. /**
  6960. * TODO
  6961. *
  6962. * @param {Function} callback - TODO.
  6963. * @return {ComputeNode} A reference to this node.
  6964. */
  6965. onInit( callback ) {
  6966. this.onInitFunction = callback;
  6967. return this;
  6968. }
  6969. /**
  6970. * The method execute the compute for this node.
  6971. *
  6972. * @param {NodeFrame} frame - A reference to the current node frame.
  6973. */
  6974. updateBefore( { renderer } ) {
  6975. renderer.compute( this );
  6976. }
  6977. setup( builder ) {
  6978. const result = this.computeNode.build( builder );
  6979. if ( result ) {
  6980. const properties = builder.getNodeProperties( this );
  6981. properties.outputComputeNode = result.outputNode;
  6982. result.outputNode = null;
  6983. }
  6984. return result;
  6985. }
  6986. generate( builder, output ) {
  6987. const { shaderStage } = builder;
  6988. if ( shaderStage === 'compute' ) {
  6989. const snippet = this.computeNode.build( builder, 'void' );
  6990. if ( snippet !== '' ) {
  6991. builder.addLineFlowCode( snippet, this );
  6992. }
  6993. } else {
  6994. const properties = builder.getNodeProperties( this );
  6995. const outputComputeNode = properties.outputComputeNode;
  6996. if ( outputComputeNode ) {
  6997. return outputComputeNode.build( builder, output );
  6998. }
  6999. }
  7000. }
  7001. }
  7002. /**
  7003. * TSL function for creating a compute kernel node.
  7004. *
  7005. * @tsl
  7006. * @function
  7007. * @param {Node} node - TODO
  7008. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7009. * @returns {AtomicFunctionNode}
  7010. */
  7011. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  7012. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  7013. error( 'TSL: compute() workgroupSize must have 1, 2, or 3 elements' );
  7014. }
  7015. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  7016. const val = workgroupSize[ i ];
  7017. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  7018. error( `TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer` );
  7019. }
  7020. }
  7021. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  7022. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  7023. //
  7024. return nodeObject( new ComputeNode( nodeObject( node ), workgroupSize ) );
  7025. };
  7026. /**
  7027. * TSL function for creating a compute node.
  7028. *
  7029. * @tsl
  7030. * @function
  7031. * @param {Node} node - TODO
  7032. * @param {number|Array<number>} count - TODO.
  7033. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7034. * @returns {AtomicFunctionNode}
  7035. */
  7036. const compute = ( node, count, workgroupSize ) => computeKernel( node, workgroupSize ).setCount( count );
  7037. addMethodChaining( 'compute', compute );
  7038. addMethodChaining( 'computeKernel', computeKernel );
  7039. /**
  7040. * This node can be used as a cache management component for another node.
  7041. * Caching is in general used by default in {@link NodeBuilder} but this node
  7042. * allows the usage of a shared parent cache during the build process.
  7043. *
  7044. * @augments Node
  7045. */
  7046. class IsolateNode extends Node {
  7047. static get type() {
  7048. return 'IsolateNode';
  7049. }
  7050. /**
  7051. * Constructs a new cache node.
  7052. *
  7053. * @param {Node} node - The node that should be cached.
  7054. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7055. */
  7056. constructor( node, parent = true ) {
  7057. super();
  7058. /**
  7059. * The node that should be cached.
  7060. *
  7061. * @type {Node}
  7062. */
  7063. this.node = node;
  7064. /**
  7065. * Whether this node refers to a shared parent cache or not.
  7066. *
  7067. * @type {boolean}
  7068. * @default true
  7069. */
  7070. this.parent = parent;
  7071. /**
  7072. * This flag can be used for type testing.
  7073. *
  7074. * @type {boolean}
  7075. * @readonly
  7076. * @default true
  7077. */
  7078. this.isIsolateNode = true;
  7079. }
  7080. getNodeType( builder ) {
  7081. const previousCache = builder.getCache();
  7082. const cache = builder.getCacheFromNode( this, this.parent );
  7083. builder.setCache( cache );
  7084. const nodeType = this.node.getNodeType( builder );
  7085. builder.setCache( previousCache );
  7086. return nodeType;
  7087. }
  7088. build( builder, ...params ) {
  7089. const previousCache = builder.getCache();
  7090. const cache = builder.getCacheFromNode( this, this.parent );
  7091. builder.setCache( cache );
  7092. const data = this.node.build( builder, ...params );
  7093. builder.setCache( previousCache );
  7094. return data;
  7095. }
  7096. setParent( parent ) {
  7097. this.parent = parent;
  7098. return this;
  7099. }
  7100. getParent() {
  7101. return this.parent;
  7102. }
  7103. }
  7104. /**
  7105. * TSL function for creating a cache node.
  7106. *
  7107. * @tsl
  7108. * @function
  7109. * @param {Node} node - The node that should be cached.
  7110. * @returns {IsolateNode}
  7111. */
  7112. const isolate = ( node ) => new IsolateNode( nodeObject( node ) );
  7113. /**
  7114. * TSL function for creating a cache node.
  7115. *
  7116. * @tsl
  7117. * @function
  7118. * @deprecated
  7119. * @param {Node} node - The node that should be cached.
  7120. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7121. * @returns {IsolateNode}
  7122. */
  7123. function cache( node, parent = true ) {
  7124. warn( 'TSL: "cache()" has been deprecated. Use "isolate()" instead.' ); // @deprecated r181
  7125. return isolate( node ).setParent( parent );
  7126. }
  7127. addMethodChaining( 'cache', cache );
  7128. addMethodChaining( 'isolate', isolate );
  7129. /**
  7130. * The class generates the code of a given node but returns another node in the output.
  7131. * This can be used to call a method or node that does not return a value, i.e.
  7132. * type `void` on an input where returning a value is required. Example:
  7133. *
  7134. * ```js
  7135. * material.colorNode = myColor.bypass( runVoidFn() )
  7136. *```
  7137. *
  7138. * @augments Node
  7139. */
  7140. class BypassNode extends Node {
  7141. static get type() {
  7142. return 'BypassNode';
  7143. }
  7144. /**
  7145. * Constructs a new bypass node.
  7146. *
  7147. * @param {Node} outputNode - The output node.
  7148. * @param {Node} callNode - The call node.
  7149. */
  7150. constructor( outputNode, callNode ) {
  7151. super();
  7152. /**
  7153. * This flag can be used for type testing.
  7154. *
  7155. * @type {boolean}
  7156. * @readonly
  7157. * @default true
  7158. */
  7159. this.isBypassNode = true;
  7160. /**
  7161. * The output node.
  7162. *
  7163. * @type {Node}
  7164. */
  7165. this.outputNode = outputNode;
  7166. /**
  7167. * The call node.
  7168. *
  7169. * @type {Node}
  7170. */
  7171. this.callNode = callNode;
  7172. }
  7173. getNodeType( builder ) {
  7174. return this.outputNode.getNodeType( builder );
  7175. }
  7176. generate( builder ) {
  7177. const snippet = this.callNode.build( builder, 'void' );
  7178. if ( snippet !== '' ) {
  7179. builder.addLineFlowCode( snippet, this );
  7180. }
  7181. return this.outputNode.build( builder );
  7182. }
  7183. }
  7184. /**
  7185. * TSL function for creating a bypass node.
  7186. *
  7187. * @tsl
  7188. * @function
  7189. * @param {Node} outputNode - The output node.
  7190. * @param {Node} callNode - The call node.
  7191. * @returns {BypassNode}
  7192. */
  7193. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  7194. addMethodChaining( 'bypass', bypass );
  7195. /**
  7196. * This node allows to remap a node value from one range into another. E.g a value of
  7197. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7198. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  7199. *
  7200. * @augments Node
  7201. */
  7202. class RemapNode extends Node {
  7203. static get type() {
  7204. return 'RemapNode';
  7205. }
  7206. /**
  7207. * Constructs a new remap node.
  7208. *
  7209. * @param {Node} node - The node that should be remapped.
  7210. * @param {Node} inLowNode - The source or current lower bound of the range.
  7211. * @param {Node} inHighNode - The source or current upper bound of the range.
  7212. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  7213. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  7214. */
  7215. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  7216. super();
  7217. /**
  7218. * The node that should be remapped.
  7219. *
  7220. * @type {Node}
  7221. */
  7222. this.node = node;
  7223. /**
  7224. * The source or current lower bound of the range.
  7225. *
  7226. * @type {Node}
  7227. */
  7228. this.inLowNode = inLowNode;
  7229. /**
  7230. * The source or current upper bound of the range.
  7231. *
  7232. * @type {Node}
  7233. */
  7234. this.inHighNode = inHighNode;
  7235. /**
  7236. * The target lower bound of the range.
  7237. *
  7238. * @type {Node}
  7239. * @default float(0)
  7240. */
  7241. this.outLowNode = outLowNode;
  7242. /**
  7243. * The target upper bound of the range.
  7244. *
  7245. * @type {Node}
  7246. * @default float(1)
  7247. */
  7248. this.outHighNode = outHighNode;
  7249. /**
  7250. * Whether the node value should be clamped before
  7251. * remapping it to the target range.
  7252. *
  7253. * @type {boolean}
  7254. * @default true
  7255. */
  7256. this.doClamp = true;
  7257. }
  7258. setup() {
  7259. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  7260. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  7261. if ( doClamp === true ) t = t.clamp();
  7262. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  7263. }
  7264. }
  7265. /**
  7266. * TSL function for creating a remap node.
  7267. *
  7268. * @tsl
  7269. * @function
  7270. * @param {Node} node - The node that should be remapped.
  7271. * @param {Node} inLowNode - The source or current lower bound of the range.
  7272. * @param {Node} inHighNode - The source or current upper bound of the range.
  7273. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7274. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7275. * @returns {RemapNode}
  7276. */
  7277. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  7278. /**
  7279. * TSL function for creating a remap node, but with enabled clamping.
  7280. *
  7281. * @tsl
  7282. * @function
  7283. * @param {Node} node - The node that should be remapped.
  7284. * @param {Node} inLowNode - The source or current lower bound of the range.
  7285. * @param {Node} inHighNode - The source or current upper bound of the range.
  7286. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7287. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7288. * @returns {RemapNode}
  7289. */
  7290. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  7291. addMethodChaining( 'remap', remap );
  7292. addMethodChaining( 'remapClamp', remapClamp );
  7293. /**
  7294. * This class can be used to implement basic expressions in shader code.
  7295. * Basic examples for that are `return`, `continue` or `discard` statements.
  7296. *
  7297. * @augments Node
  7298. */
  7299. class ExpressionNode extends Node {
  7300. static get type() {
  7301. return 'ExpressionNode';
  7302. }
  7303. /**
  7304. * Constructs a new expression node.
  7305. *
  7306. * @param {string} [snippet=''] - The native code snippet.
  7307. * @param {string} [nodeType='void'] - The node type.
  7308. */
  7309. constructor( snippet = '', nodeType = 'void' ) {
  7310. super( nodeType );
  7311. /**
  7312. * The native code snippet.
  7313. *
  7314. * @type {string}
  7315. * @default ''
  7316. */
  7317. this.snippet = snippet;
  7318. }
  7319. generate( builder, output ) {
  7320. const type = this.getNodeType( builder );
  7321. const snippet = this.snippet;
  7322. if ( type === 'void' ) {
  7323. builder.addLineFlowCode( snippet, this );
  7324. } else {
  7325. return builder.format( snippet, type, output );
  7326. }
  7327. }
  7328. }
  7329. /**
  7330. * TSL function for creating an expression node.
  7331. *
  7332. * @tsl
  7333. * @function
  7334. * @param {string} [snippet] - The native code snippet.
  7335. * @param {?string} [nodeType='void'] - The node type.
  7336. * @returns {ExpressionNode}
  7337. */
  7338. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  7339. /**
  7340. * Represents a `discard` shader operation in TSL.
  7341. *
  7342. * @tsl
  7343. * @function
  7344. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  7345. * @return {Node} The `discard` expression.
  7346. */
  7347. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  7348. /**
  7349. * Represents a `return` shader operation in TSL.
  7350. *
  7351. * @tsl
  7352. * @function
  7353. * @return {ExpressionNode} The `return` expression.
  7354. */
  7355. const Return = () => expression( 'return' ).toStack();
  7356. addMethodChaining( 'discard', Discard );
  7357. /**
  7358. * Normally, tone mapping and color conversion happens automatically
  7359. * before outputting pixel too the default (screen) framebuffer. In certain
  7360. * post processing setups this happens to late because certain effects
  7361. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  7362. * to apply tone mapping and color space conversion at an arbitrary point
  7363. * in the effect chain.
  7364. *
  7365. * When applying tone mapping and color space conversion manually with this node,
  7366. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  7367. *
  7368. * ```js
  7369. * const postProcessing = new PostProcessing( renderer );
  7370. * postProcessing.outputColorTransform = false;
  7371. *
  7372. * const scenePass = pass( scene, camera );
  7373. * const outputPass = renderOutput( scenePass );
  7374. *
  7375. * postProcessing.outputNode = outputPass;
  7376. * ```
  7377. *
  7378. * @augments TempNode
  7379. */
  7380. class RenderOutputNode extends TempNode {
  7381. static get type() {
  7382. return 'RenderOutputNode';
  7383. }
  7384. /**
  7385. * Constructs a new render output node.
  7386. *
  7387. * @param {Node} colorNode - The color node to process.
  7388. * @param {?number} toneMapping - The tone mapping type.
  7389. * @param {?string} outputColorSpace - The output color space.
  7390. */
  7391. constructor( colorNode, toneMapping, outputColorSpace ) {
  7392. super( 'vec4' );
  7393. /**
  7394. * The color node to process.
  7395. *
  7396. * @type {Node}
  7397. */
  7398. this.colorNode = colorNode;
  7399. /**
  7400. * The tone mapping type.
  7401. *
  7402. * @private
  7403. * @type {?number}
  7404. */
  7405. this._toneMapping = toneMapping;
  7406. /**
  7407. * The output color space.
  7408. *
  7409. * @type {?string}
  7410. */
  7411. this.outputColorSpace = outputColorSpace;
  7412. /**
  7413. * This flag can be used for type testing.
  7414. *
  7415. * @type {boolean}
  7416. * @readonly
  7417. * @default true
  7418. */
  7419. this.isRenderOutputNode = true;
  7420. }
  7421. /**
  7422. * Sets the tone mapping type.
  7423. *
  7424. * @param {number} value - The tone mapping type.
  7425. * @return {ToneMappingNode} A reference to this node.
  7426. */
  7427. setToneMapping( value ) {
  7428. this._toneMapping = value;
  7429. return this;
  7430. }
  7431. /**
  7432. * Gets the tone mapping type.
  7433. *
  7434. * @returns {number} The tone mapping type.
  7435. */
  7436. getToneMapping() {
  7437. return this._toneMapping;
  7438. }
  7439. setup( { context } ) {
  7440. let outputNode = this.colorNode || context.color;
  7441. // tone mapping
  7442. const toneMapping = ( this._toneMapping !== null ? this._toneMapping : context.toneMapping ) || NoToneMapping;
  7443. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  7444. if ( toneMapping !== NoToneMapping ) {
  7445. outputNode = outputNode.toneMapping( toneMapping );
  7446. }
  7447. // working to output color space
  7448. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  7449. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  7450. }
  7451. return outputNode;
  7452. }
  7453. }
  7454. /**
  7455. * TSL function for creating a posterize node.
  7456. *
  7457. * @tsl
  7458. * @function
  7459. * @param {Node} color - The color node to process.
  7460. * @param {?number} [toneMapping=null] - The tone mapping type.
  7461. * @param {?string} [outputColorSpace=null] - The output color space.
  7462. * @returns {RenderOutputNode}
  7463. */
  7464. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  7465. addMethodChaining( 'renderOutput', renderOutput );
  7466. class DebugNode extends TempNode {
  7467. static get type() {
  7468. return 'DebugNode';
  7469. }
  7470. constructor( node, callback = null ) {
  7471. super();
  7472. this.node = node;
  7473. this.callback = callback;
  7474. }
  7475. getNodeType( builder ) {
  7476. return this.node.getNodeType( builder );
  7477. }
  7478. setup( builder ) {
  7479. return this.node.build( builder );
  7480. }
  7481. analyze( builder ) {
  7482. return this.node.build( builder );
  7483. }
  7484. generate( builder ) {
  7485. const callback = this.callback;
  7486. const snippet = this.node.build( builder );
  7487. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  7488. const border = '-'.repeat( title.length );
  7489. let code = '';
  7490. code += '// #' + title + '#\n';
  7491. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  7492. code += '/* ... */ ' + snippet + ' /* ... */\n';
  7493. code += '// #' + border + '#\n';
  7494. if ( callback !== null ) {
  7495. callback( builder, code );
  7496. } else {
  7497. log$1( code );
  7498. }
  7499. return snippet;
  7500. }
  7501. }
  7502. /**
  7503. * TSL function for creating a debug node.
  7504. *
  7505. * @tsl
  7506. * @function
  7507. * @param {Node} node - The node to debug.
  7508. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  7509. * @returns {DebugNode}
  7510. */
  7511. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) ).toStack();
  7512. addMethodChaining( 'debug', debug );
  7513. /**
  7514. * InspectorBase is the base class for all inspectors.
  7515. *
  7516. * @class InspectorBase
  7517. */
  7518. class InspectorBase {
  7519. /**
  7520. * Creates a new InspectorBase.
  7521. */
  7522. constructor() {
  7523. /**
  7524. * The renderer associated with this inspector.
  7525. *
  7526. * @type {WebGLRenderer}
  7527. * @private
  7528. */
  7529. this._renderer = null;
  7530. /**
  7531. * The current frame being processed.
  7532. *
  7533. * @type {Object}
  7534. */
  7535. this.currentFrame = null;
  7536. }
  7537. /**
  7538. * Returns the node frame for the current renderer.
  7539. *
  7540. * @return {Object} The node frame.
  7541. */
  7542. get nodeFrame() {
  7543. return this._renderer._nodes.nodeFrame;
  7544. }
  7545. /**
  7546. * Sets the renderer for this inspector.
  7547. *
  7548. * @param {WebGLRenderer} renderer - The renderer to associate with this inspector.
  7549. * @return {InspectorBase} This inspector instance.
  7550. */
  7551. setRenderer( renderer ) {
  7552. this._renderer = renderer;
  7553. return this;
  7554. }
  7555. /**
  7556. * Returns the renderer associated with this inspector.
  7557. *
  7558. * @return {WebGLRenderer} The associated renderer.
  7559. */
  7560. getRenderer() {
  7561. return this._renderer;
  7562. }
  7563. /**
  7564. * Initializes the inspector.
  7565. */
  7566. init() { }
  7567. /**
  7568. * Called when a frame begins.
  7569. */
  7570. begin() { }
  7571. /**
  7572. * Called when a frame ends.
  7573. */
  7574. finish() { }
  7575. /**
  7576. * Inspects a node.
  7577. *
  7578. * @param {Node} node - The node to inspect.
  7579. */
  7580. inspect( /*node*/ ) { }
  7581. /**
  7582. * When a compute operation is performed.
  7583. *
  7584. * @param {ComputeNode} computeNode - The compute node being executed.
  7585. * @param {number|Array<number>} dispatchSizeOrCount - The dispatch size or count.
  7586. */
  7587. computeAsync( /*computeNode, dispatchSizeOrCount*/ ) { }
  7588. /**
  7589. * Called when a compute operation begins.
  7590. *
  7591. * @param {string} uid - A unique identifier for the render context.
  7592. * @param {ComputeNode} computeNode - The compute node being executed.
  7593. */
  7594. beginCompute( /*uid, computeNode*/ ) { }
  7595. /**
  7596. * Called when a compute operation ends.
  7597. *
  7598. * @param {string} uid - A unique identifier for the render context.
  7599. * @param {ComputeNode} computeNode - The compute node being executed.
  7600. */
  7601. finishCompute( /*uid*/ ) { }
  7602. /**
  7603. * Called when a render operation begins.
  7604. *
  7605. * @param {string} uid - A unique identifier for the render context.
  7606. * @param {Scene} scene - The scene being rendered.
  7607. * @param {Camera} camera - The camera being used for rendering.
  7608. * @param {?WebGLRenderTarget} renderTarget - The render target, if any.
  7609. */
  7610. beginRender( /*uid, scene, camera, renderTarget*/ ) { }
  7611. /**
  7612. * Called when an animation loop ends.
  7613. *
  7614. * @param {string} uid - A unique identifier for the render context.
  7615. */
  7616. finishRender( /*uid*/ ) { }
  7617. /**
  7618. * Called when a texture copy operation is performed.
  7619. *
  7620. * @param {Texture} srcTexture - The source texture.
  7621. * @param {Texture} dstTexture - The destination texture.
  7622. */
  7623. copyTextureToTexture( /*srcTexture, dstTexture*/ ) { }
  7624. /**
  7625. * Called when a framebuffer copy operation is performed.
  7626. *
  7627. * @param {Texture} framebufferTexture - The texture associated with the framebuffer.
  7628. */
  7629. copyFramebufferToTexture( /*framebufferTexture*/ ) { }
  7630. }
  7631. /**
  7632. * InspectorNode is a wrapper node that allows inspection of node values during rendering.
  7633. * It can be used to debug or analyze node outputs in the rendering pipeline.
  7634. *
  7635. * @augments Node
  7636. */
  7637. class InspectorNode extends Node {
  7638. /**
  7639. * Returns the type of the node.
  7640. *
  7641. * @returns {string}
  7642. */
  7643. static get type() {
  7644. return 'InspectorNode';
  7645. }
  7646. /**
  7647. * Creates an InspectorNode.
  7648. *
  7649. * @param {Node} node - The node to inspect.
  7650. * @param {string} [name=''] - Optional name for the inspector node.
  7651. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7652. */
  7653. constructor( node, name = '', callback = null ) {
  7654. super();
  7655. this.node = node;
  7656. this.name = name;
  7657. this.callback = callback;
  7658. this.updateType = NodeUpdateType.FRAME;
  7659. this.isInspectorNode = true;
  7660. }
  7661. /**
  7662. * Returns the name of the inspector node.
  7663. *
  7664. * @returns {string}
  7665. */
  7666. getName() {
  7667. return this.name || this.node.name;
  7668. }
  7669. /**
  7670. * Updates the inspector node, allowing inspection of the wrapped node.
  7671. *
  7672. * @param {NodeFrame} frame - A reference to the current node frame.
  7673. */
  7674. update( frame ) {
  7675. frame.renderer.inspector.inspect( this );
  7676. }
  7677. /**
  7678. * Returns the type of the wrapped node.
  7679. *
  7680. * @param {NodeBuilder} builder - The node builder.
  7681. * @returns {string}
  7682. */
  7683. getNodeType( builder ) {
  7684. return this.node.getNodeType( builder );
  7685. }
  7686. /**
  7687. * Sets up the inspector node.
  7688. *
  7689. * @param {NodeBuilder} builder - The node builder.
  7690. * @returns {Node} The setup node.
  7691. */
  7692. setup( builder ) {
  7693. let node = this.node;
  7694. if ( builder.context.inspector === true && this.callback !== null ) {
  7695. node = this.callback( node );
  7696. }
  7697. if ( builder.renderer.backend.isWebGPUBackend !== true && builder.renderer.inspector.constructor !== InspectorBase ) {
  7698. warnOnce( 'TSL: ".toInspector()" is only available with WebGPU.' );
  7699. }
  7700. return node;
  7701. }
  7702. }
  7703. /**
  7704. * Creates an inspector node to wrap around a given node for inspection purposes.
  7705. *
  7706. * @tsl
  7707. * @param {Node} node - The node to inspect.
  7708. * @param {string} [name=''] - Optional name for the inspector node.
  7709. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7710. * @returns {Node} The inspector node.
  7711. */
  7712. function inspector( node, name = '', callback = null ) {
  7713. node = nodeObject( node );
  7714. return node.before( new InspectorNode( node, name, callback ) );
  7715. }
  7716. addMethodChaining( 'toInspector', inspector );
  7717. function addNodeElement( name/*, nodeElement*/ ) {
  7718. warn( 'TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  7719. }
  7720. /**
  7721. * Base class for representing shader attributes as nodes.
  7722. *
  7723. * @augments Node
  7724. */
  7725. class AttributeNode extends Node {
  7726. static get type() {
  7727. return 'AttributeNode';
  7728. }
  7729. /**
  7730. * Constructs a new attribute node.
  7731. *
  7732. * @param {string} attributeName - The name of the attribute.
  7733. * @param {?string} nodeType - The node type.
  7734. */
  7735. constructor( attributeName, nodeType = null ) {
  7736. super( nodeType );
  7737. /**
  7738. * `AttributeNode` sets this property to `true` by default.
  7739. *
  7740. * @type {boolean}
  7741. * @default true
  7742. */
  7743. this.global = true;
  7744. this._attributeName = attributeName;
  7745. }
  7746. getHash( builder ) {
  7747. return this.getAttributeName( builder );
  7748. }
  7749. getNodeType( builder ) {
  7750. let nodeType = this.nodeType;
  7751. if ( nodeType === null ) {
  7752. const attributeName = this.getAttributeName( builder );
  7753. if ( builder.hasGeometryAttribute( attributeName ) ) {
  7754. const attribute = builder.geometry.getAttribute( attributeName );
  7755. nodeType = builder.getTypeFromAttribute( attribute );
  7756. } else {
  7757. nodeType = 'float';
  7758. }
  7759. }
  7760. return nodeType;
  7761. }
  7762. /**
  7763. * Sets the attribute name to the given value. The method can be
  7764. * overwritten in derived classes if the final name must be computed
  7765. * analytically.
  7766. *
  7767. * @param {string} attributeName - The name of the attribute.
  7768. * @return {AttributeNode} A reference to this node.
  7769. */
  7770. setAttributeName( attributeName ) {
  7771. this._attributeName = attributeName;
  7772. return this;
  7773. }
  7774. /**
  7775. * Returns the attribute name of this node. The method can be
  7776. * overwritten in derived classes if the final name must be computed
  7777. * analytically.
  7778. *
  7779. * @param {NodeBuilder} builder - The current node builder.
  7780. * @return {string} The attribute name.
  7781. */
  7782. getAttributeName( /*builder*/ ) {
  7783. return this._attributeName;
  7784. }
  7785. generate( builder ) {
  7786. const attributeName = this.getAttributeName( builder );
  7787. const nodeType = this.getNodeType( builder );
  7788. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  7789. if ( geometryAttribute === true ) {
  7790. const attribute = builder.geometry.getAttribute( attributeName );
  7791. const attributeType = builder.getTypeFromAttribute( attribute );
  7792. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  7793. if ( builder.shaderStage === 'vertex' ) {
  7794. return builder.format( nodeAttribute.name, attributeType, nodeType );
  7795. } else {
  7796. const nodeVarying = varying( this );
  7797. return nodeVarying.build( builder, nodeType );
  7798. }
  7799. } else {
  7800. warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  7801. return builder.generateConst( nodeType );
  7802. }
  7803. }
  7804. serialize( data ) {
  7805. super.serialize( data );
  7806. data.global = this.global;
  7807. data._attributeName = this._attributeName;
  7808. }
  7809. deserialize( data ) {
  7810. super.deserialize( data );
  7811. this.global = data.global;
  7812. this._attributeName = data._attributeName;
  7813. }
  7814. }
  7815. /**
  7816. * TSL function for creating an attribute node.
  7817. *
  7818. * @tsl
  7819. * @function
  7820. * @param {string} name - The name of the attribute.
  7821. * @param {?string} [nodeType=null] - The node type.
  7822. * @returns {AttributeNode}
  7823. */
  7824. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  7825. /**
  7826. * TSL function for creating an uv attribute node with the given index.
  7827. *
  7828. * @tsl
  7829. * @function
  7830. * @param {number} [index=0] - The uv index.
  7831. * @return {AttributeNode<vec2>} The uv attribute node.
  7832. */
  7833. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  7834. /**
  7835. * A node that represents the dimensions of a texture. The texture size is
  7836. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  7837. * or `textureSize()`.
  7838. *
  7839. * @augments Node
  7840. */
  7841. class TextureSizeNode extends Node {
  7842. static get type() {
  7843. return 'TextureSizeNode';
  7844. }
  7845. /**
  7846. * Constructs a new texture size node.
  7847. *
  7848. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7849. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7850. */
  7851. constructor( textureNode, levelNode = null ) {
  7852. super( 'uvec2' );
  7853. /**
  7854. * This flag can be used for type testing.
  7855. *
  7856. * @type {boolean}
  7857. * @readonly
  7858. * @default true
  7859. */
  7860. this.isTextureSizeNode = true;
  7861. /**
  7862. * A texture node which size should be retrieved.
  7863. *
  7864. * @type {TextureNode}
  7865. */
  7866. this.textureNode = textureNode;
  7867. /**
  7868. * A level node which defines the requested mip.
  7869. *
  7870. * @type {Node<int>}
  7871. * @default null
  7872. */
  7873. this.levelNode = levelNode;
  7874. }
  7875. generate( builder, output ) {
  7876. const textureProperty = this.textureNode.build( builder, 'property' );
  7877. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  7878. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  7879. }
  7880. }
  7881. /**
  7882. * TSL function for creating a texture size node.
  7883. *
  7884. * @tsl
  7885. * @function
  7886. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7887. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7888. * @returns {TextureSizeNode}
  7889. */
  7890. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  7891. /**
  7892. * A special type of uniform node that computes the
  7893. * maximum mipmap level for a given texture node.
  7894. *
  7895. * ```js
  7896. * const level = maxMipLevel( textureNode );
  7897. * ```
  7898. *
  7899. * @augments UniformNode
  7900. */
  7901. class MaxMipLevelNode extends UniformNode {
  7902. static get type() {
  7903. return 'MaxMipLevelNode';
  7904. }
  7905. /**
  7906. * Constructs a new max mip level node.
  7907. *
  7908. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7909. */
  7910. constructor( textureNode ) {
  7911. super( 0 );
  7912. /**
  7913. * The texture node to compute the max mip level for.
  7914. *
  7915. * @private
  7916. * @type {TextureNode}
  7917. */
  7918. this._textureNode = textureNode;
  7919. /**
  7920. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  7921. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  7922. *
  7923. * @type {string}
  7924. * @default 'frame'
  7925. */
  7926. this.updateType = NodeUpdateType.FRAME;
  7927. }
  7928. /**
  7929. * The texture node to compute the max mip level for.
  7930. *
  7931. * @readonly
  7932. * @type {TextureNode}
  7933. */
  7934. get textureNode() {
  7935. return this._textureNode;
  7936. }
  7937. /**
  7938. * The texture.
  7939. *
  7940. * @readonly
  7941. * @type {Texture}
  7942. */
  7943. get texture() {
  7944. return this._textureNode.value;
  7945. }
  7946. update() {
  7947. const texture = this.texture;
  7948. const images = texture.images;
  7949. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  7950. if ( image && image.width !== undefined ) {
  7951. const { width, height } = image;
  7952. this.value = Math.log2( Math.max( width, height ) );
  7953. }
  7954. }
  7955. }
  7956. /**
  7957. * TSL function for creating a max mip level node.
  7958. *
  7959. * @tsl
  7960. * @function
  7961. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7962. * @returns {MaxMipLevelNode}
  7963. */
  7964. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  7965. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  7966. /**
  7967. * This type of uniform node represents a 2D texture.
  7968. *
  7969. * @augments UniformNode
  7970. */
  7971. class TextureNode extends UniformNode {
  7972. static get type() {
  7973. return 'TextureNode';
  7974. }
  7975. /**
  7976. * Constructs a new texture node.
  7977. *
  7978. * @param {Texture} [value=EmptyTexture] - The texture.
  7979. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7980. * @param {?Node<int>} [levelNode=null] - The level node.
  7981. * @param {?Node<float>} [biasNode=null] - The bias node.
  7982. */
  7983. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  7984. super( value );
  7985. /**
  7986. * This flag can be used for type testing.
  7987. *
  7988. * @type {boolean}
  7989. * @readonly
  7990. * @default true
  7991. */
  7992. this.isTextureNode = true;
  7993. /**
  7994. * Represents the texture coordinates.
  7995. *
  7996. * @type {?Node<vec2|vec3>}
  7997. * @default null
  7998. */
  7999. this.uvNode = uvNode;
  8000. /**
  8001. * Represents the mip level that should be selected.
  8002. *
  8003. * @type {?Node<int>}
  8004. * @default null
  8005. */
  8006. this.levelNode = levelNode;
  8007. /**
  8008. * Represents the bias to be applied during level-of-detail computation.
  8009. *
  8010. * @type {?Node<float>}
  8011. * @default null
  8012. */
  8013. this.biasNode = biasNode;
  8014. /**
  8015. * Represents a reference value a texture sample is compared to.
  8016. *
  8017. * @type {?Node<float>}
  8018. * @default null
  8019. */
  8020. this.compareNode = null;
  8021. /**
  8022. * When using texture arrays, the depth node defines the layer to select.
  8023. *
  8024. * @type {?Node<int>}
  8025. * @default null
  8026. */
  8027. this.depthNode = null;
  8028. /**
  8029. * When defined, a texture is sampled using explicit gradients.
  8030. *
  8031. * @type {?Array<Node<vec2>>}
  8032. * @default null
  8033. */
  8034. this.gradNode = null;
  8035. /**
  8036. * Represents the optional texel offset applied to the unnormalized texture
  8037. * coordinate before sampling the texture.
  8038. *
  8039. * @type {?Node<ivec2|ivec3>}
  8040. * @default null
  8041. */
  8042. this.offsetNode = null;
  8043. /**
  8044. * Whether texture values should be sampled or fetched.
  8045. *
  8046. * @type {boolean}
  8047. * @default true
  8048. */
  8049. this.sampler = true;
  8050. /**
  8051. * Whether the uv transformation matrix should be
  8052. * automatically updated or not. Use `setUpdateMatrix()`
  8053. * if you want to change the value of the property.
  8054. *
  8055. * @type {boolean}
  8056. * @default false
  8057. */
  8058. this.updateMatrix = false;
  8059. /**
  8060. * By default the `update()` method is not executed. Depending on
  8061. * whether a uv transformation matrix and/or flipY is applied, `update()`
  8062. * is executed per object.
  8063. *
  8064. * @type {string}
  8065. * @default 'none'
  8066. */
  8067. this.updateType = NodeUpdateType.NONE;
  8068. /**
  8069. * The reference node.
  8070. *
  8071. * @type {?Node}
  8072. * @default null
  8073. */
  8074. this.referenceNode = null;
  8075. /**
  8076. * The texture value is stored in a private property.
  8077. *
  8078. * @private
  8079. * @type {Texture}
  8080. */
  8081. this._value = value;
  8082. /**
  8083. * The uniform node that represents the uv transformation matrix.
  8084. *
  8085. * @private
  8086. * @type {?UniformNode<mat3>}
  8087. * @default null
  8088. */
  8089. this._matrixUniform = null;
  8090. /**
  8091. * The uniform node that represents the y-flip. Only required for WebGL.
  8092. *
  8093. * @private
  8094. * @type {?UniformNode<bool>}
  8095. * @default null
  8096. */
  8097. this._flipYUniform = null;
  8098. this.setUpdateMatrix( uvNode === null );
  8099. }
  8100. set value( value ) {
  8101. if ( this.referenceNode ) {
  8102. this.referenceNode.value = value;
  8103. } else {
  8104. this._value = value;
  8105. }
  8106. }
  8107. /**
  8108. * The texture value.
  8109. *
  8110. * @type {Texture}
  8111. */
  8112. get value() {
  8113. return this.referenceNode ? this.referenceNode.value : this._value;
  8114. }
  8115. /**
  8116. * Overwritten since the uniform hash is defined by the texture's UUID.
  8117. *
  8118. * @param {NodeBuilder} builder - The current node builder.
  8119. * @return {string} The uniform hash.
  8120. */
  8121. getUniformHash( /*builder*/ ) {
  8122. return this.value.uuid;
  8123. }
  8124. /**
  8125. * Overwritten since the node type is inferred from the texture type.
  8126. *
  8127. * @param {NodeBuilder} builder - The current node builder.
  8128. * @return {string} The node type.
  8129. */
  8130. getNodeType( /*builder*/ ) {
  8131. if ( this.value.isDepthTexture === true ) return 'float';
  8132. if ( this.value.type === UnsignedIntType ) {
  8133. return 'uvec4';
  8134. } else if ( this.value.type === IntType ) {
  8135. return 'ivec4';
  8136. }
  8137. return 'vec4';
  8138. }
  8139. /**
  8140. * Overwrites the default implementation to return a fixed value `'texture'`.
  8141. *
  8142. * @param {NodeBuilder} builder - The current node builder.
  8143. * @return {string} The input type.
  8144. */
  8145. getInputType( /*builder*/ ) {
  8146. return 'texture';
  8147. }
  8148. /**
  8149. * Returns a default uvs based on the current texture's channel.
  8150. *
  8151. * @return {AttributeNode<vec2>} The default uvs.
  8152. */
  8153. getDefaultUV() {
  8154. return uv$1( this.value.channel );
  8155. }
  8156. /**
  8157. * Overwritten to always return the texture reference of the node.
  8158. *
  8159. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  8160. * @return {Texture} The texture reference.
  8161. */
  8162. updateReference( /*state*/ ) {
  8163. return this.value;
  8164. }
  8165. /**
  8166. * Transforms the given uv node with the texture transformation matrix.
  8167. *
  8168. * @param {Node} uvNode - The uv node to transform.
  8169. * @return {Node} The transformed uv node.
  8170. */
  8171. getTransformedUV( uvNode ) {
  8172. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  8173. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  8174. }
  8175. /**
  8176. * Defines whether the uv transformation matrix should automatically be updated or not.
  8177. *
  8178. * @param {boolean} value - The update toggle.
  8179. * @return {TextureNode} A reference to this node.
  8180. */
  8181. setUpdateMatrix( value ) {
  8182. this.updateMatrix = value;
  8183. return this;
  8184. }
  8185. /**
  8186. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  8187. * to modify the uv node for correct sampling.
  8188. *
  8189. * @param {NodeBuilder} builder - The current node builder.
  8190. * @param {Node} uvNode - The uv node to setup.
  8191. * @return {Node} The updated uv node.
  8192. */
  8193. setupUV( builder, uvNode ) {
  8194. if ( builder.isFlipY() ) {
  8195. if ( this._flipYUniform === null ) this._flipYUniform = uniform( false );
  8196. uvNode = uvNode.toVar();
  8197. if ( this.sampler ) {
  8198. uvNode = this._flipYUniform.select( uvNode.flipY(), uvNode );
  8199. } else {
  8200. uvNode = this._flipYUniform.select( uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) ), uvNode );
  8201. }
  8202. }
  8203. return uvNode;
  8204. }
  8205. /**
  8206. * Setups texture node by preparing the internal nodes for code generation.
  8207. *
  8208. * @param {NodeBuilder} builder - The current node builder.
  8209. */
  8210. setup( builder ) {
  8211. const properties = builder.getNodeProperties( this );
  8212. properties.referenceNode = this.referenceNode;
  8213. //
  8214. const texture = this.value;
  8215. if ( ! texture || texture.isTexture !== true ) {
  8216. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  8217. }
  8218. //
  8219. const uvNode = Fn( () => {
  8220. let uvNode = this.uvNode;
  8221. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  8222. uvNode = builder.context.getUV( this, builder );
  8223. }
  8224. if ( ! uvNode ) uvNode = this.getDefaultUV();
  8225. if ( this.updateMatrix === true ) {
  8226. uvNode = this.getTransformedUV( uvNode );
  8227. }
  8228. uvNode = this.setupUV( builder, uvNode );
  8229. //
  8230. this.updateType = ( this._matrixUniform !== null || this._flipYUniform !== null ) ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  8231. //
  8232. return uvNode;
  8233. } )();
  8234. //
  8235. let levelNode = this.levelNode;
  8236. if ( levelNode === null && builder.context.getTextureLevel ) {
  8237. levelNode = builder.context.getTextureLevel( this );
  8238. }
  8239. //
  8240. properties.uvNode = uvNode;
  8241. properties.levelNode = levelNode;
  8242. properties.biasNode = this.biasNode;
  8243. properties.compareNode = this.compareNode;
  8244. properties.gradNode = this.gradNode;
  8245. properties.depthNode = this.depthNode;
  8246. properties.offsetNode = this.offsetNode;
  8247. }
  8248. /**
  8249. * Generates the uv code snippet.
  8250. *
  8251. * @param {NodeBuilder} builder - The current node builder.
  8252. * @param {Node} uvNode - The uv node to generate code for.
  8253. * @return {string} The generated code snippet.
  8254. */
  8255. generateUV( builder, uvNode ) {
  8256. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  8257. }
  8258. /**
  8259. * Generates the offset code snippet.
  8260. *
  8261. * @param {NodeBuilder} builder - The current node builder.
  8262. * @param {Node} offsetNode - The offset node to generate code for.
  8263. * @return {string} The generated code snippet.
  8264. */
  8265. generateOffset( builder, offsetNode ) {
  8266. return offsetNode.build( builder, 'ivec2' );
  8267. }
  8268. /**
  8269. * Generates the snippet for the texture sampling.
  8270. *
  8271. * @param {NodeBuilder} builder - The current node builder.
  8272. * @param {string} textureProperty - The texture property.
  8273. * @param {string} uvSnippet - The uv snippet.
  8274. * @param {?string} levelSnippet - The level snippet.
  8275. * @param {?string} biasSnippet - The bias snippet.
  8276. * @param {?string} depthSnippet - The depth snippet.
  8277. * @param {?string} compareSnippet - The compare snippet.
  8278. * @param {?Array<string>} gradSnippet - The grad snippet.
  8279. * @param {?string} offsetSnippet - The offset snippet.
  8280. * @return {string} The generated code snippet.
  8281. */
  8282. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet ) {
  8283. const texture = this.value;
  8284. let snippet;
  8285. if ( biasSnippet ) {
  8286. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet );
  8287. } else if ( gradSnippet ) {
  8288. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet );
  8289. } else if ( compareSnippet ) {
  8290. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet );
  8291. } else if ( this.sampler === false ) {
  8292. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8293. } else if ( levelSnippet ) {
  8294. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8295. } else {
  8296. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet );
  8297. }
  8298. return snippet;
  8299. }
  8300. /**
  8301. * Generates the code snippet of the texture node.
  8302. *
  8303. * @param {NodeBuilder} builder - The current node builder.
  8304. * @param {string} output - The current output.
  8305. * @return {string} The generated code snippet.
  8306. */
  8307. generate( builder, output ) {
  8308. const texture = this.value;
  8309. const properties = builder.getNodeProperties( this );
  8310. const textureProperty = super.generate( builder, 'property' );
  8311. if ( /^sampler/.test( output ) ) {
  8312. return textureProperty + '_sampler';
  8313. } else if ( builder.isReference( output ) ) {
  8314. return textureProperty;
  8315. } else {
  8316. const nodeData = builder.getDataFromNode( this );
  8317. let propertyName = nodeData.propertyName;
  8318. if ( propertyName === undefined ) {
  8319. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode, offsetNode } = properties;
  8320. const uvSnippet = this.generateUV( builder, uvNode );
  8321. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  8322. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  8323. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  8324. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  8325. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  8326. const offsetSnippet = offsetNode ? this.generateOffset( builder, offsetNode ) : null;
  8327. const nodeVar = builder.getVarFromNode( this );
  8328. propertyName = builder.getPropertyName( nodeVar );
  8329. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet );
  8330. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  8331. nodeData.snippet = snippet;
  8332. nodeData.propertyName = propertyName;
  8333. }
  8334. let snippet = propertyName;
  8335. const nodeType = this.getNodeType( builder );
  8336. if ( builder.needsToWorkingColorSpace( texture ) ) {
  8337. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  8338. }
  8339. return builder.format( snippet, nodeType, output );
  8340. }
  8341. }
  8342. /**
  8343. * Sets the sampler value.
  8344. *
  8345. * @param {boolean} value - The sampler value to set.
  8346. * @return {TextureNode} A reference to this texture node.
  8347. */
  8348. setSampler( value ) {
  8349. this.sampler = value;
  8350. return this;
  8351. }
  8352. /**
  8353. * Returns the sampler value.
  8354. *
  8355. * @return {boolean} The sampler value.
  8356. */
  8357. getSampler() {
  8358. return this.sampler;
  8359. }
  8360. // @TODO: Move to TSL
  8361. /**
  8362. * @function
  8363. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  8364. *
  8365. * @param {Node} uvNode - The uv node.
  8366. * @return {TextureNode} A texture node representing the texture sample.
  8367. */
  8368. uv( uvNode ) { // @deprecated, r172
  8369. warn( 'TextureNode: .uv() has been renamed. Use .sample() instead.' );
  8370. return this.sample( uvNode );
  8371. }
  8372. /**
  8373. * Samples the texture with the given uv node.
  8374. *
  8375. * @param {Node} uvNode - The uv node.
  8376. * @return {TextureNode} A texture node representing the texture sample.
  8377. */
  8378. sample( uvNode ) {
  8379. const textureNode = this.clone();
  8380. textureNode.uvNode = nodeObject( uvNode );
  8381. textureNode.referenceNode = this.getBase();
  8382. return nodeObject( textureNode );
  8383. }
  8384. /**
  8385. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8386. *
  8387. * @param {Node<uvec2>} uvNode - The uv node.
  8388. * @returns {TextureNode} A texture node representing the texture load.
  8389. */
  8390. load( uvNode ) {
  8391. return this.sample( uvNode ).setSampler( false );
  8392. }
  8393. /**
  8394. * Samples a blurred version of the texture by defining an internal bias.
  8395. *
  8396. * @param {Node<float>} amountNode - How blurred the texture should be.
  8397. * @return {TextureNode} A texture node representing the texture sample.
  8398. */
  8399. blur( amountNode ) {
  8400. const textureNode = this.clone();
  8401. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  8402. textureNode.referenceNode = this.getBase();
  8403. const map = textureNode.value;
  8404. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  8405. warn( 'TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  8406. textureNode.biasNode = null;
  8407. }
  8408. return nodeObject( textureNode );
  8409. }
  8410. /**
  8411. * Samples a specific mip of the texture.
  8412. *
  8413. * @param {Node<int>} levelNode - The mip level to sample.
  8414. * @return {TextureNode} A texture node representing the texture sample.
  8415. */
  8416. level( levelNode ) {
  8417. const textureNode = this.clone();
  8418. textureNode.levelNode = nodeObject( levelNode );
  8419. textureNode.referenceNode = this.getBase();
  8420. return nodeObject( textureNode );
  8421. }
  8422. /**
  8423. * Returns the texture size of the requested level.
  8424. *
  8425. * @param {Node<int>} levelNode - The level to compute the size for.
  8426. * @return {TextureSizeNode} The texture size.
  8427. */
  8428. size( levelNode ) {
  8429. return textureSize( this, levelNode );
  8430. }
  8431. /**
  8432. * Samples the texture with the given bias.
  8433. *
  8434. * @param {Node<float>} biasNode - The bias node.
  8435. * @return {TextureNode} A texture node representing the texture sample.
  8436. */
  8437. bias( biasNode ) {
  8438. const textureNode = this.clone();
  8439. textureNode.biasNode = nodeObject( biasNode );
  8440. textureNode.referenceNode = this.getBase();
  8441. return nodeObject( textureNode );
  8442. }
  8443. /**
  8444. * Returns the base texture of this node.
  8445. * @return {TextureNode} The base texture node.
  8446. */
  8447. getBase() {
  8448. return this.referenceNode ? this.referenceNode.getBase() : this;
  8449. }
  8450. /**
  8451. * Samples the texture by executing a compare operation.
  8452. *
  8453. * @param {Node<float>} compareNode - The node that defines the compare value.
  8454. * @return {TextureNode} A texture node representing the texture sample.
  8455. */
  8456. compare( compareNode ) {
  8457. const textureNode = this.clone();
  8458. textureNode.compareNode = nodeObject( compareNode );
  8459. textureNode.referenceNode = this.getBase();
  8460. return nodeObject( textureNode );
  8461. }
  8462. /**
  8463. * Samples the texture using an explicit gradient.
  8464. *
  8465. * @param {Node<vec2>} gradNodeX - The gradX node.
  8466. * @param {Node<vec2>} gradNodeY - The gradY node.
  8467. * @return {TextureNode} A texture node representing the texture sample.
  8468. */
  8469. grad( gradNodeX, gradNodeY ) {
  8470. const textureNode = this.clone();
  8471. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  8472. textureNode.referenceNode = this.getBase();
  8473. return nodeObject( textureNode );
  8474. }
  8475. /**
  8476. * Samples the texture by defining a depth node.
  8477. *
  8478. * @param {Node<int>} depthNode - The depth node.
  8479. * @return {TextureNode} A texture node representing the texture sample.
  8480. */
  8481. depth( depthNode ) {
  8482. const textureNode = this.clone();
  8483. textureNode.depthNode = nodeObject( depthNode );
  8484. textureNode.referenceNode = this.getBase();
  8485. return nodeObject( textureNode );
  8486. }
  8487. /**
  8488. * Samples the texture by defining an offset node.
  8489. *
  8490. * @param {Node<ivec2>} offsetNode - The offset node.
  8491. * @return {TextureNode} A texture node representing the texture sample.
  8492. */
  8493. offset( offsetNode ) {
  8494. const textureNode = this.clone();
  8495. textureNode.offsetNode = nodeObject( offsetNode );
  8496. textureNode.referenceNode = this.getBase();
  8497. return nodeObject( textureNode );
  8498. }
  8499. // --
  8500. serialize( data ) {
  8501. super.serialize( data );
  8502. data.value = this.value.toJSON( data.meta ).uuid;
  8503. data.sampler = this.sampler;
  8504. data.updateMatrix = this.updateMatrix;
  8505. data.updateType = this.updateType;
  8506. }
  8507. deserialize( data ) {
  8508. super.deserialize( data );
  8509. this.value = data.meta.textures[ data.value ];
  8510. this.sampler = data.sampler;
  8511. this.updateMatrix = data.updateMatrix;
  8512. this.updateType = data.updateType;
  8513. }
  8514. /**
  8515. * The update is used to implement the update of the uv transformation matrix.
  8516. */
  8517. update() {
  8518. const texture = this.value;
  8519. const matrixUniform = this._matrixUniform;
  8520. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  8521. if ( texture.matrixAutoUpdate === true ) {
  8522. texture.updateMatrix();
  8523. }
  8524. //
  8525. const flipYUniform = this._flipYUniform;
  8526. if ( flipYUniform !== null ) {
  8527. flipYUniform.value = ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true );
  8528. }
  8529. }
  8530. /**
  8531. * Clones the texture node.
  8532. *
  8533. * @return {TextureNode} The cloned texture node.
  8534. */
  8535. clone() {
  8536. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  8537. newNode.sampler = this.sampler;
  8538. newNode.depthNode = this.depthNode;
  8539. newNode.compareNode = this.compareNode;
  8540. newNode.gradNode = this.gradNode;
  8541. newNode.offsetNode = this.offsetNode;
  8542. return newNode;
  8543. }
  8544. }
  8545. /**
  8546. * TSL function for creating a texture node.
  8547. *
  8548. * @tsl
  8549. * @function
  8550. * @param {?Texture} value - The texture.
  8551. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8552. * @param {?Node<int>} [levelNode=null] - The level node.
  8553. * @param {?Node<float>} [biasNode=null] - The bias node.
  8554. * @returns {TextureNode}
  8555. */
  8556. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  8557. /**
  8558. * TSL function for creating a texture node or sample a texture node already existing.
  8559. *
  8560. * @tsl
  8561. * @function
  8562. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8563. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8564. * @param {?Node<int>} [levelNode=null] - The level node.
  8565. * @param {?Node<float>} [biasNode=null] - The bias node.
  8566. * @returns {TextureNode}
  8567. */
  8568. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  8569. let textureNode;
  8570. if ( value && value.isTextureNode === true ) {
  8571. textureNode = nodeObject( value.clone() );
  8572. textureNode.referenceNode = value.getBase(); // Ensure the reference is set to the original node
  8573. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  8574. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  8575. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  8576. } else {
  8577. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  8578. }
  8579. return textureNode;
  8580. };
  8581. /**
  8582. * TSL function for creating a uniform texture node.
  8583. *
  8584. * @tsl
  8585. * @function
  8586. * @param {?Texture} value - The texture.
  8587. * @returns {TextureNode}
  8588. */
  8589. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  8590. /**
  8591. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8592. *
  8593. * @tsl
  8594. * @function
  8595. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8596. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8597. * @param {?Node<int>} [levelNode=null] - The level node.
  8598. * @param {?Node<float>} [biasNode=null] - The bias node.
  8599. * @returns {TextureNode}
  8600. */
  8601. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  8602. const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  8603. /**
  8604. * Converts a texture or texture node to a sampler.
  8605. *
  8606. * @tsl
  8607. * @function
  8608. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8609. * @returns {Node}
  8610. */
  8611. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  8612. /**
  8613. * Converts a texture or texture node to a sampler comparison.
  8614. *
  8615. * @tsl
  8616. * @function
  8617. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8618. * @returns {Node}
  8619. */
  8620. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  8621. /**
  8622. * A special type of uniform node which represents array-like data
  8623. * as uniform buffers. The access usually happens via `element()`
  8624. * which returns an instance of {@link ArrayElementNode}. For example:
  8625. *
  8626. * ```js
  8627. * const bufferNode = buffer( array, 'mat4', count );
  8628. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  8629. * ```
  8630. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  8631. * since it handles more input types and automatically cares about buffer paddings.
  8632. *
  8633. * @augments UniformNode
  8634. */
  8635. class BufferNode extends UniformNode {
  8636. static get type() {
  8637. return 'BufferNode';
  8638. }
  8639. /**
  8640. * Constructs a new buffer node.
  8641. *
  8642. * @param {Array<number>} value - Array-like buffer data.
  8643. * @param {string} bufferType - The data type of the buffer.
  8644. * @param {number} [bufferCount=0] - The count of buffer elements.
  8645. */
  8646. constructor( value, bufferType, bufferCount = 0 ) {
  8647. super( value, bufferType );
  8648. /**
  8649. * This flag can be used for type testing.
  8650. *
  8651. * @type {boolean}
  8652. * @readonly
  8653. * @default true
  8654. */
  8655. this.isBufferNode = true;
  8656. /**
  8657. * The data type of the buffer.
  8658. *
  8659. * @type {string}
  8660. */
  8661. this.bufferType = bufferType;
  8662. /**
  8663. * The uniform node that holds the value of the reference node.
  8664. *
  8665. * @type {number}
  8666. * @default 0
  8667. */
  8668. this.bufferCount = bufferCount;
  8669. }
  8670. /**
  8671. * The data type of the buffer elements.
  8672. *
  8673. * @param {NodeBuilder} builder - The current node builder.
  8674. * @return {string} The element type.
  8675. */
  8676. getElementType( builder ) {
  8677. return this.getNodeType( builder );
  8678. }
  8679. /**
  8680. * Overwrites the default implementation to return a fixed value `'buffer'`.
  8681. *
  8682. * @param {NodeBuilder} builder - The current node builder.
  8683. * @return {string} The input type.
  8684. */
  8685. getInputType( /*builder*/ ) {
  8686. return 'buffer';
  8687. }
  8688. }
  8689. /**
  8690. * TSL function for creating a buffer node.
  8691. *
  8692. * @tsl
  8693. * @function
  8694. * @param {Array<number>} value - Array-like buffer data.
  8695. * @param {string} type - The data type of a buffer element.
  8696. * @param {number} count - The count of buffer elements.
  8697. * @returns {BufferNode}
  8698. */
  8699. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  8700. /**
  8701. * Represents the element access on uniform array nodes.
  8702. *
  8703. * @augments ArrayElementNode
  8704. */
  8705. class UniformArrayElementNode extends ArrayElementNode {
  8706. static get type() {
  8707. return 'UniformArrayElementNode';
  8708. }
  8709. /**
  8710. * Constructs a new buffer node.
  8711. *
  8712. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  8713. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  8714. */
  8715. constructor( uniformArrayNode, indexNode ) {
  8716. super( uniformArrayNode, indexNode );
  8717. /**
  8718. * This flag can be used for type testing.
  8719. *
  8720. * @type {boolean}
  8721. * @readonly
  8722. * @default true
  8723. */
  8724. this.isArrayBufferElementNode = true;
  8725. }
  8726. generate( builder ) {
  8727. const snippet = super.generate( builder );
  8728. const type = this.getNodeType();
  8729. const paddedType = this.node.getPaddedType();
  8730. return builder.format( snippet, paddedType, type );
  8731. }
  8732. }
  8733. /**
  8734. * Similar to {@link BufferNode} this module represents array-like data as
  8735. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  8736. * data types in the array (e.g `three.js` primitives) and automatically
  8737. * manage buffer padding. It should be the first choice when working with
  8738. * uniforms buffers.
  8739. * ```js
  8740. * const tintColors = uniformArray( [
  8741. * new Color( 1, 0, 0 ),
  8742. * new Color( 0, 1, 0 ),
  8743. * new Color( 0, 0, 1 )
  8744. * ], 'color' );
  8745. *
  8746. * const redColor = tintColors.element( 0 );
  8747. *
  8748. * @augments BufferNode
  8749. */
  8750. class UniformArrayNode extends BufferNode {
  8751. static get type() {
  8752. return 'UniformArrayNode';
  8753. }
  8754. /**
  8755. * Constructs a new uniform array node.
  8756. *
  8757. * @param {Array<any>} value - Array holding the buffer data.
  8758. * @param {?string} [elementType=null] - The data type of a buffer element.
  8759. */
  8760. constructor( value, elementType = null ) {
  8761. super( null );
  8762. /**
  8763. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  8764. * hold number primitives as well as three.js objects like vectors, matrices
  8765. * or colors.
  8766. *
  8767. * @type {Array<any>}
  8768. */
  8769. this.array = value;
  8770. /**
  8771. * The data type of an array element.
  8772. *
  8773. * @type {string}
  8774. */
  8775. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  8776. /**
  8777. * The padded type. Uniform buffers must conform to a certain buffer layout
  8778. * so a separate type is computed to ensure correct buffer size.
  8779. *
  8780. * @type {string}
  8781. */
  8782. this.paddedType = this.getPaddedType();
  8783. /**
  8784. * Overwritten since uniform array nodes are updated per render.
  8785. *
  8786. * @type {string}
  8787. * @default 'render'
  8788. */
  8789. this.updateType = NodeUpdateType.RENDER;
  8790. /**
  8791. * This flag can be used for type testing.
  8792. *
  8793. * @type {boolean}
  8794. * @readonly
  8795. * @default true
  8796. */
  8797. this.isArrayBufferNode = true;
  8798. }
  8799. /**
  8800. * This method is overwritten since the node type is inferred from the
  8801. * {@link UniformArrayNode#paddedType}.
  8802. *
  8803. * @param {NodeBuilder} builder - The current node builder.
  8804. * @return {string} The node type.
  8805. */
  8806. getNodeType( /*builder*/ ) {
  8807. return this.paddedType;
  8808. }
  8809. /**
  8810. * The data type of the array elements.
  8811. *
  8812. * @param {NodeBuilder} builder - The current node builder.
  8813. * @return {string} The element type.
  8814. */
  8815. getElementType() {
  8816. return this.elementType;
  8817. }
  8818. /**
  8819. * Returns the padded type based on the element type.
  8820. *
  8821. * @return {string} The padded type.
  8822. */
  8823. getPaddedType() {
  8824. const elementType = this.elementType;
  8825. let paddedType = 'vec4';
  8826. if ( elementType === 'mat2' ) {
  8827. paddedType = 'mat2';
  8828. } else if ( /mat/.test( elementType ) === true ) {
  8829. paddedType = 'mat4';
  8830. } else if ( elementType.charAt( 0 ) === 'i' ) {
  8831. paddedType = 'ivec4';
  8832. } else if ( elementType.charAt( 0 ) === 'u' ) {
  8833. paddedType = 'uvec4';
  8834. }
  8835. return paddedType;
  8836. }
  8837. /**
  8838. * The update makes sure to correctly transfer the data from the (complex) objects
  8839. * in the array to the internal, correctly padded value buffer.
  8840. *
  8841. * @param {NodeFrame} frame - A reference to the current node frame.
  8842. */
  8843. update( /*frame*/ ) {
  8844. const { array, value } = this;
  8845. const elementType = this.elementType;
  8846. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  8847. for ( let i = 0; i < array.length; i ++ ) {
  8848. const index = i * 4;
  8849. value[ index ] = array[ i ];
  8850. }
  8851. } else if ( elementType === 'color' ) {
  8852. for ( let i = 0; i < array.length; i ++ ) {
  8853. const index = i * 4;
  8854. const vector = array[ i ];
  8855. value[ index ] = vector.r;
  8856. value[ index + 1 ] = vector.g;
  8857. value[ index + 2 ] = vector.b || 0;
  8858. //value[ index + 3 ] = vector.a || 0;
  8859. }
  8860. } else if ( elementType === 'mat2' ) {
  8861. for ( let i = 0; i < array.length; i ++ ) {
  8862. const index = i * 4;
  8863. const matrix = array[ i ];
  8864. value[ index ] = matrix.elements[ 0 ];
  8865. value[ index + 1 ] = matrix.elements[ 1 ];
  8866. value[ index + 2 ] = matrix.elements[ 2 ];
  8867. value[ index + 3 ] = matrix.elements[ 3 ];
  8868. }
  8869. } else if ( elementType === 'mat3' ) {
  8870. for ( let i = 0; i < array.length; i ++ ) {
  8871. const index = i * 16;
  8872. const matrix = array[ i ];
  8873. value[ index ] = matrix.elements[ 0 ];
  8874. value[ index + 1 ] = matrix.elements[ 1 ];
  8875. value[ index + 2 ] = matrix.elements[ 2 ];
  8876. value[ index + 4 ] = matrix.elements[ 3 ];
  8877. value[ index + 5 ] = matrix.elements[ 4 ];
  8878. value[ index + 6 ] = matrix.elements[ 5 ];
  8879. value[ index + 8 ] = matrix.elements[ 6 ];
  8880. value[ index + 9 ] = matrix.elements[ 7 ];
  8881. value[ index + 10 ] = matrix.elements[ 8 ];
  8882. value[ index + 15 ] = 1;
  8883. }
  8884. } else if ( elementType === 'mat4' ) {
  8885. for ( let i = 0; i < array.length; i ++ ) {
  8886. const index = i * 16;
  8887. const matrix = array[ i ];
  8888. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  8889. value[ index + i ] = matrix.elements[ i ];
  8890. }
  8891. }
  8892. } else {
  8893. for ( let i = 0; i < array.length; i ++ ) {
  8894. const index = i * 4;
  8895. const vector = array[ i ];
  8896. value[ index ] = vector.x;
  8897. value[ index + 1 ] = vector.y;
  8898. value[ index + 2 ] = vector.z || 0;
  8899. value[ index + 3 ] = vector.w || 0;
  8900. }
  8901. }
  8902. }
  8903. /**
  8904. * Implement the value buffer creation based on the array data.
  8905. *
  8906. * @param {NodeBuilder} builder - A reference to the current node builder.
  8907. * @return {null}
  8908. */
  8909. setup( builder ) {
  8910. const length = this.array.length;
  8911. const elementType = this.elementType;
  8912. let arrayType = Float32Array;
  8913. const paddedType = this.paddedType;
  8914. const paddedElementLength = builder.getTypeLength( paddedType );
  8915. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  8916. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  8917. this.value = new arrayType( length * paddedElementLength );
  8918. this.bufferCount = length;
  8919. this.bufferType = paddedType;
  8920. return super.setup( builder );
  8921. }
  8922. /**
  8923. * Overwrites the default `element()` method to provide element access
  8924. * based on {@link UniformArrayNode}.
  8925. *
  8926. * @param {IndexNode} indexNode - The index node.
  8927. * @return {UniformArrayElementNode}
  8928. */
  8929. element( indexNode ) {
  8930. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  8931. }
  8932. }
  8933. /**
  8934. * TSL function for creating an uniform array node.
  8935. *
  8936. * @tsl
  8937. * @function
  8938. * @param {Array<any>} values - Array-like data.
  8939. * @param {?string} [nodeType] - The data type of the array elements.
  8940. * @returns {UniformArrayNode}
  8941. */
  8942. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  8943. /**
  8944. * The node allows to set values for built-in shader variables. That is
  8945. * required for features like hardware-accelerated vertex clipping.
  8946. *
  8947. * @augments Node
  8948. */
  8949. class BuiltinNode extends Node {
  8950. /**
  8951. * Constructs a new builtin node.
  8952. *
  8953. * @param {string} name - The name of the built-in shader variable.
  8954. */
  8955. constructor( name ) {
  8956. super( 'float' );
  8957. /**
  8958. * The name of the built-in shader variable.
  8959. *
  8960. * @type {string}
  8961. */
  8962. this.name = name;
  8963. /**
  8964. * This flag can be used for type testing.
  8965. *
  8966. * @type {boolean}
  8967. * @readonly
  8968. * @default true
  8969. */
  8970. this.isBuiltinNode = true;
  8971. }
  8972. /**
  8973. * Generates the code snippet of the builtin node.
  8974. *
  8975. * @param {NodeBuilder} builder - The current node builder.
  8976. * @return {string} The generated code snippet.
  8977. */
  8978. generate( /* builder */ ) {
  8979. return this.name;
  8980. }
  8981. }
  8982. /**
  8983. * TSL function for creating a builtin node.
  8984. *
  8985. * @tsl
  8986. * @function
  8987. * @param {string} name - The name of the built-in shader variable.
  8988. * @returns {BuiltinNode}
  8989. */
  8990. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  8991. let _screenSizeVec, _viewportVec;
  8992. /**
  8993. * This node provides a collection of screen related metrics.
  8994. * Depending on {@link ScreenNode#scope}, the nodes can represent
  8995. * resolution or viewport data as well as fragment or uv coordinates.
  8996. *
  8997. * @augments Node
  8998. */
  8999. class ScreenNode extends Node {
  9000. static get type() {
  9001. return 'ScreenNode';
  9002. }
  9003. /**
  9004. * Constructs a new screen node.
  9005. *
  9006. * @param {('coordinate'|'viewport'|'size'|'uv'|'dpr')} scope - The node's scope.
  9007. */
  9008. constructor( scope ) {
  9009. super();
  9010. /**
  9011. * The node represents different metric depending on which scope is selected.
  9012. *
  9013. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  9014. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  9015. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  9016. * - `ScreenNode.UV`: Normalized coordinates.
  9017. * - `ScreenNode.DPR`: Device pixel ratio.
  9018. *
  9019. * @type {('coordinate'|'viewport'|'size'|'uv'|'dpr')}
  9020. */
  9021. this.scope = scope;
  9022. /**
  9023. * This output node.
  9024. *
  9025. * @type {?Node}
  9026. * @default null
  9027. */
  9028. this._output = null;
  9029. /**
  9030. * This flag can be used for type testing.
  9031. *
  9032. * @type {boolean}
  9033. * @readonly
  9034. * @default true
  9035. */
  9036. this.isViewportNode = true;
  9037. }
  9038. /**
  9039. * This method is overwritten since the node type depends on the selected scope.
  9040. *
  9041. * @return {('float'|'vec2'|'vec4')} The node type.
  9042. */
  9043. getNodeType() {
  9044. if ( this.scope === ScreenNode.DPR ) return 'float';
  9045. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  9046. else return 'vec2';
  9047. }
  9048. /**
  9049. * This method is overwritten since the node's update type depends on the selected scope.
  9050. *
  9051. * @return {NodeUpdateType} The update type.
  9052. */
  9053. getUpdateType() {
  9054. let updateType = NodeUpdateType.NONE;
  9055. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT || this.scope === ScreenNode.DPR ) {
  9056. updateType = NodeUpdateType.RENDER;
  9057. }
  9058. this.updateType = updateType;
  9059. return updateType;
  9060. }
  9061. /**
  9062. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  9063. * from the current renderer.
  9064. *
  9065. * @param {NodeFrame} frame - A reference to the current node frame.
  9066. */
  9067. update( { renderer } ) {
  9068. const renderTarget = renderer.getRenderTarget();
  9069. if ( this.scope === ScreenNode.VIEWPORT ) {
  9070. if ( renderTarget !== null ) {
  9071. _viewportVec.copy( renderTarget.viewport );
  9072. } else {
  9073. renderer.getViewport( _viewportVec );
  9074. _viewportVec.multiplyScalar( renderer.getPixelRatio() );
  9075. }
  9076. } else if ( this.scope === ScreenNode.DPR ) {
  9077. this._output.value = renderer.getPixelRatio();
  9078. } else {
  9079. if ( renderTarget !== null ) {
  9080. _screenSizeVec.width = renderTarget.width;
  9081. _screenSizeVec.height = renderTarget.height;
  9082. } else {
  9083. renderer.getDrawingBufferSize( _screenSizeVec );
  9084. }
  9085. }
  9086. }
  9087. setup( /*builder*/ ) {
  9088. const scope = this.scope;
  9089. let output = null;
  9090. if ( scope === ScreenNode.SIZE ) {
  9091. output = uniform( _screenSizeVec || ( _screenSizeVec = new Vector2() ) );
  9092. } else if ( scope === ScreenNode.VIEWPORT ) {
  9093. output = uniform( _viewportVec || ( _viewportVec = new Vector4() ) );
  9094. } else if ( scope === ScreenNode.DPR ) {
  9095. output = uniform( 1 );
  9096. } else {
  9097. output = vec2( screenCoordinate.div( screenSize ) );
  9098. }
  9099. this._output = output;
  9100. return output;
  9101. }
  9102. generate( builder ) {
  9103. if ( this.scope === ScreenNode.COORDINATE ) {
  9104. let coord = builder.getFragCoord();
  9105. if ( builder.isFlipY() ) {
  9106. // follow webgpu standards
  9107. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  9108. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  9109. }
  9110. return coord;
  9111. }
  9112. return super.generate( builder );
  9113. }
  9114. }
  9115. ScreenNode.COORDINATE = 'coordinate';
  9116. ScreenNode.VIEWPORT = 'viewport';
  9117. ScreenNode.SIZE = 'size';
  9118. ScreenNode.UV = 'uv';
  9119. ScreenNode.DPR = 'dpr';
  9120. // Screen
  9121. /**
  9122. * TSL object that represents the current DPR.
  9123. *
  9124. * @tsl
  9125. * @type {ScreenNode<float>}
  9126. */
  9127. const screenDPR = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.DPR );
  9128. /**
  9129. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  9130. *
  9131. * @tsl
  9132. * @type {ScreenNode<vec2>}
  9133. */
  9134. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  9135. /**
  9136. * TSL object that represents the screen resolution in physical pixel units.
  9137. *
  9138. * @tsl
  9139. * @type {ScreenNode<vec2>}
  9140. */
  9141. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  9142. /**
  9143. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  9144. *
  9145. * @tsl
  9146. * @type {ScreenNode<vec2>}
  9147. */
  9148. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  9149. // Viewport
  9150. /**
  9151. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  9152. *
  9153. * @tsl
  9154. * @type {ScreenNode<vec4>}
  9155. */
  9156. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  9157. /**
  9158. * TSL object that represents the viewport resolution in physical pixel units.
  9159. *
  9160. * @tsl
  9161. * @type {ScreenNode<vec2>}
  9162. */
  9163. const viewportSize = viewport.zw;
  9164. /**
  9165. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  9166. *
  9167. * @tsl
  9168. * @type {ScreenNode<vec2>}
  9169. */
  9170. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  9171. /**
  9172. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  9173. *
  9174. * @tsl
  9175. * @type {ScreenNode<vec2>}
  9176. */
  9177. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  9178. // Deprecated
  9179. /**
  9180. * @deprecated since r169. Use {@link screenSize} instead.
  9181. */
  9182. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  9183. warn( 'TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  9184. return screenSize;
  9185. }, 'vec2' ).once() )();
  9186. /**
  9187. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  9188. *
  9189. * @tsl
  9190. * @type {UniformNode<uint>}
  9191. */
  9192. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  9193. /**
  9194. * TSL object that represents the `near` value of the camera used for the current render.
  9195. *
  9196. * @tsl
  9197. * @type {UniformNode<float>}
  9198. */
  9199. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  9200. /**
  9201. * TSL object that represents the `far` value of the camera used for the current render.
  9202. *
  9203. * @tsl
  9204. * @type {UniformNode<float>}
  9205. */
  9206. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  9207. /**
  9208. * TSL object that represents the projection matrix of the camera used for the current render.
  9209. *
  9210. * @tsl
  9211. * @type {UniformNode<mat4>}
  9212. */
  9213. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9214. let cameraProjectionMatrix;
  9215. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9216. const matrices = [];
  9217. for ( const subCamera of camera.cameras ) {
  9218. matrices.push( subCamera.projectionMatrix );
  9219. }
  9220. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  9221. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrix' );
  9222. } else {
  9223. cameraProjectionMatrix = uniform( 'mat4' ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  9224. }
  9225. return cameraProjectionMatrix;
  9226. } ).once() )();
  9227. /**
  9228. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  9229. *
  9230. * @tsl
  9231. * @type {UniformNode<mat4>}
  9232. */
  9233. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9234. let cameraProjectionMatrixInverse;
  9235. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9236. const matrices = [];
  9237. for ( const subCamera of camera.cameras ) {
  9238. matrices.push( subCamera.projectionMatrixInverse );
  9239. }
  9240. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  9241. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrixInverse' );
  9242. } else {
  9243. cameraProjectionMatrixInverse = uniform( 'mat4' ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  9244. }
  9245. return cameraProjectionMatrixInverse;
  9246. } ).once() )();
  9247. /**
  9248. * TSL object that represents the view matrix of the camera used for the current render.
  9249. *
  9250. * @tsl
  9251. * @type {UniformNode<mat4>}
  9252. */
  9253. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9254. let cameraViewMatrix;
  9255. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9256. const matrices = [];
  9257. for ( const subCamera of camera.cameras ) {
  9258. matrices.push( subCamera.matrixWorldInverse );
  9259. }
  9260. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  9261. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraViewMatrix' );
  9262. } else {
  9263. cameraViewMatrix = uniform( 'mat4' ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  9264. }
  9265. return cameraViewMatrix;
  9266. } ).once() )();
  9267. /**
  9268. * TSL object that represents the world matrix of the camera used for the current render.
  9269. *
  9270. * @tsl
  9271. * @type {UniformNode<mat4>}
  9272. */
  9273. const cameraWorldMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9274. let cameraWorldMatrix;
  9275. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9276. const matrices = [];
  9277. for ( const subCamera of camera.cameras ) {
  9278. matrices.push( subCamera.matrixWorld );
  9279. }
  9280. const cameraWorldMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraWorldMatrices' );
  9281. cameraWorldMatrix = cameraWorldMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraWorldMatrix' );
  9282. } else {
  9283. cameraWorldMatrix = uniform( 'mat4' ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  9284. }
  9285. return cameraWorldMatrix;
  9286. } ).once() )();
  9287. /**
  9288. * TSL object that represents the normal matrix of the camera used for the current render.
  9289. *
  9290. * @tsl
  9291. * @type {UniformNode<mat3>}
  9292. */
  9293. const cameraNormalMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9294. let cameraNormalMatrix;
  9295. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9296. const matrices = [];
  9297. for ( const subCamera of camera.cameras ) {
  9298. matrices.push( subCamera.normalMatrix );
  9299. }
  9300. const cameraNormalMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraNormalMatrices' );
  9301. cameraNormalMatrix = cameraNormalMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraNormalMatrix' );
  9302. } else {
  9303. cameraNormalMatrix = uniform( 'mat3' ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  9304. }
  9305. return cameraNormalMatrix;
  9306. } ).once() )();
  9307. /**
  9308. * TSL object that represents the position in world space of the camera used for the current render.
  9309. *
  9310. * @tsl
  9311. * @type {UniformNode<vec3>}
  9312. */
  9313. const cameraPosition = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9314. let cameraPosition;
  9315. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9316. const positions = [];
  9317. for ( let i = 0, l = camera.cameras.length; i < l; i ++ ) {
  9318. positions.push( new Vector3() );
  9319. }
  9320. const cameraPositions = uniformArray( positions ).setGroup( renderGroup ).setName( 'cameraPositions' ).onRenderUpdate( ( { camera }, self ) => {
  9321. const subCameras = camera.cameras;
  9322. const array = self.array;
  9323. for ( let i = 0, l = subCameras.length; i < l; i ++ ) {
  9324. array[ i ].setFromMatrixPosition( subCameras[ i ].matrixWorld );
  9325. }
  9326. } );
  9327. cameraPosition = cameraPositions.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraPosition' );
  9328. } else {
  9329. cameraPosition = uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  9330. }
  9331. return cameraPosition;
  9332. } ).once() )();
  9333. /**
  9334. * TSL object that represents the viewport of the camera used for the current render.
  9335. *
  9336. * @tsl
  9337. * @type {UniformNode<vec4>}
  9338. */
  9339. const cameraViewport = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9340. let cameraViewport;
  9341. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9342. const viewports = [];
  9343. for ( const subCamera of camera.cameras ) {
  9344. viewports.push( subCamera.viewport );
  9345. }
  9346. const cameraViewports = uniformArray( viewports, 'vec4' ).setGroup( renderGroup ).setName( 'cameraViewports' );
  9347. cameraViewport = cameraViewports.element( cameraIndex ).toConst( 'cameraViewport' );
  9348. } else {
  9349. // Fallback for single camera
  9350. cameraViewport = vec4( 0, 0, screenSize.x, screenSize.y ).toConst( 'cameraViewport' );
  9351. }
  9352. return cameraViewport;
  9353. } ).once() )();
  9354. const _sphere = /*@__PURE__*/ new Sphere();
  9355. /**
  9356. * This node can be used to access transformation related metrics of 3D objects.
  9357. * Depending on the selected scope, a different metric is represented as a uniform
  9358. * in the shader. The following scopes are supported:
  9359. *
  9360. * - `POSITION`: The object's position in world space.
  9361. * - `VIEW_POSITION`: The object's position in view/camera space.
  9362. * - `DIRECTION`: The object's direction in world space.
  9363. * - `SCALE`: The object's scale in world space.
  9364. * - `WORLD_MATRIX`: The object's matrix in world space.
  9365. *
  9366. * @augments Node
  9367. */
  9368. class Object3DNode extends Node {
  9369. static get type() {
  9370. return 'Object3DNode';
  9371. }
  9372. /**
  9373. * Constructs a new object 3D node.
  9374. *
  9375. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9376. * @param {?Object3D} [object3d=null] - The 3D object.
  9377. */
  9378. constructor( scope, object3d = null ) {
  9379. super();
  9380. /**
  9381. * The node reports a different type of transformation depending on the scope.
  9382. *
  9383. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  9384. */
  9385. this.scope = scope;
  9386. /**
  9387. * The 3D object.
  9388. *
  9389. * @type {?Object3D}
  9390. * @default null
  9391. */
  9392. this.object3d = object3d;
  9393. /**
  9394. * Overwritten since this type of node is updated per object.
  9395. *
  9396. * @type {string}
  9397. * @default 'object'
  9398. */
  9399. this.updateType = NodeUpdateType.OBJECT;
  9400. /**
  9401. * Holds the value of the node as a uniform.
  9402. *
  9403. * @type {UniformNode}
  9404. */
  9405. this.uniformNode = new UniformNode( null );
  9406. }
  9407. /**
  9408. * Overwritten since the node type is inferred from the scope.
  9409. *
  9410. * @return {('mat4'|'vec3'|'float')} The node type.
  9411. */
  9412. getNodeType() {
  9413. const scope = this.scope;
  9414. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9415. return 'mat4';
  9416. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9417. return 'vec3';
  9418. } else if ( scope === Object3DNode.RADIUS ) {
  9419. return 'float';
  9420. }
  9421. }
  9422. /**
  9423. * Updates the uniform value depending on the scope.
  9424. *
  9425. * @param {NodeFrame} frame - The current node frame.
  9426. */
  9427. update( frame ) {
  9428. const object = this.object3d;
  9429. const uniformNode = this.uniformNode;
  9430. const scope = this.scope;
  9431. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9432. uniformNode.value = object.matrixWorld;
  9433. } else if ( scope === Object3DNode.POSITION ) {
  9434. uniformNode.value = uniformNode.value || new Vector3();
  9435. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9436. } else if ( scope === Object3DNode.SCALE ) {
  9437. uniformNode.value = uniformNode.value || new Vector3();
  9438. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  9439. } else if ( scope === Object3DNode.DIRECTION ) {
  9440. uniformNode.value = uniformNode.value || new Vector3();
  9441. object.getWorldDirection( uniformNode.value );
  9442. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  9443. const camera = frame.camera;
  9444. uniformNode.value = uniformNode.value || new Vector3();
  9445. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9446. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  9447. } else if ( scope === Object3DNode.RADIUS ) {
  9448. const geometry = frame.object.geometry;
  9449. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9450. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  9451. uniformNode.value = _sphere.radius;
  9452. }
  9453. }
  9454. /**
  9455. * Generates the code snippet of the uniform node. The node type of the uniform
  9456. * node also depends on the selected scope.
  9457. *
  9458. * @param {NodeBuilder} builder - The current node builder.
  9459. * @return {string} The generated code snippet.
  9460. */
  9461. generate( builder ) {
  9462. const scope = this.scope;
  9463. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9464. this.uniformNode.nodeType = 'mat4';
  9465. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9466. this.uniformNode.nodeType = 'vec3';
  9467. } else if ( scope === Object3DNode.RADIUS ) {
  9468. this.uniformNode.nodeType = 'float';
  9469. }
  9470. return this.uniformNode.build( builder );
  9471. }
  9472. serialize( data ) {
  9473. super.serialize( data );
  9474. data.scope = this.scope;
  9475. }
  9476. deserialize( data ) {
  9477. super.deserialize( data );
  9478. this.scope = data.scope;
  9479. }
  9480. }
  9481. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  9482. Object3DNode.POSITION = 'position';
  9483. Object3DNode.SCALE = 'scale';
  9484. Object3DNode.VIEW_POSITION = 'viewPosition';
  9485. Object3DNode.DIRECTION = 'direction';
  9486. Object3DNode.RADIUS = 'radius';
  9487. /**
  9488. * TSL function for creating an object 3D node that represents the object's direction in world space.
  9489. *
  9490. * @tsl
  9491. * @function
  9492. * @param {?Object3D} [object3d] - The 3D object.
  9493. * @returns {Object3DNode<vec3>}
  9494. */
  9495. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  9496. /**
  9497. * TSL function for creating an object 3D node that represents the object's world matrix.
  9498. *
  9499. * @tsl
  9500. * @function
  9501. * @param {?Object3D} [object3d] - The 3D object.
  9502. * @returns {Object3DNode<mat4>}
  9503. */
  9504. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  9505. /**
  9506. * TSL function for creating an object 3D node that represents the object's position in world space.
  9507. *
  9508. * @tsl
  9509. * @function
  9510. * @param {?Object3D} [object3d] - The 3D object.
  9511. * @returns {Object3DNode<vec3>}
  9512. */
  9513. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  9514. /**
  9515. * TSL function for creating an object 3D node that represents the object's scale in world space.
  9516. *
  9517. * @tsl
  9518. * @function
  9519. * @param {?Object3D} [object3d] - The 3D object.
  9520. * @returns {Object3DNode<vec3>}
  9521. */
  9522. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  9523. /**
  9524. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  9525. *
  9526. * @tsl
  9527. * @function
  9528. * @param {?Object3D} [object3d] - The 3D object.
  9529. * @returns {Object3DNode<vec3>}
  9530. */
  9531. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  9532. /**
  9533. * TSL function for creating an object 3D node that represents the object's radius.
  9534. *
  9535. * @tsl
  9536. * @function
  9537. * @param {?Object3D} [object3d] - The 3D object.
  9538. * @returns {Object3DNode<float>}
  9539. */
  9540. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  9541. /**
  9542. * This type of node is a specialized version of `Object3DNode`
  9543. * with larger set of model related metrics. Unlike `Object3DNode`,
  9544. * `ModelNode` extracts the reference to the 3D object from the
  9545. * current node frame state.
  9546. *
  9547. * @augments Object3DNode
  9548. */
  9549. class ModelNode extends Object3DNode {
  9550. static get type() {
  9551. return 'ModelNode';
  9552. }
  9553. /**
  9554. * Constructs a new object model node.
  9555. *
  9556. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9557. */
  9558. constructor( scope ) {
  9559. super( scope );
  9560. }
  9561. /**
  9562. * Extracts the model reference from the frame state and then
  9563. * updates the uniform value depending on the scope.
  9564. *
  9565. * @param {NodeFrame} frame - The current node frame.
  9566. */
  9567. update( frame ) {
  9568. this.object3d = frame.object;
  9569. super.update( frame );
  9570. }
  9571. }
  9572. /**
  9573. * TSL object that represents the object's direction in world space.
  9574. *
  9575. * @tsl
  9576. * @type {ModelNode<vec3>}
  9577. */
  9578. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  9579. /**
  9580. * TSL object that represents the object's world matrix.
  9581. *
  9582. * @tsl
  9583. * @type {ModelNode<mat4>}
  9584. */
  9585. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  9586. /**
  9587. * TSL object that represents the object's position in world space.
  9588. *
  9589. * @tsl
  9590. * @type {ModelNode<vec3>}
  9591. */
  9592. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  9593. /**
  9594. * TSL object that represents the object's scale in world space.
  9595. *
  9596. * @tsl
  9597. * @type {ModelNode<vec3>}
  9598. */
  9599. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  9600. /**
  9601. * TSL object that represents the object's position in view/camera space.
  9602. *
  9603. * @tsl
  9604. * @type {ModelNode<vec3>}
  9605. */
  9606. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  9607. /**
  9608. * TSL object that represents the object's radius.
  9609. *
  9610. * @tsl
  9611. * @type {ModelNode<float>}
  9612. */
  9613. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  9614. /**
  9615. * TSL object that represents the object's normal matrix.
  9616. *
  9617. * @tsl
  9618. * @type {UniformNode<mat3>}
  9619. */
  9620. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  9621. /**
  9622. * TSL object that represents the object's inverse world matrix.
  9623. *
  9624. * @tsl
  9625. * @type {UniformNode<mat4>}
  9626. */
  9627. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  9628. /**
  9629. * TSL object that represents the object's model view matrix.
  9630. *
  9631. * @tsl
  9632. * @type {Node<mat4>}
  9633. */
  9634. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9635. return builder.renderer.overrideNodes.modelViewMatrix || mediumpModelViewMatrix;
  9636. } ).once() )().toVar( 'modelViewMatrix' );
  9637. // GPU Precision
  9638. /**
  9639. * TSL object that represents the object's model view in `mediump` precision.
  9640. *
  9641. * @tsl
  9642. * @type {Node<mat4>}
  9643. */
  9644. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  9645. // CPU Precision
  9646. /**
  9647. * TSL object that represents the object's model view in `highp` precision
  9648. * which is achieved by computing the matrix in JS and not in the shader.
  9649. *
  9650. * @tsl
  9651. * @type {Node<mat4>}
  9652. */
  9653. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9654. builder.context.isHighPrecisionModelViewMatrix = true;
  9655. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  9656. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9657. } );
  9658. } ).once() )().toVar( 'highpModelViewMatrix' );
  9659. /**
  9660. * TSL object that represents the object's model normal view in `highp` precision
  9661. * which is achieved by computing the matrix in JS and not in the shader.
  9662. *
  9663. * @tsl
  9664. * @type {Node<mat3>}
  9665. */
  9666. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9667. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  9668. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  9669. if ( isHighPrecisionModelViewMatrix !== true ) {
  9670. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9671. }
  9672. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  9673. } );
  9674. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  9675. /**
  9676. * TSL object that represents the position attribute of the current rendered object.
  9677. *
  9678. * @tsl
  9679. * @type {AttributeNode<vec3>}
  9680. */
  9681. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  9682. /**
  9683. * TSL object that represents the vertex position in local space of the current rendered object.
  9684. *
  9685. * @tsl
  9686. * @type {AttributeNode<vec3>}
  9687. */
  9688. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  9689. /**
  9690. * TSL object that represents the previous vertex position in local space of the current rendered object.
  9691. * Used in context of {@link VelocityNode} for rendering motion vectors.
  9692. *
  9693. * @tsl
  9694. * @type {AttributeNode<vec3>}
  9695. */
  9696. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  9697. /**
  9698. * TSL object that represents the vertex position in world space of the current rendered object.
  9699. *
  9700. * @tsl
  9701. * @type {VaryingNode<vec3>}
  9702. */
  9703. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  9704. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  9705. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9706. /**
  9707. * TSL object that represents the position world direction of the current rendered object.
  9708. *
  9709. * @tsl
  9710. * @type {Node<vec3>}
  9711. */
  9712. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  9713. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  9714. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  9715. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9716. /**
  9717. * TSL object that represents the vertex position in view space of the current rendered object.
  9718. *
  9719. * @tsl
  9720. * @type {VaryingNode<vec3>}
  9721. */
  9722. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  9723. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  9724. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9725. /**
  9726. * TSL object that represents the position view direction of the current rendered object.
  9727. *
  9728. * @tsl
  9729. * @type {VaryingNode<vec3>}
  9730. */
  9731. const positionViewDirection = /*@__PURE__*/ ( Fn( ( builder ) => {
  9732. let output;
  9733. if ( builder.camera.isOrthographicCamera ) {
  9734. output = vec3( 0, 0, 1 );
  9735. } else {
  9736. output = positionView.negate().toVarying( 'v_positionViewDirection' ).normalize();
  9737. }
  9738. return output.toVar( 'positionViewDirection' );
  9739. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9740. /**
  9741. * This node can be used to evaluate whether a primitive is front or back facing.
  9742. *
  9743. * @augments Node
  9744. */
  9745. class FrontFacingNode extends Node {
  9746. static get type() {
  9747. return 'FrontFacingNode';
  9748. }
  9749. /**
  9750. * Constructs a new front facing node.
  9751. */
  9752. constructor() {
  9753. super( 'bool' );
  9754. /**
  9755. * This flag can be used for type testing.
  9756. *
  9757. * @type {boolean}
  9758. * @readonly
  9759. * @default true
  9760. */
  9761. this.isFrontFacingNode = true;
  9762. }
  9763. generate( builder ) {
  9764. if ( builder.shaderStage !== 'fragment' ) return 'true';
  9765. //
  9766. const { material } = builder;
  9767. if ( material.side === BackSide ) {
  9768. return 'false';
  9769. }
  9770. return builder.getFrontFacing();
  9771. }
  9772. }
  9773. /**
  9774. * TSL object that represents whether a primitive is front or back facing
  9775. *
  9776. * @tsl
  9777. * @type {FrontFacingNode<bool>}
  9778. */
  9779. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  9780. /**
  9781. * TSL object that represents the front facing status as a number instead of a bool.
  9782. * `1` means front facing, `-1` means back facing.
  9783. *
  9784. * @tsl
  9785. * @type {Node<float>}
  9786. */
  9787. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  9788. /**
  9789. * Converts a direction vector to a face direction vector based on the material's side.
  9790. *
  9791. * If the material is set to `BackSide`, the direction is inverted.
  9792. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  9793. *
  9794. * @tsl
  9795. * @param {Node<vec3>} direction - The direction vector to convert.
  9796. * @returns {Node<vec3>} The converted direction vector.
  9797. */
  9798. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  9799. const side = material.side;
  9800. if ( side === BackSide ) {
  9801. direction = direction.mul( -1 );
  9802. } else if ( side === DoubleSide ) {
  9803. direction = direction.mul( faceDirection );
  9804. }
  9805. return direction;
  9806. } );
  9807. /**
  9808. * TSL object that represents the normal attribute of the current rendered object in local space.
  9809. *
  9810. * @tsl
  9811. * @type {Node<vec3>}
  9812. */
  9813. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  9814. /**
  9815. * TSL object that represents the vertex normal of the current rendered object in local space.
  9816. *
  9817. * @tsl
  9818. * @type {Node<vec3>}
  9819. */
  9820. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  9821. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  9822. warn( 'TSL: Vertex attribute "normal" not found on geometry.' );
  9823. return vec3( 0, 1, 0 );
  9824. }
  9825. return normalGeometry;
  9826. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  9827. /**
  9828. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  9829. *
  9830. * @tsl
  9831. * @type {Node<vec3>}
  9832. */
  9833. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  9834. /**
  9835. * TSL object that represents the vertex normal of the current rendered object in view space.
  9836. *
  9837. * @tsl
  9838. * @type {Node<vec3>}
  9839. */
  9840. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9841. let node;
  9842. if ( builder.material.flatShading === true ) {
  9843. node = normalFlat;
  9844. } else {
  9845. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  9846. }
  9847. return node;
  9848. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  9849. /**
  9850. * TSL object that represents the vertex normal of the current rendered object in world space.
  9851. *
  9852. * @tsl
  9853. * @type {Node<vec3>}
  9854. */
  9855. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9856. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  9857. if ( builder.material.flatShading !== true ) {
  9858. normal = normal.toVarying( 'v_normalWorldGeometry' );
  9859. }
  9860. return normal.normalize().toVar( 'normalWorldGeometry' );
  9861. }, 'vec3' ).once() )();
  9862. /**
  9863. * TSL object that represents the vertex normal of the current rendered object in view space.
  9864. *
  9865. * @tsl
  9866. * @type {Node<vec3>}
  9867. */
  9868. const normalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, material, context } ) => {
  9869. let node;
  9870. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9871. node = normalViewGeometry;
  9872. if ( material.flatShading !== true ) {
  9873. node = directionToFaceDirection( node );
  9874. }
  9875. } else {
  9876. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9877. node = context.setupNormal().context( { getUV: null } );
  9878. }
  9879. return node;
  9880. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  9881. /**
  9882. * TSL object that represents the vertex normal of the current rendered object in world space.
  9883. *
  9884. * @tsl
  9885. * @type {Node<vec3>}
  9886. */
  9887. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  9888. /**
  9889. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  9890. *
  9891. * @tsl
  9892. * @type {Node<vec3>}
  9893. */
  9894. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  9895. let node;
  9896. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9897. node = normalView;
  9898. } else {
  9899. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9900. node = context.setupClearcoatNormal().context( { getUV: null } );
  9901. }
  9902. return node;
  9903. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  9904. /**
  9905. * Transforms the normal with the given matrix.
  9906. *
  9907. * @tsl
  9908. * @function
  9909. * @param {Node<vec3>} normal - The normal.
  9910. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  9911. * @return {Node<vec3>} The transformed normal.
  9912. */
  9913. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  9914. const m = mat3( matrix );
  9915. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  9916. return m.mul( transformedNormal ).xyz;
  9917. } );
  9918. /**
  9919. * Transforms the given normal from local to view space.
  9920. *
  9921. * @tsl
  9922. * @function
  9923. * @param {Node<vec3>} normal - The normal.
  9924. * @param {NodeBuilder} builder - The current node builder.
  9925. * @return {Node<vec3>} The transformed normal.
  9926. */
  9927. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  9928. const modelNormalViewMatrix = builder.renderer.overrideNodes.modelNormalViewMatrix;
  9929. if ( modelNormalViewMatrix !== null ) {
  9930. return modelNormalViewMatrix.transformDirection( normal );
  9931. }
  9932. //
  9933. const transformedNormal = modelNormalMatrix.mul( normal );
  9934. return cameraViewMatrix.transformDirection( transformedNormal );
  9935. } );
  9936. // Deprecated
  9937. /**
  9938. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  9939. *
  9940. * @tsl
  9941. * @type {Node<vec3>}
  9942. * @deprecated since r178. Use `normalView` instead.
  9943. */
  9944. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  9945. warn( 'TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  9946. return normalView;
  9947. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9948. /**
  9949. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  9950. *
  9951. * @tsl
  9952. * @type {Node<vec3>}
  9953. * @deprecated since r178. Use `normalWorld` instead.
  9954. */
  9955. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  9956. warn( 'TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  9957. return normalWorld;
  9958. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9959. /**
  9960. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  9961. *
  9962. * @tsl
  9963. * @type {Node<vec3>}
  9964. * @deprecated since r178. Use `clearcoatNormalView` instead.
  9965. */
  9966. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  9967. warn( 'TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  9968. return clearcoatNormalView;
  9969. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9970. const _e1$1 = /*@__PURE__*/ new Euler();
  9971. const _m1$1 = /*@__PURE__*/ new Matrix4();
  9972. /**
  9973. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  9974. *
  9975. * @tsl
  9976. * @type {UniformNode<float>}
  9977. */
  9978. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  9979. /**
  9980. * TSL object that represents the intensity of environment maps of PBR materials.
  9981. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  9982. *
  9983. * @tsl
  9984. * @type {Node<float>}
  9985. */
  9986. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  9987. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  9988. } );
  9989. /**
  9990. * TSL object that represents the rotation of environment maps.
  9991. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  9992. * rotation of `scene.environment` instead.
  9993. *
  9994. * @tsl
  9995. * @type {Node<mat4>}
  9996. */
  9997. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  9998. return frame.material;
  9999. } ).onObjectUpdate( function ( { material, scene } ) {
  10000. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  10001. if ( rotation ) {
  10002. _e1$1.copy( rotation );
  10003. _m1$1.makeRotationFromEuler( _e1$1 );
  10004. } else {
  10005. _m1$1.identity();
  10006. }
  10007. return _m1$1;
  10008. } );
  10009. /**
  10010. * The reflect vector in view space.
  10011. *
  10012. * @tsl
  10013. * @type {Node<vec3>}
  10014. */
  10015. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  10016. /**
  10017. * The refract vector in view space.
  10018. *
  10019. * @tsl
  10020. * @type {Node<vec3>}
  10021. */
  10022. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  10023. /**
  10024. * Used for sampling cube maps when using cube reflection mapping.
  10025. *
  10026. * @tsl
  10027. * @type {Node<vec3>}
  10028. */
  10029. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10030. /**
  10031. * Used for sampling cube maps when using cube refraction mapping.
  10032. *
  10033. * @tsl
  10034. * @type {Node<vec3>}
  10035. */
  10036. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10037. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  10038. /**
  10039. * This type of uniform node represents a cube texture.
  10040. *
  10041. * @augments TextureNode
  10042. */
  10043. class CubeTextureNode extends TextureNode {
  10044. static get type() {
  10045. return 'CubeTextureNode';
  10046. }
  10047. /**
  10048. * Constructs a new cube texture node.
  10049. *
  10050. * @param {CubeTexture} value - The cube texture.
  10051. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10052. * @param {?Node<int>} [levelNode=null] - The level node.
  10053. * @param {?Node<float>} [biasNode=null] - The bias node.
  10054. */
  10055. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  10056. super( value, uvNode, levelNode, biasNode );
  10057. /**
  10058. * This flag can be used for type testing.
  10059. *
  10060. * @type {boolean}
  10061. * @readonly
  10062. * @default true
  10063. */
  10064. this.isCubeTextureNode = true;
  10065. }
  10066. /**
  10067. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  10068. *
  10069. * @param {NodeBuilder} builder - The current node builder.
  10070. * @return {string} The input type.
  10071. */
  10072. getInputType( /*builder*/ ) {
  10073. return 'cubeTexture';
  10074. }
  10075. /**
  10076. * Returns a default uvs based on the mapping type of the cube texture.
  10077. *
  10078. * @return {Node<vec3>} The default uv attribute.
  10079. */
  10080. getDefaultUV() {
  10081. const texture = this.value;
  10082. if ( texture.mapping === CubeReflectionMapping ) {
  10083. return reflectVector;
  10084. } else if ( texture.mapping === CubeRefractionMapping ) {
  10085. return refractVector;
  10086. } else {
  10087. error( 'CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  10088. return vec3( 0, 0, 0 );
  10089. }
  10090. }
  10091. /**
  10092. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  10093. * for cube textures. The uv transformation matrix is not applied to cube textures.
  10094. *
  10095. * @param {boolean} value - The update toggle.
  10096. */
  10097. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  10098. /**
  10099. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  10100. * to modify the uv node for correct sampling.
  10101. *
  10102. * @param {NodeBuilder} builder - The current node builder.
  10103. * @param {Node} uvNode - The uv node to setup.
  10104. * @return {Node} The updated uv node.
  10105. */
  10106. setupUV( builder, uvNode ) {
  10107. const texture = this.value;
  10108. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  10109. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  10110. }
  10111. return materialEnvRotation.mul( uvNode );
  10112. }
  10113. /**
  10114. * Generates the uv code snippet.
  10115. *
  10116. * @param {NodeBuilder} builder - The current node builder.
  10117. * @param {Node} cubeUV - The uv node to generate code for.
  10118. * @return {string} The generated code snippet.
  10119. */
  10120. generateUV( builder, cubeUV ) {
  10121. return cubeUV.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  10122. }
  10123. }
  10124. /**
  10125. * TSL function for creating a cube texture node.
  10126. *
  10127. * @tsl
  10128. * @function
  10129. * @param {CubeTexture} value - The cube texture.
  10130. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10131. * @param {?Node<int>} [levelNode=null] - The level node.
  10132. * @param {?Node<float>} [biasNode=null] - The bias node.
  10133. * @returns {CubeTextureNode}
  10134. */
  10135. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  10136. /**
  10137. * TSL function for creating a cube texture uniform node.
  10138. *
  10139. * @tsl
  10140. * @function
  10141. * @param {?(CubeTexture|CubeTextureNode)} [value=EmptyTexture] - The cube texture.
  10142. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10143. * @param {?Node<int>} [levelNode=null] - The level node.
  10144. * @param {?Node<float>} [biasNode=null] - The bias node.
  10145. * @returns {CubeTextureNode}
  10146. */
  10147. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  10148. let textureNode;
  10149. if ( value && value.isCubeTextureNode === true ) {
  10150. textureNode = nodeObject( value.clone() );
  10151. textureNode.referenceNode = value; // Ensure the reference is set to the original node
  10152. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  10153. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  10154. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  10155. } else {
  10156. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  10157. }
  10158. return textureNode;
  10159. };
  10160. /**
  10161. * TSL function for creating a uniform cube texture node.
  10162. *
  10163. * @tsl
  10164. * @function
  10165. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  10166. * @returns {CubeTextureNode}
  10167. */
  10168. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  10169. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  10170. /**
  10171. * This class is only relevant if the referenced property is array-like.
  10172. * In this case, `ReferenceElementNode` allows to refer to a specific
  10173. * element inside the data structure via an index.
  10174. *
  10175. * @augments ArrayElementNode
  10176. */
  10177. class ReferenceElementNode extends ArrayElementNode {
  10178. static get type() {
  10179. return 'ReferenceElementNode';
  10180. }
  10181. /**
  10182. * Constructs a new reference element node.
  10183. *
  10184. * @param {?ReferenceNode} referenceNode - The reference node.
  10185. * @param {Node} indexNode - The index node that defines the element access.
  10186. */
  10187. constructor( referenceNode, indexNode ) {
  10188. super( referenceNode, indexNode );
  10189. /**
  10190. * Similar to {@link ReferenceNode#reference}, an additional
  10191. * property references to the current node.
  10192. *
  10193. * @type {?ReferenceNode}
  10194. * @default null
  10195. */
  10196. this.referenceNode = referenceNode;
  10197. /**
  10198. * This flag can be used for type testing.
  10199. *
  10200. * @type {boolean}
  10201. * @readonly
  10202. * @default true
  10203. */
  10204. this.isReferenceElementNode = true;
  10205. }
  10206. /**
  10207. * This method is overwritten since the node type is inferred from
  10208. * the uniform type of the reference node.
  10209. *
  10210. * @return {string} The node type.
  10211. */
  10212. getNodeType() {
  10213. return this.referenceNode.uniformType;
  10214. }
  10215. generate( builder ) {
  10216. const snippet = super.generate( builder );
  10217. const arrayType = this.referenceNode.getNodeType();
  10218. const elementType = this.getNodeType();
  10219. return builder.format( snippet, arrayType, elementType );
  10220. }
  10221. }
  10222. /**
  10223. * This type of node establishes a reference to a property of another object.
  10224. * In this way, the value of the node is automatically linked to the value of
  10225. * referenced object. Reference nodes internally represent the linked value
  10226. * as a uniform.
  10227. *
  10228. * @augments Node
  10229. */
  10230. class ReferenceNode extends Node {
  10231. static get type() {
  10232. return 'ReferenceNode';
  10233. }
  10234. /**
  10235. * Constructs a new reference node.
  10236. *
  10237. * @param {string} property - The name of the property the node refers to.
  10238. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  10239. * @param {?Object} [object=null] - The object the property belongs to.
  10240. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  10241. */
  10242. constructor( property, uniformType, object = null, count = null ) {
  10243. super();
  10244. /**
  10245. * The name of the property the node refers to.
  10246. *
  10247. * @type {string}
  10248. */
  10249. this.property = property;
  10250. /**
  10251. * The uniform type that should be used to represent the property value.
  10252. *
  10253. * @type {string}
  10254. */
  10255. this.uniformType = uniformType;
  10256. /**
  10257. * The object the property belongs to.
  10258. *
  10259. * @type {?Object}
  10260. * @default null
  10261. */
  10262. this.object = object;
  10263. /**
  10264. * When the linked property is an array, this parameter defines its length.
  10265. *
  10266. * @type {?number}
  10267. * @default null
  10268. */
  10269. this.count = count;
  10270. /**
  10271. * The property name might have dots so nested properties can be referred.
  10272. * The hierarchy of the names is stored inside this array.
  10273. *
  10274. * @type {Array<string>}
  10275. */
  10276. this.properties = property.split( '.' );
  10277. /**
  10278. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  10279. * since the final reference might be updated from calling code.
  10280. *
  10281. * @type {?Object}
  10282. * @default null
  10283. */
  10284. this.reference = object;
  10285. /**
  10286. * The uniform node that holds the value of the reference node.
  10287. *
  10288. * @type {UniformNode}
  10289. * @default null
  10290. */
  10291. this.node = null;
  10292. /**
  10293. * The uniform group of the internal uniform.
  10294. *
  10295. * @type {UniformGroupNode}
  10296. * @default null
  10297. */
  10298. this.group = null;
  10299. /**
  10300. * An optional label of the internal uniform node.
  10301. *
  10302. * @type {?string}
  10303. * @default null
  10304. */
  10305. this.name = null;
  10306. /**
  10307. * Overwritten since reference nodes are updated per object.
  10308. *
  10309. * @type {string}
  10310. * @default 'object'
  10311. */
  10312. this.updateType = NodeUpdateType.OBJECT;
  10313. }
  10314. /**
  10315. * When the referred property is array-like, this method can be used
  10316. * to access elements via an index node.
  10317. *
  10318. * @param {IndexNode} indexNode - indexNode.
  10319. * @return {ReferenceElementNode} A reference to an element.
  10320. */
  10321. element( indexNode ) {
  10322. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  10323. }
  10324. /**
  10325. * Sets the uniform group for this reference node.
  10326. *
  10327. * @param {UniformGroupNode} group - The uniform group to set.
  10328. * @return {ReferenceNode} A reference to this node.
  10329. */
  10330. setGroup( group ) {
  10331. this.group = group;
  10332. return this;
  10333. }
  10334. /**
  10335. * Sets the name for the internal uniform.
  10336. *
  10337. * @param {string} name - The label to set.
  10338. * @return {ReferenceNode} A reference to this node.
  10339. */
  10340. setName( name ) {
  10341. this.name = name;
  10342. return this;
  10343. }
  10344. /**
  10345. * Sets the label for the internal uniform.
  10346. *
  10347. * @deprecated
  10348. * @param {string} name - The label to set.
  10349. * @return {ReferenceNode} A reference to this node.
  10350. */
  10351. label( name ) {
  10352. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  10353. return this.setName( name );
  10354. }
  10355. /**
  10356. * Sets the node type which automatically defines the internal
  10357. * uniform type.
  10358. *
  10359. * @param {string} uniformType - The type to set.
  10360. */
  10361. setNodeType( uniformType ) {
  10362. let node = null;
  10363. if ( this.count !== null ) {
  10364. node = buffer( null, uniformType, this.count );
  10365. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  10366. node = uniformArray( null, uniformType );
  10367. } else if ( uniformType === 'texture' ) {
  10368. node = texture( null );
  10369. } else if ( uniformType === 'cubeTexture' ) {
  10370. node = cubeTexture( null );
  10371. } else {
  10372. node = uniform( null, uniformType );
  10373. }
  10374. if ( this.group !== null ) {
  10375. node.setGroup( this.group );
  10376. }
  10377. if ( this.name !== null ) node.setName( this.name );
  10378. this.node = node;
  10379. }
  10380. /**
  10381. * This method is overwritten since the node type is inferred from
  10382. * the type of the reference node.
  10383. *
  10384. * @param {NodeBuilder} builder - The current node builder.
  10385. * @return {string} The node type.
  10386. */
  10387. getNodeType( builder ) {
  10388. if ( this.node === null ) {
  10389. this.updateReference( builder );
  10390. this.updateValue();
  10391. }
  10392. return this.node.getNodeType( builder );
  10393. }
  10394. /**
  10395. * Returns the property value from the given referred object.
  10396. *
  10397. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  10398. * @return {any} The value.
  10399. */
  10400. getValueFromReference( object = this.reference ) {
  10401. const { properties } = this;
  10402. let value = object[ properties[ 0 ] ];
  10403. for ( let i = 1; i < properties.length; i ++ ) {
  10404. value = value[ properties[ i ] ];
  10405. }
  10406. return value;
  10407. }
  10408. /**
  10409. * Allows to update the reference based on the given state. The state is only
  10410. * evaluated {@link ReferenceNode#object} is not set.
  10411. *
  10412. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10413. * @return {Object} The updated reference.
  10414. */
  10415. updateReference( state ) {
  10416. this.reference = this.object !== null ? this.object : state.object;
  10417. return this.reference;
  10418. }
  10419. /**
  10420. * The output of the reference node is the internal uniform node.
  10421. *
  10422. * @param {NodeBuilder} builder - The current node builder.
  10423. * @return {UniformNode} The output node.
  10424. */
  10425. setup( /* builder */ ) {
  10426. this.updateValue();
  10427. return this.node;
  10428. }
  10429. /**
  10430. * Overwritten to update the internal uniform value.
  10431. *
  10432. * @param {NodeFrame} frame - A reference to the current node frame.
  10433. */
  10434. update( /*frame*/ ) {
  10435. this.updateValue();
  10436. }
  10437. /**
  10438. * Retrieves the value from the referred object property and uses it
  10439. * to updated the internal uniform.
  10440. */
  10441. updateValue() {
  10442. if ( this.node === null ) this.setNodeType( this.uniformType );
  10443. const value = this.getValueFromReference();
  10444. if ( Array.isArray( value ) ) {
  10445. this.node.array = value;
  10446. } else {
  10447. this.node.value = value;
  10448. }
  10449. }
  10450. }
  10451. /**
  10452. * TSL function for creating a reference node.
  10453. *
  10454. * @tsl
  10455. * @function
  10456. * @param {string} name - The name of the property the node refers to.
  10457. * @param {string} type - The uniform type that should be used to represent the property value.
  10458. * @param {?Object} [object] - The object the property belongs to.
  10459. * @returns {ReferenceNode}
  10460. */
  10461. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  10462. /**
  10463. * TSL function for creating a reference node. Use this function if you want need a reference
  10464. * to an array-like property that should be represented as a uniform buffer.
  10465. *
  10466. * @tsl
  10467. * @function
  10468. * @param {string} name - The name of the property the node refers to.
  10469. * @param {string} type - The uniform type that should be used to represent the property value.
  10470. * @param {number} count - The number of value inside the array-like object.
  10471. * @param {Object} object - An array-like object the property belongs to.
  10472. * @returns {ReferenceNode}
  10473. */
  10474. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  10475. /**
  10476. * This node is a special type of reference node which is intended
  10477. * for linking material properties with node values.
  10478. * ```js
  10479. * const opacityNode = materialReference( 'opacity', 'float', material );
  10480. * ```
  10481. * When changing `material.opacity`, the node value of `opacityNode` will
  10482. * automatically be updated.
  10483. *
  10484. * @augments ReferenceNode
  10485. */
  10486. class MaterialReferenceNode extends ReferenceNode {
  10487. static get type() {
  10488. return 'MaterialReferenceNode';
  10489. }
  10490. /**
  10491. * Constructs a new material reference node.
  10492. *
  10493. * @param {string} property - The name of the property the node refers to.
  10494. * @param {string} inputType - The uniform type that should be used to represent the property value.
  10495. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  10496. * the node refers to the material of the current rendered object.
  10497. */
  10498. constructor( property, inputType, material = null ) {
  10499. super( property, inputType, material );
  10500. /**
  10501. * The material the property belongs to. When no material is set,
  10502. * the node refers to the material of the current rendered object.
  10503. *
  10504. * @type {?Material}
  10505. * @default null
  10506. */
  10507. this.material = material;
  10508. /**
  10509. * This flag can be used for type testing.
  10510. *
  10511. * @type {boolean}
  10512. * @readonly
  10513. * @default true
  10514. */
  10515. this.isMaterialReferenceNode = true;
  10516. }
  10517. /**
  10518. * Updates the reference based on the given state. The state is only evaluated
  10519. * {@link MaterialReferenceNode#material} is not set.
  10520. *
  10521. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10522. * @return {Object} The updated reference.
  10523. */
  10524. updateReference( state ) {
  10525. this.reference = this.material !== null ? this.material : state.material;
  10526. return this.reference;
  10527. }
  10528. }
  10529. /**
  10530. * TSL function for creating a material reference node.
  10531. *
  10532. * @tsl
  10533. * @function
  10534. * @param {string} name - The name of the property the node refers to.
  10535. * @param {string} type - The uniform type that should be used to represent the property value.
  10536. * @param {?Material} [material=null] - The material the property belongs to.
  10537. * When no material is set, the node refers to the material of the current rendered object.
  10538. * @returns {MaterialReferenceNode}
  10539. */
  10540. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  10541. // Normal Mapping Without Precomputed Tangents
  10542. // http://www.thetenthplanet.de/archives/1180
  10543. const uv = uv$1();
  10544. const q0 = positionView.dFdx();
  10545. const q1 = positionView.dFdy();
  10546. const st0 = uv.dFdx();
  10547. const st1 = uv.dFdy();
  10548. const N = normalView;
  10549. const q1perp = q1.cross( N );
  10550. const q0perp = N.cross( q0 );
  10551. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  10552. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  10553. const det = T.dot( T ).max( B.dot( B ) );
  10554. const scale$1 = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  10555. /**
  10556. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  10557. * Useful for normal mapping without precomputed tangents.
  10558. *
  10559. * Reference: http://www.thetenthplanet.de/archives/1180
  10560. *
  10561. * @tsl
  10562. * @type {Node<vec3>}
  10563. */
  10564. const tangentViewFrame = /*@__PURE__*/ T.mul( scale$1 ).toVar( 'tangentViewFrame' );
  10565. /**
  10566. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  10567. * Complements the tangentViewFrame for constructing the tangent space basis.
  10568. *
  10569. * Reference: http://www.thetenthplanet.de/archives/1180
  10570. *
  10571. * @tsl
  10572. * @type {Node<vec3>}
  10573. */
  10574. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale$1 ).toVar( 'bitangentViewFrame' );
  10575. /**
  10576. * TSL object that represents the tangent attribute of the current rendered object.
  10577. *
  10578. * @tsl
  10579. * @type {Node<vec4>}
  10580. */
  10581. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  10582. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  10583. builder.geometry.computeTangents();
  10584. }
  10585. return attribute( 'tangent', 'vec4' );
  10586. } )();
  10587. /**
  10588. * TSL object that represents the vertex tangent in local space of the current rendered object.
  10589. *
  10590. * @tsl
  10591. * @type {Node<vec3>}
  10592. */
  10593. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  10594. /**
  10595. * TSL object that represents the vertex tangent in view space of the current rendered object.
  10596. *
  10597. * @tsl
  10598. * @type {Node<vec3>}
  10599. */
  10600. const tangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10601. let node;
  10602. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10603. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  10604. } else {
  10605. node = tangentViewFrame;
  10606. }
  10607. if ( material.flatShading !== true ) {
  10608. node = directionToFaceDirection( node );
  10609. }
  10610. return node;
  10611. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  10612. /**
  10613. * TSL object that represents the vertex tangent in world space of the current rendered object.
  10614. *
  10615. * @tsl
  10616. * @type {Node<vec3>}
  10617. */
  10618. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  10619. /**
  10620. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  10621. *
  10622. * @tsl
  10623. * @private
  10624. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  10625. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  10626. * @returns {Node<vec3>} The bitangent node.
  10627. */
  10628. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], { subBuildFn, material } ) => {
  10629. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  10630. if ( subBuildFn === 'NORMAL' && material.flatShading !== true ) {
  10631. bitangent = bitangent.toVarying( varyingName );
  10632. }
  10633. return bitangent;
  10634. } ).once( [ 'NORMAL' ] );
  10635. /**
  10636. * TSL object that represents the bitangent attribute of the current rendered object.
  10637. *
  10638. * @tsl
  10639. * @type {Node<vec3>}
  10640. */
  10641. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  10642. /**
  10643. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  10644. *
  10645. * @tsl
  10646. * @type {Node<vec3>}
  10647. */
  10648. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  10649. /**
  10650. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  10651. *
  10652. * @tsl
  10653. * @type {Node<vec3>}
  10654. */
  10655. const bitangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10656. let node;
  10657. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10658. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  10659. } else {
  10660. node = bitangentViewFrame;
  10661. }
  10662. if ( material.flatShading !== true ) {
  10663. node = directionToFaceDirection( node );
  10664. }
  10665. return node;
  10666. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  10667. /**
  10668. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  10669. *
  10670. * @tsl
  10671. * @type {Node<vec3>}
  10672. */
  10673. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  10674. /**
  10675. * TSL object that represents the TBN matrix in view space.
  10676. *
  10677. * @tsl
  10678. * @type {Node<mat3>}
  10679. */
  10680. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  10681. /**
  10682. * TSL object that represents the parallax direction.
  10683. *
  10684. * @tsl
  10685. * @type {Node<mat3>}
  10686. */
  10687. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  10688. /**
  10689. * TSL function for computing parallax uv coordinates.
  10690. *
  10691. * @tsl
  10692. * @function
  10693. * @param {Node<vec2>} uv - A uv node.
  10694. * @param {Node<vec2>} scale - A scale node.
  10695. * @returns {Node<vec2>} Parallax uv coordinates.
  10696. */
  10697. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  10698. /**
  10699. * TSL function for computing bent normals.
  10700. *
  10701. * @tsl
  10702. * @function
  10703. * @returns {Node<vec3>} Bent normals.
  10704. */
  10705. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  10706. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  10707. let bentNormal = anisotropyB.cross( positionViewDirection );
  10708. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  10709. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  10710. return bentNormal;
  10711. } ).once() )();
  10712. /**
  10713. * This class can be used for applying normals maps to materials.
  10714. *
  10715. * ```js
  10716. * material.normalNode = normalMap( texture( normalTex ) );
  10717. * ```
  10718. *
  10719. * @augments TempNode
  10720. */
  10721. class NormalMapNode extends TempNode {
  10722. static get type() {
  10723. return 'NormalMapNode';
  10724. }
  10725. /**
  10726. * Constructs a new normal map node.
  10727. *
  10728. * @param {Node<vec3>} node - Represents the normal map data.
  10729. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10730. */
  10731. constructor( node, scaleNode = null ) {
  10732. super( 'vec3' );
  10733. /**
  10734. * Represents the normal map data.
  10735. *
  10736. * @type {Node<vec3>}
  10737. */
  10738. this.node = node;
  10739. /**
  10740. * Controls the intensity of the effect.
  10741. *
  10742. * @type {?Node<vec2>}
  10743. * @default null
  10744. */
  10745. this.scaleNode = scaleNode;
  10746. /**
  10747. * The normal map type.
  10748. *
  10749. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  10750. * @default TangentSpaceNormalMap
  10751. */
  10752. this.normalMapType = TangentSpaceNormalMap;
  10753. }
  10754. setup( { material } ) {
  10755. const { normalMapType, scaleNode } = this;
  10756. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  10757. if ( scaleNode !== null ) {
  10758. let scale = scaleNode;
  10759. if ( material.flatShading === true ) {
  10760. scale = directionToFaceDirection( scale );
  10761. }
  10762. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  10763. }
  10764. let output = null;
  10765. if ( normalMapType === ObjectSpaceNormalMap ) {
  10766. output = transformNormalToView( normalMap );
  10767. } else if ( normalMapType === TangentSpaceNormalMap ) {
  10768. output = TBNViewMatrix.mul( normalMap ).normalize();
  10769. } else {
  10770. error( `NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  10771. output = normalView; // Fallback to default normal view
  10772. }
  10773. return output;
  10774. }
  10775. }
  10776. /**
  10777. * TSL function for creating a normal map node.
  10778. *
  10779. * @tsl
  10780. * @function
  10781. * @param {Node<vec3>} node - Represents the normal map data.
  10782. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10783. * @returns {NormalMapNode}
  10784. */
  10785. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  10786. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  10787. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  10788. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  10789. // It's used to preserve the same TextureNode instance
  10790. const sampleTexture = ( callback ) => textureNode.isolate().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  10791. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  10792. return vec2(
  10793. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  10794. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  10795. ).mul( bumpScale );
  10796. } );
  10797. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10798. const perturbNormalArb = Fn( ( inputs ) => {
  10799. const { surf_pos, surf_norm, dHdxy } = inputs;
  10800. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  10801. const vSigmaX = surf_pos.dFdx().normalize();
  10802. const vSigmaY = surf_pos.dFdy().normalize();
  10803. const vN = surf_norm; // normalized
  10804. const R1 = vSigmaY.cross( vN );
  10805. const R2 = vN.cross( vSigmaX );
  10806. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  10807. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  10808. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  10809. } );
  10810. /**
  10811. * This class can be used for applying bump maps to materials.
  10812. *
  10813. * ```js
  10814. * material.normalNode = bumpMap( texture( bumpTex ) );
  10815. * ```
  10816. *
  10817. * @augments TempNode
  10818. */
  10819. class BumpMapNode extends TempNode {
  10820. static get type() {
  10821. return 'BumpMapNode';
  10822. }
  10823. /**
  10824. * Constructs a new bump map node.
  10825. *
  10826. * @param {Node<float>} textureNode - Represents the bump map data.
  10827. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10828. */
  10829. constructor( textureNode, scaleNode = null ) {
  10830. super( 'vec3' );
  10831. /**
  10832. * Represents the bump map data.
  10833. *
  10834. * @type {Node<float>}
  10835. */
  10836. this.textureNode = textureNode;
  10837. /**
  10838. * Controls the intensity of the bump effect.
  10839. *
  10840. * @type {?Node<float>}
  10841. * @default null
  10842. */
  10843. this.scaleNode = scaleNode;
  10844. }
  10845. setup() {
  10846. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  10847. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  10848. return perturbNormalArb( {
  10849. surf_pos: positionView,
  10850. surf_norm: normalView,
  10851. dHdxy
  10852. } );
  10853. }
  10854. }
  10855. /**
  10856. * TSL function for creating a bump map node.
  10857. *
  10858. * @tsl
  10859. * @function
  10860. * @param {Node<float>} textureNode - Represents the bump map data.
  10861. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10862. * @returns {BumpMapNode}
  10863. */
  10864. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  10865. const _propertyCache = new Map();
  10866. /**
  10867. * This class should simplify the node access to material properties.
  10868. * It internal uses reference nodes to make sure changes to material
  10869. * properties are automatically reflected to predefined TSL objects
  10870. * like e.g. `materialColor`.
  10871. *
  10872. * @augments Node
  10873. */
  10874. class MaterialNode extends Node {
  10875. static get type() {
  10876. return 'MaterialNode';
  10877. }
  10878. /**
  10879. * Constructs a new material node.
  10880. *
  10881. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  10882. */
  10883. constructor( scope ) {
  10884. super();
  10885. /**
  10886. * The scope defines what material property is referred by the node.
  10887. *
  10888. * @type {string}
  10889. */
  10890. this.scope = scope;
  10891. }
  10892. /**
  10893. * Returns a cached reference node for the given property and type.
  10894. *
  10895. * @param {string} property - The name of the material property.
  10896. * @param {string} type - The uniform type of the property.
  10897. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10898. */
  10899. getCache( property, type ) {
  10900. let node = _propertyCache.get( property );
  10901. if ( node === undefined ) {
  10902. node = materialReference( property, type );
  10903. _propertyCache.set( property, node );
  10904. }
  10905. return node;
  10906. }
  10907. /**
  10908. * Returns a float-typed material reference node for the given property name.
  10909. *
  10910. * @param {string} property - The name of the material property.
  10911. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  10912. */
  10913. getFloat( property ) {
  10914. return this.getCache( property, 'float' );
  10915. }
  10916. /**
  10917. * Returns a color-typed material reference node for the given property name.
  10918. *
  10919. * @param {string} property - The name of the material property.
  10920. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  10921. */
  10922. getColor( property ) {
  10923. return this.getCache( property, 'color' );
  10924. }
  10925. /**
  10926. * Returns a texture-typed material reference node for the given property name.
  10927. *
  10928. * @param {string} property - The name of the material property.
  10929. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10930. */
  10931. getTexture( property ) {
  10932. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  10933. }
  10934. /**
  10935. * The node setup is done depending on the selected scope. Multiple material properties
  10936. * might be grouped into a single node composition if they logically belong together.
  10937. *
  10938. * @param {NodeBuilder} builder - The current node builder.
  10939. * @return {Node} The node representing the selected scope.
  10940. */
  10941. setup( builder ) {
  10942. const material = builder.context.material;
  10943. const scope = this.scope;
  10944. let node = null;
  10945. if ( scope === MaterialNode.COLOR ) {
  10946. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  10947. if ( material.map && material.map.isTexture === true ) {
  10948. node = colorNode.mul( this.getTexture( 'map' ) );
  10949. } else {
  10950. node = colorNode;
  10951. }
  10952. } else if ( scope === MaterialNode.OPACITY ) {
  10953. const opacityNode = this.getFloat( scope );
  10954. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  10955. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  10956. } else {
  10957. node = opacityNode;
  10958. }
  10959. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  10960. if ( material.specularMap && material.specularMap.isTexture === true ) {
  10961. node = this.getTexture( 'specular' ).r;
  10962. } else {
  10963. node = float( 1 );
  10964. }
  10965. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  10966. const specularIntensityNode = this.getFloat( scope );
  10967. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  10968. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  10969. } else {
  10970. node = specularIntensityNode;
  10971. }
  10972. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  10973. const specularColorNode = this.getColor( scope );
  10974. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  10975. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  10976. } else {
  10977. node = specularColorNode;
  10978. }
  10979. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  10980. const roughnessNode = this.getFloat( scope );
  10981. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  10982. node = roughnessNode.mul( this.getTexture( scope ).g );
  10983. } else {
  10984. node = roughnessNode;
  10985. }
  10986. } else if ( scope === MaterialNode.METALNESS ) {
  10987. const metalnessNode = this.getFloat( scope );
  10988. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  10989. node = metalnessNode.mul( this.getTexture( scope ).b );
  10990. } else {
  10991. node = metalnessNode;
  10992. }
  10993. } else if ( scope === MaterialNode.EMISSIVE ) {
  10994. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  10995. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  10996. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  10997. node = emissiveNode.mul( this.getTexture( scope ) );
  10998. } else {
  10999. node = emissiveNode;
  11000. }
  11001. } else if ( scope === MaterialNode.NORMAL ) {
  11002. if ( material.normalMap ) {
  11003. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  11004. node.normalMapType = material.normalMapType;
  11005. } else if ( material.bumpMap ) {
  11006. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  11007. } else {
  11008. node = normalView;
  11009. }
  11010. } else if ( scope === MaterialNode.CLEARCOAT ) {
  11011. const clearcoatNode = this.getFloat( scope );
  11012. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  11013. node = clearcoatNode.mul( this.getTexture( scope ).r );
  11014. } else {
  11015. node = clearcoatNode;
  11016. }
  11017. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  11018. const clearcoatRoughnessNode = this.getFloat( scope );
  11019. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  11020. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  11021. } else {
  11022. node = clearcoatRoughnessNode;
  11023. }
  11024. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  11025. if ( material.clearcoatNormalMap ) {
  11026. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  11027. } else {
  11028. node = normalView;
  11029. }
  11030. } else if ( scope === MaterialNode.SHEEN ) {
  11031. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  11032. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  11033. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  11034. } else {
  11035. node = sheenNode;
  11036. }
  11037. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  11038. const sheenRoughnessNode = this.getFloat( scope );
  11039. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  11040. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  11041. } else {
  11042. node = sheenRoughnessNode;
  11043. }
  11044. node = node.clamp( 0.07, 1.0 );
  11045. } else if ( scope === MaterialNode.ANISOTROPY ) {
  11046. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  11047. const anisotropyPolar = this.getTexture( scope );
  11048. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  11049. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  11050. } else {
  11051. node = materialAnisotropyVector;
  11052. }
  11053. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  11054. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  11055. if ( material.iridescenceThicknessMap ) {
  11056. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  11057. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  11058. } else {
  11059. node = iridescenceThicknessMaximum;
  11060. }
  11061. } else if ( scope === MaterialNode.TRANSMISSION ) {
  11062. const transmissionNode = this.getFloat( scope );
  11063. if ( material.transmissionMap ) {
  11064. node = transmissionNode.mul( this.getTexture( scope ).r );
  11065. } else {
  11066. node = transmissionNode;
  11067. }
  11068. } else if ( scope === MaterialNode.THICKNESS ) {
  11069. const thicknessNode = this.getFloat( scope );
  11070. if ( material.thicknessMap ) {
  11071. node = thicknessNode.mul( this.getTexture( scope ).g );
  11072. } else {
  11073. node = thicknessNode;
  11074. }
  11075. } else if ( scope === MaterialNode.IOR ) {
  11076. node = this.getFloat( scope );
  11077. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  11078. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  11079. } else if ( scope === MaterialNode.AO ) {
  11080. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  11081. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  11082. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  11083. } else {
  11084. const outputType = this.getNodeType( builder );
  11085. node = this.getCache( scope, outputType );
  11086. }
  11087. return node;
  11088. }
  11089. }
  11090. MaterialNode.ALPHA_TEST = 'alphaTest';
  11091. MaterialNode.COLOR = 'color';
  11092. MaterialNode.OPACITY = 'opacity';
  11093. MaterialNode.SHININESS = 'shininess';
  11094. MaterialNode.SPECULAR = 'specular';
  11095. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  11096. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  11097. MaterialNode.SPECULAR_COLOR = 'specularColor';
  11098. MaterialNode.REFLECTIVITY = 'reflectivity';
  11099. MaterialNode.ROUGHNESS = 'roughness';
  11100. MaterialNode.METALNESS = 'metalness';
  11101. MaterialNode.NORMAL = 'normal';
  11102. MaterialNode.CLEARCOAT = 'clearcoat';
  11103. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  11104. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  11105. MaterialNode.EMISSIVE = 'emissive';
  11106. MaterialNode.ROTATION = 'rotation';
  11107. MaterialNode.SHEEN = 'sheen';
  11108. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  11109. MaterialNode.ANISOTROPY = 'anisotropy';
  11110. MaterialNode.IRIDESCENCE = 'iridescence';
  11111. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  11112. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  11113. MaterialNode.IOR = 'ior';
  11114. MaterialNode.TRANSMISSION = 'transmission';
  11115. MaterialNode.THICKNESS = 'thickness';
  11116. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  11117. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  11118. MaterialNode.LINE_SCALE = 'scale';
  11119. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  11120. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  11121. MaterialNode.LINE_WIDTH = 'linewidth';
  11122. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  11123. MaterialNode.POINT_SIZE = 'size';
  11124. MaterialNode.DISPERSION = 'dispersion';
  11125. MaterialNode.LIGHT_MAP = 'light';
  11126. MaterialNode.AO = 'ao';
  11127. /**
  11128. * TSL object that represents alpha test of the current material.
  11129. *
  11130. * @tsl
  11131. * @type {Node<float>}
  11132. */
  11133. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  11134. /**
  11135. * TSL object that represents the diffuse color of the current material.
  11136. * The value is composed via `color` * `map`.
  11137. *
  11138. * @tsl
  11139. * @type {Node<vec3>}
  11140. */
  11141. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  11142. /**
  11143. * TSL object that represents the shininess of the current material.
  11144. *
  11145. * @tsl
  11146. * @type {Node<float>}
  11147. */
  11148. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  11149. /**
  11150. * TSL object that represents the emissive color of the current material.
  11151. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  11152. *
  11153. * @tsl
  11154. * @type {Node<vec3>}
  11155. */
  11156. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  11157. /**
  11158. * TSL object that represents the opacity of the current material.
  11159. * The value is composed via `opacity` * `alphaMap`.
  11160. *
  11161. * @tsl
  11162. * @type {Node<float>}
  11163. */
  11164. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  11165. /**
  11166. * TSL object that represents the specular of the current material.
  11167. *
  11168. * @tsl
  11169. * @type {Node<vec3>}
  11170. */
  11171. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  11172. /**
  11173. * TSL object that represents the specular intensity of the current material.
  11174. * The value is composed via `specularIntensity` * `specularMap.a`.
  11175. *
  11176. * @tsl
  11177. * @type {Node<float>}
  11178. */
  11179. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  11180. /**
  11181. * TSL object that represents the specular color of the current material.
  11182. * The value is composed via `specularColor` * `specularMap.rgb`.
  11183. *
  11184. * @tsl
  11185. * @type {Node<vec3>}
  11186. */
  11187. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  11188. /**
  11189. * TSL object that represents the specular strength of the current material.
  11190. * The value is composed via `specularMap.r`.
  11191. *
  11192. * @tsl
  11193. * @type {Node<float>}
  11194. */
  11195. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  11196. /**
  11197. * TSL object that represents the reflectivity of the current material.
  11198. *
  11199. * @tsl
  11200. * @type {Node<float>}
  11201. */
  11202. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  11203. /**
  11204. * TSL object that represents the roughness of the current material.
  11205. * The value is composed via `roughness` * `roughnessMap.g`.
  11206. *
  11207. * @tsl
  11208. * @type {Node<float>}
  11209. */
  11210. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  11211. /**
  11212. * TSL object that represents the metalness of the current material.
  11213. * The value is composed via `metalness` * `metalnessMap.b`.
  11214. *
  11215. * @tsl
  11216. * @type {Node<float>}
  11217. */
  11218. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  11219. /**
  11220. * TSL object that represents the normal of the current material.
  11221. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  11222. *
  11223. * @tsl
  11224. * @type {Node<vec3>}
  11225. */
  11226. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  11227. /**
  11228. * TSL object that represents the clearcoat of the current material.
  11229. * The value is composed via `clearcoat` * `clearcoatMap.r`
  11230. *
  11231. * @tsl
  11232. * @type {Node<float>}
  11233. */
  11234. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  11235. /**
  11236. * TSL object that represents the clearcoat roughness of the current material.
  11237. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  11238. *
  11239. * @tsl
  11240. * @type {Node<float>}
  11241. */
  11242. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  11243. /**
  11244. * TSL object that represents the clearcoat normal of the current material.
  11245. * The value will be either `clearcoatNormalMap` or `normalView`.
  11246. *
  11247. * @tsl
  11248. * @type {Node<vec3>}
  11249. */
  11250. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  11251. /**
  11252. * TSL object that represents the rotation of the current sprite material.
  11253. *
  11254. * @tsl
  11255. * @type {Node<float>}
  11256. */
  11257. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  11258. /**
  11259. * TSL object that represents the sheen color of the current material.
  11260. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  11261. *
  11262. * @tsl
  11263. * @type {Node<vec3>}
  11264. */
  11265. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  11266. /**
  11267. * TSL object that represents the sheen roughness of the current material.
  11268. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  11269. *
  11270. * @tsl
  11271. * @type {Node<float>}
  11272. */
  11273. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  11274. /**
  11275. * TSL object that represents the anisotropy of the current material.
  11276. *
  11277. * @tsl
  11278. * @type {Node<vec2>}
  11279. */
  11280. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  11281. /**
  11282. * TSL object that represents the iridescence of the current material.
  11283. *
  11284. * @tsl
  11285. * @type {Node<float>}
  11286. */
  11287. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  11288. /**
  11289. * TSL object that represents the iridescence IOR of the current material.
  11290. *
  11291. * @tsl
  11292. * @type {Node<float>}
  11293. */
  11294. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  11295. /**
  11296. * TSL object that represents the iridescence thickness of the current material.
  11297. *
  11298. * @tsl
  11299. * @type {Node<float>}
  11300. */
  11301. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  11302. /**
  11303. * TSL object that represents the transmission of the current material.
  11304. * The value is composed via `transmission` * `transmissionMap.r`.
  11305. *
  11306. * @tsl
  11307. * @type {Node<float>}
  11308. */
  11309. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  11310. /**
  11311. * TSL object that represents the thickness of the current material.
  11312. * The value is composed via `thickness` * `thicknessMap.g`.
  11313. *
  11314. * @tsl
  11315. * @type {Node<float>}
  11316. */
  11317. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  11318. /**
  11319. * TSL object that represents the IOR of the current material.
  11320. *
  11321. * @tsl
  11322. * @type {Node<float>}
  11323. */
  11324. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  11325. /**
  11326. * TSL object that represents the attenuation distance of the current material.
  11327. *
  11328. * @tsl
  11329. * @type {Node<float>}
  11330. */
  11331. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  11332. /**
  11333. * TSL object that represents the attenuation color of the current material.
  11334. *
  11335. * @tsl
  11336. * @type {Node<vec3>}
  11337. */
  11338. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  11339. /**
  11340. * TSL object that represents the scale of the current dashed line material.
  11341. *
  11342. * @tsl
  11343. * @type {Node<float>}
  11344. */
  11345. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  11346. /**
  11347. * TSL object that represents the dash size of the current dashed line material.
  11348. *
  11349. * @tsl
  11350. * @type {Node<float>}
  11351. */
  11352. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  11353. /**
  11354. * TSL object that represents the gap size of the current dashed line material.
  11355. *
  11356. * @tsl
  11357. * @type {Node<float>}
  11358. */
  11359. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  11360. /**
  11361. * TSL object that represents the line width of the current line material.
  11362. *
  11363. * @tsl
  11364. * @type {Node<float>}
  11365. */
  11366. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  11367. /**
  11368. * TSL object that represents the dash offset of the current line material.
  11369. *
  11370. * @tsl
  11371. * @type {Node<float>}
  11372. */
  11373. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  11374. /**
  11375. * TSL object that represents the point size of the current points material.
  11376. *
  11377. * @tsl
  11378. * @type {Node<float>}
  11379. */
  11380. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  11381. /**
  11382. * TSL object that represents the dispersion of the current material.
  11383. *
  11384. * @tsl
  11385. * @type {Node<float>}
  11386. */
  11387. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  11388. /**
  11389. * TSL object that represents the light map of the current material.
  11390. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  11391. *
  11392. * @tsl
  11393. * @type {Node<vec3>}
  11394. */
  11395. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  11396. /**
  11397. * TSL object that represents the ambient occlusion map of the current material.
  11398. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  11399. *
  11400. * @tsl
  11401. * @type {Node<float>}
  11402. */
  11403. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  11404. /**
  11405. * TSL object that represents the anisotropy vector of the current material.
  11406. *
  11407. * @tsl
  11408. * @type {Node<vec2>}
  11409. */
  11410. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  11411. return frame.material;
  11412. } ).onRenderUpdate( function ( { material } ) {
  11413. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  11414. } );
  11415. /**
  11416. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  11417. *
  11418. * @tsl
  11419. * @type {VaryingNode<vec4>}
  11420. */
  11421. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  11422. return builder.context.setupModelViewProjection();
  11423. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  11424. /**
  11425. * This class represents shader indices of different types. The following predefined node
  11426. * objects cover frequent use cases:
  11427. *
  11428. * - `vertexIndex`: The index of a vertex within a mesh.
  11429. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  11430. * - `drawIndex`: The index of a draw call.
  11431. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  11432. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  11433. * - `subgroupIndex`: The index of a compute invocation's subgroup within its workgroup.
  11434. *
  11435. * @augments Node
  11436. */
  11437. class IndexNode extends Node {
  11438. static get type() {
  11439. return 'IndexNode';
  11440. }
  11441. /**
  11442. * Constructs a new index node.
  11443. *
  11444. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationGlobal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  11445. */
  11446. constructor( scope ) {
  11447. super( 'uint' );
  11448. /**
  11449. * The scope of the index node.
  11450. *
  11451. * @type {string}
  11452. */
  11453. this.scope = scope;
  11454. /**
  11455. * This flag can be used for type testing.
  11456. *
  11457. * @type {boolean}
  11458. * @readonly
  11459. * @default true
  11460. */
  11461. this.isIndexNode = true;
  11462. }
  11463. generate( builder ) {
  11464. const nodeType = this.getNodeType( builder );
  11465. const scope = this.scope;
  11466. let propertyName;
  11467. if ( scope === IndexNode.VERTEX ) {
  11468. propertyName = builder.getVertexIndex();
  11469. } else if ( scope === IndexNode.INSTANCE ) {
  11470. propertyName = builder.getInstanceIndex();
  11471. } else if ( scope === IndexNode.DRAW ) {
  11472. propertyName = builder.getDrawIndex();
  11473. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  11474. propertyName = builder.getInvocationLocalIndex();
  11475. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  11476. propertyName = builder.getInvocationSubgroupIndex();
  11477. } else if ( scope === IndexNode.SUBGROUP ) {
  11478. propertyName = builder.getSubgroupIndex();
  11479. } else {
  11480. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  11481. }
  11482. let output;
  11483. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  11484. output = propertyName;
  11485. } else {
  11486. const nodeVarying = varying( this );
  11487. output = nodeVarying.build( builder, nodeType );
  11488. }
  11489. return output;
  11490. }
  11491. }
  11492. IndexNode.VERTEX = 'vertex';
  11493. IndexNode.INSTANCE = 'instance';
  11494. IndexNode.SUBGROUP = 'subgroup';
  11495. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  11496. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  11497. IndexNode.DRAW = 'draw';
  11498. /**
  11499. * TSL object that represents the index of a vertex within a mesh.
  11500. *
  11501. * @tsl
  11502. * @type {IndexNode}
  11503. */
  11504. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  11505. /**
  11506. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  11507. *
  11508. * @tsl
  11509. * @type {IndexNode}
  11510. */
  11511. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  11512. /**
  11513. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  11514. *
  11515. * @tsl
  11516. * @type {IndexNode}
  11517. */
  11518. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  11519. /**
  11520. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  11521. *
  11522. * @tsl
  11523. * @type {IndexNode}
  11524. */
  11525. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  11526. /**
  11527. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  11528. *
  11529. * @tsl
  11530. * @type {IndexNode}
  11531. */
  11532. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  11533. /**
  11534. * TSL object that represents the index of a draw call.
  11535. *
  11536. * @tsl
  11537. * @type {IndexNode}
  11538. */
  11539. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  11540. /**
  11541. * This node implements the vertex shader logic which is required
  11542. * when rendering 3D objects via instancing. The code makes sure
  11543. * vertex positions, normals and colors can be modified via instanced
  11544. * data.
  11545. *
  11546. * @augments Node
  11547. */
  11548. class InstanceNode extends Node {
  11549. static get type() {
  11550. return 'InstanceNode';
  11551. }
  11552. /**
  11553. * Constructs a new instance node.
  11554. *
  11555. * @param {number} count - The number of instances.
  11556. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  11557. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  11558. */
  11559. constructor( count, instanceMatrix, instanceColor = null ) {
  11560. super( 'void' );
  11561. /**
  11562. * The number of instances.
  11563. *
  11564. * @type {number}
  11565. */
  11566. this.count = count;
  11567. /**
  11568. * Instanced buffer attribute representing the transformation of instances.
  11569. *
  11570. * @type {InstancedBufferAttribute}
  11571. */
  11572. this.instanceMatrix = instanceMatrix;
  11573. /**
  11574. * Instanced buffer attribute representing the color of instances.
  11575. *
  11576. * @type {InstancedBufferAttribute}
  11577. */
  11578. this.instanceColor = instanceColor;
  11579. /**
  11580. * The node that represents the instance matrix data.
  11581. *
  11582. * @type {?Node}
  11583. */
  11584. this.instanceMatrixNode = null;
  11585. /**
  11586. * The node that represents the instance color data.
  11587. *
  11588. * @type {?Node}
  11589. * @default null
  11590. */
  11591. this.instanceColorNode = null;
  11592. /**
  11593. * The update type is set to `frame` since an update
  11594. * of instanced buffer data must be checked per frame.
  11595. *
  11596. * @type {string}
  11597. * @default 'frame'
  11598. */
  11599. this.updateType = NodeUpdateType.FRAME;
  11600. /**
  11601. * A reference to a buffer that is used by `instanceMatrixNode`.
  11602. *
  11603. * @type {?InstancedInterleavedBuffer}
  11604. */
  11605. this.buffer = null;
  11606. /**
  11607. * A reference to a buffer that is used by `instanceColorNode`.
  11608. *
  11609. * @type {?InstancedBufferAttribute}
  11610. */
  11611. this.bufferColor = null;
  11612. }
  11613. /**
  11614. * Setups the internal buffers and nodes and assigns the transformed vertex data
  11615. * to predefined node variables for accumulation. That follows the same patterns
  11616. * like with morph and skinning nodes.
  11617. *
  11618. * @param {NodeBuilder} builder - The current node builder.
  11619. */
  11620. setup( builder ) {
  11621. const { instanceMatrix, instanceColor } = this;
  11622. const { count } = instanceMatrix;
  11623. let { instanceMatrixNode, instanceColorNode } = this;
  11624. if ( instanceMatrixNode === null ) {
  11625. // Both WebGPU and WebGL backends have UBO max limited to 64kb. Matrix count number bigger than 1000 ( 16 * 4 * 1000 = 64kb ) will fallback to attribute.
  11626. if ( count <= 1000 ) {
  11627. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  11628. } else {
  11629. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  11630. this.buffer = buffer;
  11631. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  11632. const instanceBuffers = [
  11633. // F.Signature -> bufferAttribute( array, type, stride, offset )
  11634. bufferFn( buffer, 'vec4', 16, 0 ),
  11635. bufferFn( buffer, 'vec4', 16, 4 ),
  11636. bufferFn( buffer, 'vec4', 16, 8 ),
  11637. bufferFn( buffer, 'vec4', 16, 12 )
  11638. ];
  11639. instanceMatrixNode = mat4( ...instanceBuffers );
  11640. }
  11641. this.instanceMatrixNode = instanceMatrixNode;
  11642. }
  11643. if ( instanceColor && instanceColorNode === null ) {
  11644. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  11645. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  11646. this.bufferColor = buffer;
  11647. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  11648. this.instanceColorNode = instanceColorNode;
  11649. }
  11650. // POSITION
  11651. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  11652. positionLocal.assign( instancePosition );
  11653. // NORMAL
  11654. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  11655. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  11656. // ASSIGNS
  11657. normalLocal.assign( instanceNormal );
  11658. }
  11659. // COLOR
  11660. if ( this.instanceColorNode !== null ) {
  11661. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  11662. }
  11663. }
  11664. /**
  11665. * Checks if the internal buffers required an update.
  11666. *
  11667. * @param {NodeFrame} frame - The current node frame.
  11668. */
  11669. update( /*frame*/ ) {
  11670. if ( this.buffer !== null ) {
  11671. // keep update ranges in sync
  11672. this.buffer.clearUpdateRanges();
  11673. this.buffer.updateRanges.push( ... this.instanceMatrix.updateRanges );
  11674. // update version if necessary
  11675. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.instanceMatrix.version !== this.buffer.version ) {
  11676. this.buffer.version = this.instanceMatrix.version;
  11677. }
  11678. }
  11679. if ( this.instanceColor && this.bufferColor !== null ) {
  11680. this.bufferColor.clearUpdateRanges();
  11681. this.bufferColor.updateRanges.push( ... this.instanceColor.updateRanges );
  11682. if ( this.instanceColor.usage !== DynamicDrawUsage && this.instanceColor.version !== this.bufferColor.version ) {
  11683. this.bufferColor.version = this.instanceColor.version;
  11684. }
  11685. }
  11686. }
  11687. }
  11688. /**
  11689. * TSL function for creating an instance node.
  11690. *
  11691. * @tsl
  11692. * @function
  11693. * @param {number} count - The number of instances.
  11694. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  11695. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  11696. * @returns {InstanceNode}
  11697. */
  11698. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  11699. /**
  11700. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  11701. * It allows an easier setup of the instance node.
  11702. *
  11703. * @augments InstanceNode
  11704. */
  11705. class InstancedMeshNode extends InstanceNode {
  11706. static get type() {
  11707. return 'InstancedMeshNode';
  11708. }
  11709. /**
  11710. * Constructs a new instanced mesh node.
  11711. *
  11712. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  11713. */
  11714. constructor( instancedMesh ) {
  11715. const { count, instanceMatrix, instanceColor } = instancedMesh;
  11716. super( count, instanceMatrix, instanceColor );
  11717. /**
  11718. * A reference to the instanced mesh.
  11719. *
  11720. * @type {InstancedMesh}
  11721. */
  11722. this.instancedMesh = instancedMesh;
  11723. }
  11724. }
  11725. /**
  11726. * TSL function for creating an instanced mesh node.
  11727. *
  11728. * @tsl
  11729. * @function
  11730. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  11731. * @returns {InstancedMeshNode}
  11732. */
  11733. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  11734. /**
  11735. * This node implements the vertex shader logic which is required
  11736. * when rendering 3D objects via batching. `BatchNode` must be used
  11737. * with instances of {@link BatchedMesh}.
  11738. *
  11739. * @augments Node
  11740. */
  11741. class BatchNode extends Node {
  11742. static get type() {
  11743. return 'BatchNode';
  11744. }
  11745. /**
  11746. * Constructs a new batch node.
  11747. *
  11748. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  11749. */
  11750. constructor( batchMesh ) {
  11751. super( 'void' );
  11752. /**
  11753. * A reference to batched mesh.
  11754. *
  11755. * @type {BatchedMesh}
  11756. */
  11757. this.batchMesh = batchMesh;
  11758. /**
  11759. * The batching index node.
  11760. *
  11761. * @type {?IndexNode}
  11762. * @default null
  11763. */
  11764. this.batchingIdNode = null;
  11765. }
  11766. /**
  11767. * Setups the internal buffers and nodes and assigns the transformed vertex data
  11768. * to predefined node variables for accumulation. That follows the same patterns
  11769. * like with morph and skinning nodes.
  11770. *
  11771. * @param {NodeBuilder} builder - The current node builder.
  11772. */
  11773. setup( builder ) {
  11774. if ( this.batchingIdNode === null ) {
  11775. if ( builder.getDrawIndex() === null ) {
  11776. this.batchingIdNode = instanceIndex;
  11777. } else {
  11778. this.batchingIdNode = drawIndex;
  11779. }
  11780. }
  11781. const getIndirectIndex = Fn( ( [ id ] ) => {
  11782. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x );
  11783. const x = int( id ).mod( size );
  11784. const y = int( id ).div( size );
  11785. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  11786. } ).setLayout( {
  11787. name: 'getIndirectIndex',
  11788. type: 'uint',
  11789. inputs: [
  11790. { name: 'id', type: 'int' }
  11791. ]
  11792. } );
  11793. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  11794. const matricesTexture = this.batchMesh._matricesTexture;
  11795. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x );
  11796. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  11797. const x = j.mod( size );
  11798. const y = j.div( size );
  11799. const batchingMatrix = mat4(
  11800. textureLoad( matricesTexture, ivec2( x, y ) ),
  11801. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  11802. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  11803. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  11804. );
  11805. const colorsTexture = this.batchMesh._colorsTexture;
  11806. if ( colorsTexture !== null ) {
  11807. const getBatchingColor = Fn( ( [ id ] ) => {
  11808. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x );
  11809. const j = id;
  11810. const x = j.mod( size );
  11811. const y = j.div( size );
  11812. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  11813. } ).setLayout( {
  11814. name: 'getBatchingColor',
  11815. type: 'vec3',
  11816. inputs: [
  11817. { name: 'id', type: 'int' }
  11818. ]
  11819. } );
  11820. const color = getBatchingColor( indirectId );
  11821. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  11822. }
  11823. const bm = mat3( batchingMatrix );
  11824. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  11825. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  11826. const batchingNormal = bm.mul( transformedNormal ).xyz;
  11827. normalLocal.assign( batchingNormal );
  11828. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  11829. tangentLocal.mulAssign( bm );
  11830. }
  11831. }
  11832. }
  11833. /**
  11834. * TSL function for creating a batch node.
  11835. *
  11836. * @tsl
  11837. * @function
  11838. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  11839. * @returns {BatchNode}
  11840. */
  11841. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  11842. /**
  11843. * This class enables element access on instances of {@link StorageBufferNode}.
  11844. * In most cases, it is indirectly used when accessing elements with the
  11845. * {@link StorageBufferNode#element} method.
  11846. *
  11847. * ```js
  11848. * const position = positionStorage.element( instanceIndex );
  11849. * ```
  11850. *
  11851. * @augments ArrayElementNode
  11852. */
  11853. class StorageArrayElementNode extends ArrayElementNode {
  11854. static get type() {
  11855. return 'StorageArrayElementNode';
  11856. }
  11857. /**
  11858. * Constructs storage buffer element node.
  11859. *
  11860. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11861. * @param {Node} indexNode - The index node that defines the element access.
  11862. */
  11863. constructor( storageBufferNode, indexNode ) {
  11864. super( storageBufferNode, indexNode );
  11865. /**
  11866. * This flag can be used for type testing.
  11867. *
  11868. * @type {boolean}
  11869. * @readonly
  11870. * @default true
  11871. */
  11872. this.isStorageArrayElementNode = true;
  11873. }
  11874. /**
  11875. * The storage buffer node.
  11876. *
  11877. * @param {Node} value
  11878. * @type {StorageBufferNode}
  11879. */
  11880. set storageBufferNode( value ) {
  11881. this.node = value;
  11882. }
  11883. get storageBufferNode() {
  11884. return this.node;
  11885. }
  11886. getMemberType( builder, name ) {
  11887. const structTypeNode = this.storageBufferNode.structTypeNode;
  11888. if ( structTypeNode ) {
  11889. return structTypeNode.getMemberType( builder, name );
  11890. }
  11891. return 'void';
  11892. }
  11893. setup( builder ) {
  11894. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11895. if ( this.node.isPBO === true ) {
  11896. builder.setupPBO( this.node );
  11897. }
  11898. }
  11899. return super.setup( builder );
  11900. }
  11901. generate( builder, output ) {
  11902. let snippet;
  11903. const isAssignContext = builder.context.assign;
  11904. //
  11905. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11906. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  11907. snippet = builder.generatePBO( this );
  11908. } else {
  11909. snippet = this.node.build( builder );
  11910. }
  11911. } else {
  11912. snippet = super.generate( builder );
  11913. }
  11914. if ( isAssignContext !== true ) {
  11915. const type = this.getNodeType( builder );
  11916. snippet = builder.format( snippet, type, output );
  11917. }
  11918. return snippet;
  11919. }
  11920. }
  11921. /**
  11922. * TSL function for creating a storage element node.
  11923. *
  11924. * @tsl
  11925. * @function
  11926. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11927. * @param {Node} indexNode - The index node that defines the element access.
  11928. * @returns {StorageArrayElementNode}
  11929. */
  11930. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  11931. /**
  11932. * This node is used in context of compute shaders and allows to define a
  11933. * storage buffer for data. A typical workflow is to create instances of
  11934. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  11935. * setup up a compute shader that writes into the buffers and then convert
  11936. * the storage buffers to attribute nodes for rendering.
  11937. *
  11938. * ```js
  11939. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  11940. *
  11941. * const computeInit = Fn( () => { // the compute shader
  11942. *
  11943. * const position = positionBuffer.element( instanceIndex );
  11944. *
  11945. * // compute position data
  11946. *
  11947. * position.x = 1;
  11948. * position.y = 1;
  11949. * position.z = 1;
  11950. *
  11951. * } )().compute( particleCount );
  11952. *
  11953. * const particleMaterial = new THREE.SpriteNodeMaterial();
  11954. * particleMaterial.positionNode = positionBuffer.toAttribute();
  11955. *
  11956. * renderer.computeAsync( computeInit );
  11957. *
  11958. * ```
  11959. *
  11960. * @augments BufferNode
  11961. */
  11962. class StorageBufferNode extends BufferNode {
  11963. static get type() {
  11964. return 'StorageBufferNode';
  11965. }
  11966. /**
  11967. * Constructs a new storage buffer node.
  11968. *
  11969. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11970. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  11971. * @param {number} [bufferCount=0] - The buffer count.
  11972. */
  11973. constructor( value, bufferType = null, bufferCount = 0 ) {
  11974. let nodeType, structTypeNode = null;
  11975. if ( bufferType && bufferType.isStruct ) {
  11976. nodeType = 'struct';
  11977. structTypeNode = bufferType.layout;
  11978. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  11979. bufferCount = value.count;
  11980. }
  11981. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  11982. nodeType = getTypeFromLength( value.itemSize );
  11983. bufferCount = value.count;
  11984. } else {
  11985. nodeType = bufferType;
  11986. }
  11987. super( value, nodeType, bufferCount );
  11988. /**
  11989. * This flag can be used for type testing.
  11990. *
  11991. * @type {boolean}
  11992. * @readonly
  11993. * @default true
  11994. */
  11995. this.isStorageBufferNode = true;
  11996. /**
  11997. * The buffer struct type.
  11998. *
  11999. * @type {?StructTypeNode}
  12000. * @default null
  12001. */
  12002. this.structTypeNode = structTypeNode;
  12003. /**
  12004. * The access type of the texture node.
  12005. *
  12006. * @type {string}
  12007. * @default 'readWrite'
  12008. */
  12009. this.access = NodeAccess.READ_WRITE;
  12010. /**
  12011. * Whether the node is atomic or not.
  12012. *
  12013. * @type {boolean}
  12014. * @default false
  12015. */
  12016. this.isAtomic = false;
  12017. /**
  12018. * Whether the node represents a PBO or not.
  12019. * Only relevant for WebGL.
  12020. *
  12021. * @type {boolean}
  12022. * @default false
  12023. */
  12024. this.isPBO = false;
  12025. /**
  12026. * A reference to the internal buffer attribute node.
  12027. *
  12028. * @type {?BufferAttributeNode}
  12029. * @default null
  12030. */
  12031. this._attribute = null;
  12032. /**
  12033. * A reference to the internal varying node.
  12034. *
  12035. * @type {?VaryingNode}
  12036. * @default null
  12037. */
  12038. this._varying = null;
  12039. /**
  12040. * `StorageBufferNode` sets this property to `true` by default.
  12041. *
  12042. * @type {boolean}
  12043. * @default true
  12044. */
  12045. this.global = true;
  12046. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  12047. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  12048. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  12049. else value.isStorageBufferAttribute = true;
  12050. }
  12051. }
  12052. /**
  12053. * This method is overwritten since the buffer data might be shared
  12054. * and thus the hash should be shared as well.
  12055. *
  12056. * @param {NodeBuilder} builder - The current node builder.
  12057. * @return {string} The hash.
  12058. */
  12059. getHash( builder ) {
  12060. if ( this.bufferCount === 0 ) {
  12061. let bufferData = builder.globalCache.getData( this.value );
  12062. if ( bufferData === undefined ) {
  12063. bufferData = {
  12064. node: this
  12065. };
  12066. builder.globalCache.setData( this.value, bufferData );
  12067. }
  12068. return bufferData.node.uuid;
  12069. }
  12070. return this.uuid;
  12071. }
  12072. /**
  12073. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  12074. *
  12075. * @param {NodeBuilder} builder - The current node builder.
  12076. * @return {string} The input type.
  12077. */
  12078. getInputType( /*builder*/ ) {
  12079. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  12080. }
  12081. /**
  12082. * Enables element access with the given index node.
  12083. *
  12084. * @param {IndexNode} indexNode - The index node.
  12085. * @return {StorageArrayElementNode} A node representing the element access.
  12086. */
  12087. element( indexNode ) {
  12088. return storageElement( this, indexNode );
  12089. }
  12090. /**
  12091. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  12092. *
  12093. * @param {boolean} value - The value so set.
  12094. * @return {StorageBufferNode} A reference to this node.
  12095. */
  12096. setPBO( value ) {
  12097. this.isPBO = value;
  12098. return this;
  12099. }
  12100. /**
  12101. * Returns the `isPBO` value.
  12102. *
  12103. * @return {boolean} Whether the node represents a PBO or not.
  12104. */
  12105. getPBO() {
  12106. return this.isPBO;
  12107. }
  12108. /**
  12109. * Defines the node access.
  12110. *
  12111. * @param {string} value - The node access.
  12112. * @return {StorageBufferNode} A reference to this node.
  12113. */
  12114. setAccess( value ) {
  12115. this.access = value;
  12116. return this;
  12117. }
  12118. /**
  12119. * Convenience method for configuring a read-only node access.
  12120. *
  12121. * @return {StorageBufferNode} A reference to this node.
  12122. */
  12123. toReadOnly() {
  12124. return this.setAccess( NodeAccess.READ_ONLY );
  12125. }
  12126. /**
  12127. * Defines whether the node is atomic or not.
  12128. *
  12129. * @param {boolean} value - The atomic flag.
  12130. * @return {StorageBufferNode} A reference to this node.
  12131. */
  12132. setAtomic( value ) {
  12133. this.isAtomic = value;
  12134. return this;
  12135. }
  12136. /**
  12137. * Convenience method for making this node atomic.
  12138. *
  12139. * @return {StorageBufferNode} A reference to this node.
  12140. */
  12141. toAtomic() {
  12142. return this.setAtomic( true );
  12143. }
  12144. /**
  12145. * Returns attribute data for this storage buffer node.
  12146. *
  12147. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  12148. */
  12149. getAttributeData() {
  12150. if ( this._attribute === null ) {
  12151. this._attribute = bufferAttribute( this.value );
  12152. this._varying = varying( this._attribute );
  12153. }
  12154. return {
  12155. attribute: this._attribute,
  12156. varying: this._varying
  12157. };
  12158. }
  12159. /**
  12160. * This method is overwritten since the node type from the availability of storage buffers
  12161. * and the attribute data.
  12162. *
  12163. * @param {NodeBuilder} builder - The current node builder.
  12164. * @return {string} The node type.
  12165. */
  12166. getNodeType( builder ) {
  12167. if ( this.structTypeNode !== null ) {
  12168. return this.structTypeNode.getNodeType( builder );
  12169. }
  12170. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12171. return super.getNodeType( builder );
  12172. }
  12173. const { attribute } = this.getAttributeData();
  12174. return attribute.getNodeType( builder );
  12175. }
  12176. /**
  12177. * Returns the type of a member of the struct.
  12178. *
  12179. * @param {NodeBuilder} builder - The current node builder.
  12180. * @param {string} name - The name of the member.
  12181. * @return {string} The type of the member.
  12182. */
  12183. getMemberType( builder, name ) {
  12184. if ( this.structTypeNode !== null ) {
  12185. return this.structTypeNode.getMemberType( builder, name );
  12186. }
  12187. return 'void';
  12188. }
  12189. /**
  12190. * Generates the code snippet of the storage buffer node.
  12191. *
  12192. * @param {NodeBuilder} builder - The current node builder.
  12193. * @return {string} The generated code snippet.
  12194. */
  12195. generate( builder ) {
  12196. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  12197. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12198. return super.generate( builder );
  12199. }
  12200. const { attribute, varying } = this.getAttributeData();
  12201. const output = varying.build( builder );
  12202. builder.registerTransform( output, attribute );
  12203. return output;
  12204. }
  12205. }
  12206. /**
  12207. * TSL function for creating a storage buffer node.
  12208. *
  12209. * @tsl
  12210. * @function
  12211. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12212. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  12213. * @param {number} [count=0] - The buffer count.
  12214. * @returns {StorageBufferNode}
  12215. */
  12216. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  12217. /**
  12218. * @tsl
  12219. * @function
  12220. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  12221. *
  12222. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12223. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  12224. * @param {number} count - The buffer count.
  12225. * @returns {StorageBufferNode}
  12226. */
  12227. const storageObject = ( value, type, count ) => { // @deprecated, r171
  12228. warn( 'TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  12229. return storage( value, type, count ).setPBO( true );
  12230. };
  12231. const _frameId = new WeakMap();
  12232. /**
  12233. * This node implements the vertex transformation shader logic which is required
  12234. * for skinning/skeletal animation.
  12235. *
  12236. * @augments Node
  12237. */
  12238. class SkinningNode extends Node {
  12239. static get type() {
  12240. return 'SkinningNode';
  12241. }
  12242. /**
  12243. * Constructs a new skinning node.
  12244. *
  12245. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12246. */
  12247. constructor( skinnedMesh ) {
  12248. super( 'void' );
  12249. /**
  12250. * The skinned mesh.
  12251. *
  12252. * @type {SkinnedMesh}
  12253. */
  12254. this.skinnedMesh = skinnedMesh;
  12255. /**
  12256. * The update type overwritten since skinning nodes are updated per object.
  12257. *
  12258. * @type {string}
  12259. */
  12260. this.updateType = NodeUpdateType.OBJECT;
  12261. //
  12262. /**
  12263. * The skin index attribute.
  12264. *
  12265. * @type {AttributeNode}
  12266. */
  12267. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  12268. /**
  12269. * The skin weight attribute.
  12270. *
  12271. * @type {AttributeNode}
  12272. */
  12273. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  12274. /**
  12275. * The bind matrix node.
  12276. *
  12277. * @type {Node<mat4>}
  12278. */
  12279. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  12280. /**
  12281. * The bind matrix inverse node.
  12282. *
  12283. * @type {Node<mat4>}
  12284. */
  12285. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  12286. /**
  12287. * The bind matrices as a uniform buffer node.
  12288. *
  12289. * @type {Node}
  12290. */
  12291. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12292. /**
  12293. * The current vertex position in local space.
  12294. *
  12295. * @type {Node<vec3>}
  12296. */
  12297. this.positionNode = positionLocal;
  12298. /**
  12299. * The result of vertex position in local space.
  12300. *
  12301. * @type {Node<vec3>}
  12302. */
  12303. this.toPositionNode = positionLocal;
  12304. /**
  12305. * The previous bind matrices as a uniform buffer node.
  12306. * Required for computing motion vectors.
  12307. *
  12308. * @type {?Node}
  12309. * @default null
  12310. */
  12311. this.previousBoneMatricesNode = null;
  12312. }
  12313. /**
  12314. * Transforms the given vertex position via skinning.
  12315. *
  12316. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12317. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  12318. * @return {Node<vec3>} The transformed vertex position.
  12319. */
  12320. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  12321. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12322. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12323. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12324. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12325. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12326. // POSITION
  12327. const skinVertex = bindMatrixNode.mul( position );
  12328. const skinned = add(
  12329. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  12330. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  12331. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  12332. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  12333. );
  12334. return bindMatrixInverseNode.mul( skinned ).xyz;
  12335. }
  12336. /**
  12337. * Transforms the given vertex normal via skinning.
  12338. *
  12339. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12340. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  12341. * @return {Node<vec3>} The transformed vertex normal.
  12342. */
  12343. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  12344. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12345. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12346. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12347. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12348. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12349. // NORMAL
  12350. let skinMatrix = add(
  12351. skinWeightNode.x.mul( boneMatX ),
  12352. skinWeightNode.y.mul( boneMatY ),
  12353. skinWeightNode.z.mul( boneMatZ ),
  12354. skinWeightNode.w.mul( boneMatW )
  12355. );
  12356. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  12357. return skinMatrix.transformDirection( normal ).xyz;
  12358. }
  12359. /**
  12360. * Computes the transformed/skinned vertex position of the previous frame.
  12361. *
  12362. * @param {NodeBuilder} builder - The current node builder.
  12363. * @return {Node<vec3>} The skinned position from the previous frame.
  12364. */
  12365. getPreviousSkinnedPosition( builder ) {
  12366. const skinnedMesh = builder.object;
  12367. if ( this.previousBoneMatricesNode === null ) {
  12368. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  12369. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12370. }
  12371. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  12372. }
  12373. /**
  12374. * Returns `true` if bone matrices from the previous frame are required. Relevant
  12375. * when computing motion vectors with {@link VelocityNode}.
  12376. *
  12377. * @param {NodeBuilder} builder - The current node builder.
  12378. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  12379. */
  12380. needsPreviousBoneMatrices( builder ) {
  12381. const mrt = builder.renderer.getMRT();
  12382. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  12383. }
  12384. /**
  12385. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  12386. *
  12387. * @param {NodeBuilder} builder - The current node builder.
  12388. * @return {Node<vec3>} The transformed vertex position.
  12389. */
  12390. setup( builder ) {
  12391. if ( this.needsPreviousBoneMatrices( builder ) ) {
  12392. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  12393. }
  12394. const skinPosition = this.getSkinnedPosition();
  12395. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  12396. //
  12397. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12398. const skinNormal = this.getSkinnedNormal();
  12399. normalLocal.assign( skinNormal );
  12400. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12401. tangentLocal.assign( skinNormal );
  12402. }
  12403. }
  12404. return skinPosition;
  12405. }
  12406. /**
  12407. * Generates the code snippet of the skinning node.
  12408. *
  12409. * @param {NodeBuilder} builder - The current node builder.
  12410. * @param {string} output - The current output.
  12411. * @return {string} The generated code snippet.
  12412. */
  12413. generate( builder, output ) {
  12414. if ( output !== 'void' ) {
  12415. return super.generate( builder, output );
  12416. }
  12417. }
  12418. /**
  12419. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  12420. *
  12421. * @param {NodeFrame} frame - The current node frame.
  12422. */
  12423. update( frame ) {
  12424. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  12425. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  12426. _frameId.set( skeleton, frame.frameId );
  12427. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  12428. skeleton.update();
  12429. }
  12430. }
  12431. /**
  12432. * TSL function for creating a skinning node.
  12433. *
  12434. * @tsl
  12435. * @function
  12436. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12437. * @returns {SkinningNode}
  12438. */
  12439. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  12440. /**
  12441. * TSL function for computing skinning.
  12442. *
  12443. * @tsl
  12444. * @function
  12445. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12446. * @param {Node<vec3>} [toPosition=null] - The target position.
  12447. * @returns {SkinningNode}
  12448. */
  12449. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  12450. const node = new SkinningNode( skinnedMesh );
  12451. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12452. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12453. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12454. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  12455. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  12456. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  12457. node.toPositionNode = toPosition;
  12458. return nodeObject( node );
  12459. };
  12460. /**
  12461. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  12462. * ```js
  12463. * Loop( count, ( { i } ) => {
  12464. *
  12465. * } );
  12466. * ```
  12467. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  12468. * ```js
  12469. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  12470. *
  12471. * } );
  12472. *```
  12473. * Nested loops can be defined in a compacted form:
  12474. * ```js
  12475. * Loop( 10, 5, ( { i, j } ) => {
  12476. *
  12477. * } );
  12478. * ```
  12479. * Loops that should run backwards can be defined like so:
  12480. * ```js
  12481. * Loop( { start: 10 }, () => {} );
  12482. * ```
  12483. * It is possible to execute with boolean values, similar to the `while` syntax.
  12484. * ```js
  12485. * const value = float( 0 ).toVar();
  12486. *
  12487. * Loop( value.lessThan( 10 ), () => {
  12488. *
  12489. * value.addAssign( 1 );
  12490. *
  12491. * } );
  12492. * ```
  12493. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  12494. * @augments Node
  12495. */
  12496. class LoopNode extends Node {
  12497. static get type() {
  12498. return 'LoopNode';
  12499. }
  12500. /**
  12501. * Constructs a new loop node.
  12502. *
  12503. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  12504. */
  12505. constructor( params = [] ) {
  12506. super( 'void' );
  12507. this.params = params;
  12508. }
  12509. /**
  12510. * Returns a loop variable name based on an index. The pattern is
  12511. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  12512. *
  12513. * @param {number} index - The index.
  12514. * @return {string} The loop variable name.
  12515. */
  12516. getVarName( index ) {
  12517. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  12518. }
  12519. /**
  12520. * Returns properties about this node.
  12521. *
  12522. * @param {NodeBuilder} builder - The current node builder.
  12523. * @return {Object} The node properties.
  12524. */
  12525. getProperties( builder ) {
  12526. const properties = builder.getNodeProperties( this );
  12527. if ( properties.stackNode !== undefined ) return properties;
  12528. //
  12529. const inputs = {};
  12530. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12531. const param = this.params[ i ];
  12532. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  12533. const type = ( param.isNode !== true && param.type ) || 'int';
  12534. inputs[ name ] = expression( name, type );
  12535. }
  12536. const stack = builder.addStack();
  12537. const fnCall = this.params[ this.params.length - 1 ]( inputs );
  12538. properties.returnsNode = fnCall.context( { nodeLoop: fnCall } );
  12539. properties.stackNode = stack;
  12540. const baseParam = this.params[ 0 ];
  12541. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  12542. const fnUpdateCall = Fn( this.params[ 0 ].update )( inputs );
  12543. properties.updateNode = fnUpdateCall.context( { nodeLoop: fnUpdateCall } );
  12544. }
  12545. builder.removeStack();
  12546. return properties;
  12547. }
  12548. setup( builder ) {
  12549. // setup properties
  12550. this.getProperties( builder );
  12551. if ( builder.fnCall ) {
  12552. const shaderNodeData = builder.getDataFromNode( builder.fnCall.shaderNode );
  12553. shaderNodeData.hasLoop = true;
  12554. }
  12555. }
  12556. generate( builder ) {
  12557. const properties = this.getProperties( builder );
  12558. const params = this.params;
  12559. const stackNode = properties.stackNode;
  12560. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  12561. const param = params[ i ];
  12562. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  12563. if ( param.isNode ) {
  12564. if ( param.getNodeType( builder ) === 'bool' ) {
  12565. isWhile = true;
  12566. type = 'bool';
  12567. end = param.build( builder, type );
  12568. } else {
  12569. type = 'int';
  12570. name = this.getVarName( i );
  12571. start = '0';
  12572. end = param.build( builder, type );
  12573. condition = '<';
  12574. }
  12575. } else {
  12576. type = param.type || 'int';
  12577. name = param.name || this.getVarName( i );
  12578. start = param.start;
  12579. end = param.end;
  12580. condition = param.condition;
  12581. update = param.update;
  12582. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  12583. else if ( start && start.isNode ) start = start.build( builder, type );
  12584. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  12585. else if ( end && end.isNode ) end = end.build( builder, type );
  12586. if ( start !== undefined && end === undefined ) {
  12587. start = start + ' - 1';
  12588. end = '0';
  12589. condition = '>=';
  12590. } else if ( end !== undefined && start === undefined ) {
  12591. start = '0';
  12592. condition = '<';
  12593. }
  12594. if ( condition === undefined ) {
  12595. if ( Number( start ) > Number( end ) ) {
  12596. condition = '>=';
  12597. } else {
  12598. condition = '<';
  12599. }
  12600. }
  12601. }
  12602. let loopSnippet;
  12603. if ( isWhile ) {
  12604. loopSnippet = `while ( ${ end } )`;
  12605. } else {
  12606. const internalParam = { start, end};
  12607. //
  12608. const startSnippet = internalParam.start;
  12609. const endSnippet = internalParam.end;
  12610. let updateSnippet;
  12611. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  12612. if ( update !== undefined && update !== null ) {
  12613. switch ( typeof update ) {
  12614. case 'function':
  12615. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  12616. const snippet = flow.code.replace( /\t|;/g, '' );
  12617. updateSnippet = snippet;
  12618. break;
  12619. case 'number':
  12620. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  12621. break;
  12622. case 'string':
  12623. updateSnippet = name + ' ' + update;
  12624. break;
  12625. default:
  12626. if ( update.isNode ) {
  12627. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  12628. } else {
  12629. error( 'TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  12630. updateSnippet = 'break /* invalid update */';
  12631. }
  12632. }
  12633. } else {
  12634. if ( type === 'int' || type === 'uint' ) {
  12635. update = condition.includes( '<' ) ? '++' : '--';
  12636. } else {
  12637. update = deltaOperator() + ' 1.';
  12638. }
  12639. updateSnippet = name + ' ' + update;
  12640. }
  12641. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  12642. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  12643. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  12644. }
  12645. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  12646. }
  12647. const stackSnippet = stackNode.build( builder, 'void' );
  12648. properties.returnsNode.build( builder, 'void' );
  12649. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  12650. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12651. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  12652. }
  12653. builder.addFlowTab();
  12654. }
  12655. }
  12656. /**
  12657. * TSL function for creating a loop node.
  12658. *
  12659. * @tsl
  12660. * @function
  12661. * @param {...any} params - A list of parameters.
  12662. * @returns {LoopNode}
  12663. */
  12664. const Loop = ( ...params ) => new LoopNode( nodeArray( params, 'int' ) ).toStack();
  12665. /**
  12666. * TSL function for creating a `Continue()` expression.
  12667. *
  12668. * @tsl
  12669. * @function
  12670. * @returns {ExpressionNode}
  12671. */
  12672. const Continue = () => expression( 'continue' ).toStack();
  12673. /**
  12674. * TSL function for creating a `Break()` expression.
  12675. *
  12676. * @tsl
  12677. * @function
  12678. * @returns {ExpressionNode}
  12679. */
  12680. const Break = () => expression( 'break' ).toStack();
  12681. const _morphTextures = /*@__PURE__*/ new WeakMap();
  12682. const _morphVec4 = /*@__PURE__*/ new Vector4();
  12683. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  12684. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  12685. const y = texelIndex.div( width );
  12686. const x = texelIndex.sub( y.mul( width ) );
  12687. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  12688. return bufferAttrib.mul( influence );
  12689. } );
  12690. function getEntry( geometry ) {
  12691. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12692. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  12693. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  12694. // instead of using attributes, the WebGL 2 code path encodes morph targets
  12695. // into an array of data textures. Each layer represents a single morph target.
  12696. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12697. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12698. let entry = _morphTextures.get( geometry );
  12699. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  12700. if ( entry !== undefined ) entry.texture.dispose();
  12701. const morphTargets = geometry.morphAttributes.position || [];
  12702. const morphNormals = geometry.morphAttributes.normal || [];
  12703. const morphColors = geometry.morphAttributes.color || [];
  12704. let vertexDataCount = 0;
  12705. if ( hasMorphPosition === true ) vertexDataCount = 1;
  12706. if ( hasMorphNormals === true ) vertexDataCount = 2;
  12707. if ( hasMorphColors === true ) vertexDataCount = 3;
  12708. let width = geometry.attributes.position.count * vertexDataCount;
  12709. let height = 1;
  12710. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  12711. if ( width > maxTextureSize ) {
  12712. height = Math.ceil( width / maxTextureSize );
  12713. width = maxTextureSize;
  12714. }
  12715. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  12716. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  12717. bufferTexture.type = FloatType;
  12718. bufferTexture.needsUpdate = true;
  12719. // fill buffer
  12720. const vertexDataStride = vertexDataCount * 4;
  12721. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  12722. const morphTarget = morphTargets[ i ];
  12723. const morphNormal = morphNormals[ i ];
  12724. const morphColor = morphColors[ i ];
  12725. const offset = width * height * 4 * i;
  12726. for ( let j = 0; j < morphTarget.count; j ++ ) {
  12727. const stride = j * vertexDataStride;
  12728. if ( hasMorphPosition === true ) {
  12729. _morphVec4.fromBufferAttribute( morphTarget, j );
  12730. buffer[ offset + stride + 0 ] = _morphVec4.x;
  12731. buffer[ offset + stride + 1 ] = _morphVec4.y;
  12732. buffer[ offset + stride + 2 ] = _morphVec4.z;
  12733. buffer[ offset + stride + 3 ] = 0;
  12734. }
  12735. if ( hasMorphNormals === true ) {
  12736. _morphVec4.fromBufferAttribute( morphNormal, j );
  12737. buffer[ offset + stride + 4 ] = _morphVec4.x;
  12738. buffer[ offset + stride + 5 ] = _morphVec4.y;
  12739. buffer[ offset + stride + 6 ] = _morphVec4.z;
  12740. buffer[ offset + stride + 7 ] = 0;
  12741. }
  12742. if ( hasMorphColors === true ) {
  12743. _morphVec4.fromBufferAttribute( morphColor, j );
  12744. buffer[ offset + stride + 8 ] = _morphVec4.x;
  12745. buffer[ offset + stride + 9 ] = _morphVec4.y;
  12746. buffer[ offset + stride + 10 ] = _morphVec4.z;
  12747. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  12748. }
  12749. }
  12750. }
  12751. entry = {
  12752. count: morphTargetsCount,
  12753. texture: bufferTexture,
  12754. stride: vertexDataCount,
  12755. size: new Vector2( width, height )
  12756. };
  12757. _morphTextures.set( geometry, entry );
  12758. function disposeTexture() {
  12759. bufferTexture.dispose();
  12760. _morphTextures.delete( geometry );
  12761. geometry.removeEventListener( 'dispose', disposeTexture );
  12762. }
  12763. geometry.addEventListener( 'dispose', disposeTexture );
  12764. }
  12765. return entry;
  12766. }
  12767. /**
  12768. * This node implements the vertex transformation shader logic which is required
  12769. * for morph target animation.
  12770. *
  12771. * @augments Node
  12772. */
  12773. class MorphNode extends Node {
  12774. static get type() {
  12775. return 'MorphNode';
  12776. }
  12777. /**
  12778. * Constructs a new morph node.
  12779. *
  12780. * @param {Mesh} mesh - The mesh holding the morph targets.
  12781. */
  12782. constructor( mesh ) {
  12783. super( 'void' );
  12784. /**
  12785. * The mesh holding the morph targets.
  12786. *
  12787. * @type {Mesh}
  12788. */
  12789. this.mesh = mesh;
  12790. /**
  12791. * A uniform node which represents the morph base influence value.
  12792. *
  12793. * @type {UniformNode<float>}
  12794. */
  12795. this.morphBaseInfluence = uniform( 1 );
  12796. /**
  12797. * The update type overwritten since morph nodes are updated per object.
  12798. *
  12799. * @type {string}
  12800. */
  12801. this.updateType = NodeUpdateType.OBJECT;
  12802. }
  12803. /**
  12804. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  12805. *
  12806. * @param {NodeBuilder} builder - The current node builder.
  12807. */
  12808. setup( builder ) {
  12809. const { geometry } = builder;
  12810. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12811. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  12812. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12813. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12814. // nodes
  12815. const { texture: bufferMap, stride, size } = getEntry( geometry );
  12816. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  12817. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  12818. const width = int( size.width );
  12819. Loop( morphTargetsCount, ( { i } ) => {
  12820. const influence = float( 0 ).toVar();
  12821. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  12822. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  12823. } else {
  12824. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  12825. }
  12826. If( influence.notEqual( 0 ), () => {
  12827. if ( hasMorphPosition === true ) {
  12828. positionLocal.addAssign( getMorph( {
  12829. bufferMap,
  12830. influence,
  12831. stride,
  12832. width,
  12833. depth: i,
  12834. offset: int( 0 )
  12835. } ) );
  12836. }
  12837. if ( hasMorphNormals === true ) {
  12838. normalLocal.addAssign( getMorph( {
  12839. bufferMap,
  12840. influence,
  12841. stride,
  12842. width,
  12843. depth: i,
  12844. offset: int( 1 )
  12845. } ) );
  12846. }
  12847. } );
  12848. } );
  12849. }
  12850. /**
  12851. * Updates the state of the morphed mesh by updating the base influence.
  12852. *
  12853. * @param {NodeFrame} frame - The current node frame.
  12854. */
  12855. update( /*frame*/ ) {
  12856. const morphBaseInfluence = this.morphBaseInfluence;
  12857. if ( this.mesh.geometry.morphTargetsRelative ) {
  12858. morphBaseInfluence.value = 1;
  12859. } else {
  12860. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  12861. }
  12862. }
  12863. }
  12864. /**
  12865. * TSL function for creating a morph node.
  12866. *
  12867. * @tsl
  12868. * @function
  12869. * @param {Mesh} mesh - The mesh holding the morph targets.
  12870. * @returns {MorphNode}
  12871. */
  12872. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  12873. /**
  12874. * Base class for lighting nodes.
  12875. *
  12876. * @augments Node
  12877. */
  12878. class LightingNode extends Node {
  12879. static get type() {
  12880. return 'LightingNode';
  12881. }
  12882. /**
  12883. * Constructs a new lighting node.
  12884. */
  12885. constructor() {
  12886. super( 'vec3' );
  12887. /**
  12888. * This flag can be used for type testing.
  12889. *
  12890. * @type {boolean}
  12891. * @readonly
  12892. * @default true
  12893. */
  12894. this.isLightingNode = true;
  12895. }
  12896. }
  12897. /**
  12898. * A generic class that can be used by nodes which contribute
  12899. * ambient occlusion to the scene. E.g. an ambient occlusion map
  12900. * node can be used as input for this module. Used in {@link NodeMaterial}.
  12901. *
  12902. * @augments LightingNode
  12903. */
  12904. class AONode extends LightingNode {
  12905. static get type() {
  12906. return 'AONode';
  12907. }
  12908. /**
  12909. * Constructs a new AO node.
  12910. *
  12911. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  12912. */
  12913. constructor( aoNode = null ) {
  12914. super();
  12915. /**
  12916. * The ambient occlusion node.
  12917. *
  12918. * @type {?Node<float>}
  12919. * @default null
  12920. */
  12921. this.aoNode = aoNode;
  12922. }
  12923. setup( builder ) {
  12924. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  12925. }
  12926. }
  12927. /**
  12928. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  12929. * by adding lighting specific context data. It represents the runtime context of
  12930. * {@link LightsNode}.
  12931. *
  12932. * @augments ContextNode
  12933. */
  12934. class LightingContextNode extends ContextNode {
  12935. static get type() {
  12936. return 'LightingContextNode';
  12937. }
  12938. /**
  12939. * Constructs a new lighting context node.
  12940. *
  12941. * @param {LightsNode} lightsNode - The lights node.
  12942. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  12943. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  12944. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  12945. */
  12946. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  12947. super( lightsNode );
  12948. /**
  12949. * The current lighting model.
  12950. *
  12951. * @type {?LightingModel}
  12952. * @default null
  12953. */
  12954. this.lightingModel = lightingModel;
  12955. /**
  12956. * A backdrop node.
  12957. *
  12958. * @type {?Node<vec3>}
  12959. * @default null
  12960. */
  12961. this.backdropNode = backdropNode;
  12962. /**
  12963. * A backdrop alpha node.
  12964. *
  12965. * @type {?Node<float>}
  12966. * @default null
  12967. */
  12968. this.backdropAlphaNode = backdropAlphaNode;
  12969. this._value = null;
  12970. }
  12971. /**
  12972. * Returns a lighting context object.
  12973. *
  12974. * @return {{
  12975. * radiance: Node<vec3>,
  12976. * irradiance: Node<vec3>,
  12977. * iblIrradiance: Node<vec3>,
  12978. * ambientOcclusion: Node<float>,
  12979. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  12980. * backdrop: Node<vec3>,
  12981. * backdropAlpha: Node<float>
  12982. * }} The lighting context object.
  12983. */
  12984. getContext() {
  12985. const { backdropNode, backdropAlphaNode } = this;
  12986. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  12987. directSpecular = vec3().toVar( 'directSpecular' ),
  12988. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  12989. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  12990. const reflectedLight = {
  12991. directDiffuse,
  12992. directSpecular,
  12993. indirectDiffuse,
  12994. indirectSpecular
  12995. };
  12996. const context = {
  12997. radiance: vec3().toVar( 'radiance' ),
  12998. irradiance: vec3().toVar( 'irradiance' ),
  12999. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  13000. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  13001. reflectedLight,
  13002. backdrop: backdropNode,
  13003. backdropAlpha: backdropAlphaNode
  13004. };
  13005. return context;
  13006. }
  13007. setup( builder ) {
  13008. this.value = this._value || ( this._value = this.getContext() );
  13009. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  13010. return super.setup( builder );
  13011. }
  13012. }
  13013. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  13014. /**
  13015. * A generic class that can be used by nodes which contribute
  13016. * irradiance to the scene. E.g. a light map node can be used
  13017. * as input for this module. Used in {@link NodeMaterial}.
  13018. *
  13019. * @augments LightingNode
  13020. */
  13021. class IrradianceNode extends LightingNode {
  13022. static get type() {
  13023. return 'IrradianceNode';
  13024. }
  13025. /**
  13026. * Constructs a new irradiance node.
  13027. *
  13028. * @param {Node<vec3>} node - A node contributing irradiance.
  13029. */
  13030. constructor( node ) {
  13031. super();
  13032. /**
  13033. * A node contributing irradiance.
  13034. *
  13035. * @type {Node<vec3>}
  13036. */
  13037. this.node = node;
  13038. }
  13039. setup( builder ) {
  13040. builder.context.irradiance.addAssign( this.node );
  13041. }
  13042. }
  13043. const _size$5 = /*@__PURE__*/ new Vector2();
  13044. /**
  13045. * A special type of texture node which represents the data of the current viewport
  13046. * as a texture. The module extracts data from the current bound framebuffer with
  13047. * a copy operation so no extra render pass is required to produce the texture data
  13048. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  13049. * variety of effects like refractive or transmissive materials.
  13050. *
  13051. * @augments TextureNode
  13052. */
  13053. class ViewportTextureNode extends TextureNode {
  13054. static get type() {
  13055. return 'ViewportTextureNode';
  13056. }
  13057. /**
  13058. * Constructs a new viewport texture node.
  13059. *
  13060. * @param {Node} [uvNode=screenUV] - The uv node.
  13061. * @param {?Node} [levelNode=null] - The level node.
  13062. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13063. */
  13064. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  13065. let defaultFramebuffer = null;
  13066. if ( framebufferTexture === null ) {
  13067. defaultFramebuffer = new FramebufferTexture();
  13068. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  13069. framebufferTexture = defaultFramebuffer;
  13070. } else {
  13071. defaultFramebuffer = framebufferTexture;
  13072. }
  13073. super( framebufferTexture, uvNode, levelNode );
  13074. /**
  13075. * Whether to generate mipmaps or not.
  13076. *
  13077. * @type {boolean}
  13078. * @default false
  13079. */
  13080. this.generateMipmaps = false;
  13081. /**
  13082. * The reference framebuffer texture. This is used to store the framebuffer texture
  13083. * for the current render target. If the render target changes, a new framebuffer texture
  13084. * is created automatically.
  13085. *
  13086. * @type {FramebufferTexture}
  13087. * @default null
  13088. */
  13089. this.defaultFramebuffer = defaultFramebuffer;
  13090. /**
  13091. * This flag can be used for type testing.
  13092. *
  13093. * @type {boolean}
  13094. * @readonly
  13095. * @default true
  13096. */
  13097. this.isOutputTextureNode = true;
  13098. /**
  13099. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  13100. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  13101. *
  13102. * @type {string}
  13103. * @default 'frame'
  13104. */
  13105. this.updateBeforeType = NodeUpdateType.FRAME;
  13106. /**
  13107. * The framebuffer texture for the current renderer context.
  13108. *
  13109. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  13110. * @private
  13111. */
  13112. this._cacheTextures = new WeakMap();
  13113. }
  13114. /**
  13115. * This methods returns a texture for the given render target reference.
  13116. *
  13117. * To avoid rendering errors, `ViewportTextureNode` must use unique framebuffer textures
  13118. * for different render contexts.
  13119. *
  13120. * @param {?RenderTarget} [reference=null] - The render target reference.
  13121. * @return {Texture} The framebuffer texture.
  13122. */
  13123. getTextureForReference( reference = null ) {
  13124. let defaultFramebuffer;
  13125. let cacheTextures;
  13126. if ( this.referenceNode ) {
  13127. defaultFramebuffer = this.referenceNode.defaultFramebuffer;
  13128. cacheTextures = this.referenceNode._cacheTextures;
  13129. } else {
  13130. defaultFramebuffer = this.defaultFramebuffer;
  13131. cacheTextures = this._cacheTextures;
  13132. }
  13133. if ( reference === null ) {
  13134. return defaultFramebuffer;
  13135. }
  13136. if ( cacheTextures.has( reference ) === false ) {
  13137. const framebufferTexture = defaultFramebuffer.clone();
  13138. cacheTextures.set( reference, framebufferTexture );
  13139. }
  13140. return cacheTextures.get( reference );
  13141. }
  13142. updateReference( frame ) {
  13143. const renderTarget = frame.renderer.getRenderTarget();
  13144. this.value = this.getTextureForReference( renderTarget );
  13145. return this.value;
  13146. }
  13147. updateBefore( frame ) {
  13148. const renderer = frame.renderer;
  13149. const renderTarget = renderer.getRenderTarget();
  13150. if ( renderTarget === null ) {
  13151. renderer.getDrawingBufferSize( _size$5 );
  13152. } else {
  13153. _size$5.set( renderTarget.width, renderTarget.height );
  13154. }
  13155. //
  13156. const framebufferTexture = this.getTextureForReference( renderTarget );
  13157. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  13158. framebufferTexture.image.width = _size$5.width;
  13159. framebufferTexture.image.height = _size$5.height;
  13160. framebufferTexture.needsUpdate = true;
  13161. }
  13162. //
  13163. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  13164. framebufferTexture.generateMipmaps = this.generateMipmaps;
  13165. renderer.copyFramebufferToTexture( framebufferTexture );
  13166. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  13167. }
  13168. clone() {
  13169. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  13170. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  13171. return viewportTextureNode;
  13172. }
  13173. }
  13174. /**
  13175. * TSL function for creating a viewport texture node.
  13176. *
  13177. * @tsl
  13178. * @function
  13179. * @param {?Node} [uvNode=screenUV] - The uv node.
  13180. * @param {?Node} [levelNode=null] - The level node.
  13181. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13182. * @returns {ViewportTextureNode}
  13183. */
  13184. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  13185. /**
  13186. * TSL function for creating a viewport texture node with enabled mipmap generation.
  13187. *
  13188. * @tsl
  13189. * @function
  13190. * @param {?Node} [uvNode=screenUV] - The uv node.
  13191. * @param {?Node} [levelNode=null] - The level node.
  13192. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13193. * @returns {ViewportTextureNode}
  13194. */
  13195. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  13196. let _sharedDepthbuffer = null;
  13197. /**
  13198. * Represents the depth of the current viewport as a texture. This module
  13199. * can be used in combination with viewport texture to achieve effects
  13200. * that require depth evaluation.
  13201. *
  13202. * @augments ViewportTextureNode
  13203. */
  13204. class ViewportDepthTextureNode extends ViewportTextureNode {
  13205. static get type() {
  13206. return 'ViewportDepthTextureNode';
  13207. }
  13208. /**
  13209. * Constructs a new viewport depth texture node.
  13210. *
  13211. * @param {Node} [uvNode=screenUV] - The uv node.
  13212. * @param {?Node} [levelNode=null] - The level node.
  13213. */
  13214. constructor( uvNode = screenUV, levelNode = null ) {
  13215. if ( _sharedDepthbuffer === null ) {
  13216. _sharedDepthbuffer = new DepthTexture();
  13217. }
  13218. super( uvNode, levelNode, _sharedDepthbuffer );
  13219. }
  13220. /**
  13221. * Overwritten so the method always returns the unique shared
  13222. * depth texture.
  13223. *
  13224. * @return {DepthTexture} The shared depth texture.
  13225. */
  13226. getTextureForReference() {
  13227. return _sharedDepthbuffer;
  13228. }
  13229. }
  13230. /**
  13231. * TSL function for a viewport depth texture node.
  13232. *
  13233. * @tsl
  13234. * @function
  13235. * @param {?Node} [uvNode=screenUV] - The uv node.
  13236. * @param {?Node} [levelNode=null] - The level node.
  13237. * @returns {ViewportDepthTextureNode}
  13238. */
  13239. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  13240. /**
  13241. * This node offers a collection of features in context of the depth logic in the fragment shader.
  13242. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  13243. * fragment or for depth evaluation purposes.
  13244. *
  13245. * @augments Node
  13246. */
  13247. class ViewportDepthNode extends Node {
  13248. static get type() {
  13249. return 'ViewportDepthNode';
  13250. }
  13251. /**
  13252. * Constructs a new viewport depth node.
  13253. *
  13254. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  13255. * @param {?Node} [valueNode=null] - The value node.
  13256. */
  13257. constructor( scope, valueNode = null ) {
  13258. super( 'float' );
  13259. /**
  13260. * The node behaves differently depending on which scope is selected.
  13261. *
  13262. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  13263. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  13264. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  13265. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  13266. *
  13267. * @type {('depth'|'depthBase'|'linearDepth')}
  13268. */
  13269. this.scope = scope;
  13270. /**
  13271. * Can be used to define a custom depth value.
  13272. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  13273. *
  13274. * @type {?Node}
  13275. * @default null
  13276. */
  13277. this.valueNode = valueNode;
  13278. /**
  13279. * This flag can be used for type testing.
  13280. *
  13281. * @type {boolean}
  13282. * @readonly
  13283. * @default true
  13284. */
  13285. this.isViewportDepthNode = true;
  13286. }
  13287. generate( builder ) {
  13288. const { scope } = this;
  13289. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13290. return builder.getFragDepth();
  13291. }
  13292. return super.generate( builder );
  13293. }
  13294. setup( { camera } ) {
  13295. const { scope } = this;
  13296. const value = this.valueNode;
  13297. let node = null;
  13298. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13299. if ( value !== null ) {
  13300. node = depthBase().assign( value );
  13301. }
  13302. } else if ( scope === ViewportDepthNode.DEPTH ) {
  13303. if ( camera.isPerspectiveCamera ) {
  13304. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  13305. } else {
  13306. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13307. }
  13308. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  13309. if ( value !== null ) {
  13310. if ( camera.isPerspectiveCamera ) {
  13311. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  13312. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  13313. } else {
  13314. node = value;
  13315. }
  13316. } else {
  13317. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13318. }
  13319. }
  13320. return node;
  13321. }
  13322. }
  13323. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  13324. ViewportDepthNode.DEPTH = 'depth';
  13325. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  13326. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  13327. /**
  13328. * TSL function for converting a viewZ value to an orthographic depth value.
  13329. *
  13330. * @tsl
  13331. * @function
  13332. * @param {Node<float>} viewZ - The viewZ node.
  13333. * @param {Node<float>} near - The camera's near value.
  13334. * @param {Node<float>} far - The camera's far value.
  13335. * @returns {Node<float>}
  13336. */
  13337. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  13338. /**
  13339. * TSL function for converting an orthographic depth value to a viewZ value.
  13340. *
  13341. * @tsl
  13342. * @function
  13343. * @param {Node<float>} depth - The orthographic depth.
  13344. * @param {Node<float>} near - The camera's near value.
  13345. * @param {Node<float>} far - The camera's far value.
  13346. * @returns {Node<float>}
  13347. */
  13348. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  13349. /**
  13350. * TSL function for converting a viewZ value to a perspective depth value.
  13351. *
  13352. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  13353. *
  13354. * @tsl
  13355. * @function
  13356. * @param {Node<float>} viewZ - The viewZ node.
  13357. * @param {Node<float>} near - The camera's near value.
  13358. * @param {Node<float>} far - The camera's far value.
  13359. * @returns {Node<float>}
  13360. */
  13361. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  13362. /**
  13363. * TSL function for converting a perspective depth value to a viewZ value.
  13364. *
  13365. * @tsl
  13366. * @function
  13367. * @param {Node<float>} depth - The perspective depth.
  13368. * @param {Node<float>} near - The camera's near value.
  13369. * @param {Node<float>} far - The camera's far value.
  13370. * @returns {Node<float>}
  13371. */
  13372. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  13373. /**
  13374. * TSL function for converting a viewZ value to a logarithmic depth value.
  13375. *
  13376. * @tsl
  13377. * @function
  13378. * @param {Node<float>} viewZ - The viewZ node.
  13379. * @param {Node<float>} near - The camera's near value.
  13380. * @param {Node<float>} far - The camera's far value.
  13381. * @returns {Node<float>}
  13382. */
  13383. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  13384. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  13385. // The final logarithmic depth formula used here is adapted from one described in an
  13386. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  13387. // which was an improvement upon an earlier formula one described in an
  13388. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  13389. // Ulrich's formula is the following:
  13390. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  13391. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  13392. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  13393. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  13394. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  13395. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  13396. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  13397. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  13398. // be used, and ultimately Ulrich's "near plane" version was chosen.
  13399. // Outerra eventually made another improvement to their original "C-constant" variant,
  13400. // but it still does not incorporate the camera near plane (for this version,
  13401. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  13402. // Here we make 4 changes to Ulrich's formula:
  13403. // 1. Clamp the camera near plane so we don't divide by 0.
  13404. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  13405. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  13406. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  13407. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  13408. // so we do the same here, hence the 'viewZ.negate()' call.
  13409. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  13410. near = near.max( 1e-6 ).toVar();
  13411. const numerator = log2( viewZ.negate().div( near ) );
  13412. const denominator = log2( far.div( near ) );
  13413. return numerator.div( denominator );
  13414. };
  13415. /**
  13416. * TSL function for converting a logarithmic depth value to a viewZ value.
  13417. *
  13418. * @tsl
  13419. * @function
  13420. * @param {Node<float>} depth - The logarithmic depth.
  13421. * @param {Node<float>} near - The camera's near value.
  13422. * @param {Node<float>} far - The camera's far value.
  13423. * @returns {Node<float>}
  13424. */
  13425. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  13426. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  13427. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  13428. // a negative viewZ).
  13429. const exponent = depth.mul( log( far.div( near ) ) );
  13430. return float( Math.E ).pow( exponent ).mul( near ).negate();
  13431. };
  13432. /**
  13433. * TSL function for defining a value for the current fragment's depth.
  13434. *
  13435. * @tsl
  13436. * @function
  13437. * @param {Node<float>} value - The depth value to set.
  13438. * @returns {ViewportDepthNode<float>}
  13439. */
  13440. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  13441. /**
  13442. * TSL object that represents the depth value for the current fragment.
  13443. *
  13444. * @tsl
  13445. * @type {ViewportDepthNode}
  13446. */
  13447. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  13448. /**
  13449. * TSL function for converting a perspective depth value to linear depth.
  13450. *
  13451. * @tsl
  13452. * @function
  13453. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  13454. * @returns {ViewportDepthNode<float>}
  13455. */
  13456. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  13457. /**
  13458. * TSL object that represents the linear (orthographic) depth value of the current fragment
  13459. *
  13460. * @tsl
  13461. * @type {ViewportDepthNode}
  13462. */
  13463. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  13464. depth.assign = ( value ) => depthBase( value );
  13465. /**
  13466. * This node is used in {@link NodeMaterial} to setup the clipping
  13467. * which can happen hardware-accelerated (if supported) and optionally
  13468. * use alpha-to-coverage for anti-aliasing clipped edges.
  13469. *
  13470. * @augments Node
  13471. */
  13472. class ClippingNode extends Node {
  13473. static get type() {
  13474. return 'ClippingNode';
  13475. }
  13476. /**
  13477. * Constructs a new clipping node.
  13478. *
  13479. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  13480. * the selected scope influences the behavior of the node and what type of code is generated.
  13481. */
  13482. constructor( scope = ClippingNode.DEFAULT ) {
  13483. super();
  13484. /**
  13485. * The node's scope. Similar to other nodes, the selected scope influences
  13486. * the behavior of the node and what type of code is generated.
  13487. *
  13488. * @type {('default'|'hardware'|'alphaToCoverage')}
  13489. */
  13490. this.scope = scope;
  13491. }
  13492. /**
  13493. * Setups the node depending on the selected scope.
  13494. *
  13495. * @param {NodeBuilder} builder - The current node builder.
  13496. * @return {Node} The result node.
  13497. */
  13498. setup( builder ) {
  13499. super.setup( builder );
  13500. const clippingContext = builder.clippingContext;
  13501. const { intersectionPlanes, unionPlanes } = clippingContext;
  13502. this.hardwareClipping = builder.material.hardwareClipping;
  13503. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  13504. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  13505. } else if ( this.scope === ClippingNode.HARDWARE ) {
  13506. return this.setupHardwareClipping( unionPlanes, builder );
  13507. } else {
  13508. return this.setupDefault( intersectionPlanes, unionPlanes );
  13509. }
  13510. }
  13511. /**
  13512. * Setups alpha to coverage.
  13513. *
  13514. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13515. * @param {Array<Vector4>} unionPlanes - The union planes.
  13516. * @return {Node} The result node.
  13517. */
  13518. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  13519. return Fn( () => {
  13520. const distanceToPlane = float().toVar( 'distanceToPlane' );
  13521. const distanceGradient = float().toVar( 'distanceToGradient' );
  13522. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  13523. const numUnionPlanes = unionPlanes.length;
  13524. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13525. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13526. Loop( numUnionPlanes, ( { i } ) => {
  13527. const plane = clippingPlanes.element( i );
  13528. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13529. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13530. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  13531. } );
  13532. }
  13533. const numIntersectionPlanes = intersectionPlanes.length;
  13534. if ( numIntersectionPlanes > 0 ) {
  13535. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13536. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  13537. Loop( numIntersectionPlanes, ( { i } ) => {
  13538. const plane = clippingPlanes.element( i );
  13539. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13540. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13541. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  13542. } );
  13543. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  13544. }
  13545. diffuseColor.a.mulAssign( clipOpacity );
  13546. diffuseColor.a.equal( 0.0 ).discard();
  13547. } )();
  13548. }
  13549. /**
  13550. * Setups the default clipping.
  13551. *
  13552. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13553. * @param {Array<Vector4>} unionPlanes - The union planes.
  13554. * @return {Node} The result node.
  13555. */
  13556. setupDefault( intersectionPlanes, unionPlanes ) {
  13557. return Fn( () => {
  13558. const numUnionPlanes = unionPlanes.length;
  13559. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13560. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13561. Loop( numUnionPlanes, ( { i } ) => {
  13562. const plane = clippingPlanes.element( i );
  13563. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  13564. } );
  13565. }
  13566. const numIntersectionPlanes = intersectionPlanes.length;
  13567. if ( numIntersectionPlanes > 0 ) {
  13568. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13569. const clipped = bool( true ).toVar( 'clipped' );
  13570. Loop( numIntersectionPlanes, ( { i } ) => {
  13571. const plane = clippingPlanes.element( i );
  13572. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  13573. } );
  13574. clipped.discard();
  13575. }
  13576. } )();
  13577. }
  13578. /**
  13579. * Setups hardware clipping.
  13580. *
  13581. * @param {Array<Vector4>} unionPlanes - The union planes.
  13582. * @param {NodeBuilder} builder - The current node builder.
  13583. * @return {Node} The result node.
  13584. */
  13585. setupHardwareClipping( unionPlanes, builder ) {
  13586. const numUnionPlanes = unionPlanes.length;
  13587. builder.enableHardwareClipping( numUnionPlanes );
  13588. return Fn( () => {
  13589. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13590. const hw_clip_distances = builtin( builder.getClipDistance() );
  13591. Loop( numUnionPlanes, ( { i } ) => {
  13592. const plane = clippingPlanes.element( i );
  13593. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  13594. hw_clip_distances.element( i ).assign( distance );
  13595. } );
  13596. } )();
  13597. }
  13598. }
  13599. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  13600. ClippingNode.DEFAULT = 'default';
  13601. ClippingNode.HARDWARE = 'hardware';
  13602. /**
  13603. * TSL function for setting up the default clipping logic.
  13604. *
  13605. * @tsl
  13606. * @function
  13607. * @returns {ClippingNode}
  13608. */
  13609. const clipping = () => nodeObject( new ClippingNode() );
  13610. /**
  13611. * TSL function for setting up alpha to coverage.
  13612. *
  13613. * @tsl
  13614. * @function
  13615. * @returns {ClippingNode}
  13616. */
  13617. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  13618. /**
  13619. * TSL function for setting up hardware-based clipping.
  13620. *
  13621. * @tsl
  13622. * @function
  13623. * @returns {ClippingNode}
  13624. */
  13625. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  13626. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  13627. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  13628. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13629. 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 ) ) ) ) ) );
  13630. } );
  13631. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13632. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  13633. } );
  13634. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  13635. // Find the discretized derivatives of our coordinates
  13636. const maxDeriv = max$1(
  13637. length( dFdx( position.xyz ) ),
  13638. length( dFdy( position.xyz ) )
  13639. );
  13640. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  13641. // Find two nearest log-discretized noise scales
  13642. const pixScales = vec2(
  13643. exp2( floor( log2( pixScale ) ) ),
  13644. exp2( ceil( log2( pixScale ) ) )
  13645. );
  13646. // Compute alpha thresholds at our two noise scales
  13647. const alpha = vec2(
  13648. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  13649. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  13650. );
  13651. // Factor to interpolate lerp with
  13652. const lerpFactor = fract( log2( pixScale ) );
  13653. // Interpolate alpha threshold from noise at two scales
  13654. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  13655. // Pass into CDF to compute uniformly distrib threshold
  13656. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  13657. const cases = vec3(
  13658. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  13659. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  13660. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  13661. // Find our final, uniformly distributed alpha threshold (ατ)
  13662. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  13663. // Avoids ατ == 0. Could also do ατ =1-ατ
  13664. return clamp( threshold, 1.0e-6, 1.0 );
  13665. } ).setLayout( {
  13666. name: 'getAlphaHashThreshold',
  13667. type: 'float',
  13668. inputs: [
  13669. { name: 'position', type: 'vec3' }
  13670. ]
  13671. } );
  13672. /**
  13673. * An attribute node for representing vertex colors.
  13674. *
  13675. * @augments AttributeNode
  13676. */
  13677. class VertexColorNode extends AttributeNode {
  13678. static get type() {
  13679. return 'VertexColorNode';
  13680. }
  13681. /**
  13682. * Constructs a new vertex color node.
  13683. *
  13684. * @param {number} index - The attribute index.
  13685. */
  13686. constructor( index ) {
  13687. super( null, 'vec4' );
  13688. /**
  13689. * This flag can be used for type testing.
  13690. *
  13691. * @type {boolean}
  13692. * @readonly
  13693. * @default true
  13694. */
  13695. this.isVertexColorNode = true;
  13696. /**
  13697. * The attribute index to enable more than one sets of vertex colors.
  13698. *
  13699. * @type {number}
  13700. * @default 0
  13701. */
  13702. this.index = index;
  13703. }
  13704. /**
  13705. * Overwrites the default implementation by honoring the attribute index.
  13706. *
  13707. * @param {NodeBuilder} builder - The current node builder.
  13708. * @return {string} The attribute name.
  13709. */
  13710. getAttributeName( /*builder*/ ) {
  13711. const index = this.index;
  13712. return 'color' + ( index > 0 ? index : '' );
  13713. }
  13714. generate( builder ) {
  13715. const attributeName = this.getAttributeName( builder );
  13716. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  13717. let result;
  13718. if ( geometryAttribute === true ) {
  13719. result = super.generate( builder );
  13720. } else {
  13721. // Vertex color fallback should be white
  13722. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  13723. }
  13724. return result;
  13725. }
  13726. serialize( data ) {
  13727. super.serialize( data );
  13728. data.index = this.index;
  13729. }
  13730. deserialize( data ) {
  13731. super.deserialize( data );
  13732. this.index = data.index;
  13733. }
  13734. }
  13735. /**
  13736. * TSL function for creating a reference node.
  13737. *
  13738. * @tsl
  13739. * @function
  13740. * @param {number} [index=0] - The attribute index.
  13741. * @returns {VertexColorNode}
  13742. */
  13743. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  13744. /**
  13745. * Represents a "Color Burn" blend mode.
  13746. *
  13747. * It's designed to darken the base layer's colors based on the color of the blend layer.
  13748. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  13749. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  13750. *
  13751. * @tsl
  13752. * @function
  13753. * @param {Node<vec3>} base - The base color.
  13754. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  13755. * @return {Node<vec3>} The result.
  13756. */
  13757. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13758. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  13759. } ).setLayout( {
  13760. name: 'blendBurn',
  13761. type: 'vec3',
  13762. inputs: [
  13763. { name: 'base', type: 'vec3' },
  13764. { name: 'blend', type: 'vec3' }
  13765. ]
  13766. } );
  13767. /**
  13768. * Represents a "Color Dodge" blend mode.
  13769. *
  13770. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  13771. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  13772. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  13773. *
  13774. * @tsl
  13775. * @function
  13776. * @param {Node<vec3>} base - The base color.
  13777. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13778. * @return {Node<vec3>} The result.
  13779. */
  13780. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13781. return min$1( base.div( blend.oneMinus() ), 1.0 );
  13782. } ).setLayout( {
  13783. name: 'blendDodge',
  13784. type: 'vec3',
  13785. inputs: [
  13786. { name: 'base', type: 'vec3' },
  13787. { name: 'blend', type: 'vec3' }
  13788. ]
  13789. } );
  13790. /**
  13791. * Represents a "Screen" blend mode.
  13792. *
  13793. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  13794. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  13795. * effects.
  13796. *
  13797. * @tsl
  13798. * @function
  13799. * @param {Node<vec3>} base - The base color.
  13800. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13801. * @return {Node<vec3>} The result.
  13802. */
  13803. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13804. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  13805. } ).setLayout( {
  13806. name: 'blendScreen',
  13807. type: 'vec3',
  13808. inputs: [
  13809. { name: 'base', type: 'vec3' },
  13810. { name: 'blend', type: 'vec3' }
  13811. ]
  13812. } );
  13813. /**
  13814. * Represents a "Overlay" blend mode.
  13815. *
  13816. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  13817. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  13818. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  13819. *
  13820. * @tsl
  13821. * @function
  13822. * @param {Node<vec3>} base - The base color.
  13823. * @param {Node<vec3>} blend - The blend color
  13824. * @return {Node<vec3>} The result.
  13825. */
  13826. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13827. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  13828. } ).setLayout( {
  13829. name: 'blendOverlay',
  13830. type: 'vec3',
  13831. inputs: [
  13832. { name: 'base', type: 'vec3' },
  13833. { name: 'blend', type: 'vec3' }
  13834. ]
  13835. } );
  13836. /**
  13837. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  13838. * It assumes both input colors have non-premultiplied alpha.
  13839. *
  13840. * @tsl
  13841. * @function
  13842. * @param {Node<vec4>} base - The base color.
  13843. * @param {Node<vec4>} blend - The blend color
  13844. * @return {Node<vec4>} The result.
  13845. */
  13846. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13847. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  13848. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  13849. } ).setLayout( {
  13850. name: 'blendColor',
  13851. type: 'vec4',
  13852. inputs: [
  13853. { name: 'base', type: 'vec4' },
  13854. { name: 'blend', type: 'vec4' }
  13855. ]
  13856. } );
  13857. /**
  13858. * Premultiplies the RGB channels of a color by its alpha channel.
  13859. *
  13860. * This function is useful for converting a non-premultiplied alpha color
  13861. * into a premultiplied alpha format, where the RGB values are scaled
  13862. * by the alpha value. Premultiplied alpha is often used in graphics
  13863. * rendering for certain operations, such as compositing and image processing.
  13864. *
  13865. * @tsl
  13866. * @function
  13867. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  13868. * @return {Node<vec4>} The color with premultiplied alpha.
  13869. */
  13870. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13871. return vec4( color.rgb.mul( color.a ), color.a );
  13872. }, { color: 'vec4', return: 'vec4' } );
  13873. /**
  13874. * Unpremultiplies the RGB channels of a color by its alpha channel.
  13875. *
  13876. * This function is useful for converting a premultiplied alpha color
  13877. * back into a non-premultiplied alpha format, where the RGB values are
  13878. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  13879. * rendering for certain operations, such as compositing and image processing.
  13880. *
  13881. * @tsl
  13882. * @function
  13883. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  13884. * @return {Node<vec4>} The color with non-premultiplied alpha.
  13885. */
  13886. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13887. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  13888. return vec4( color.rgb.div( color.a ), color.a );
  13889. }, { color: 'vec4', return: 'vec4' } );
  13890. // Deprecated
  13891. /**
  13892. * @tsl
  13893. * @function
  13894. * @deprecated since r171. Use {@link blendBurn} instead.
  13895. *
  13896. * @param {...any} params
  13897. * @returns {Function}
  13898. */
  13899. const burn = ( ...params ) => { // @deprecated, r171
  13900. warn( 'TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  13901. return blendBurn( params );
  13902. };
  13903. /**
  13904. * @tsl
  13905. * @function
  13906. * @deprecated since r171. Use {@link blendDodge} instead.
  13907. *
  13908. * @param {...any} params
  13909. * @returns {Function}
  13910. */
  13911. const dodge = ( ...params ) => { // @deprecated, r171
  13912. warn( 'TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  13913. return blendDodge( params );
  13914. };
  13915. /**
  13916. * @tsl
  13917. * @function
  13918. * @deprecated since r171. Use {@link blendScreen} instead.
  13919. *
  13920. * @param {...any} params
  13921. * @returns {Function}
  13922. */
  13923. const screen = ( ...params ) => { // @deprecated, r171
  13924. warn( 'TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  13925. return blendScreen( params );
  13926. };
  13927. /**
  13928. * @tsl
  13929. * @function
  13930. * @deprecated since r171. Use {@link blendOverlay} instead.
  13931. *
  13932. * @param {...any} params
  13933. * @returns {Function}
  13934. */
  13935. const overlay = ( ...params ) => { // @deprecated, r171
  13936. warn( 'TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  13937. return blendOverlay( params );
  13938. };
  13939. /**
  13940. * Base class for all node materials.
  13941. *
  13942. * @augments Material
  13943. */
  13944. class NodeMaterial extends Material {
  13945. static get type() {
  13946. return 'NodeMaterial';
  13947. }
  13948. /**
  13949. * Represents the type of the node material.
  13950. *
  13951. * @type {string}
  13952. */
  13953. get type() {
  13954. return this.constructor.type;
  13955. }
  13956. set type( _value ) { /* */ }
  13957. /**
  13958. * Constructs a new node material.
  13959. */
  13960. constructor() {
  13961. super();
  13962. /**
  13963. * This flag can be used for type testing.
  13964. *
  13965. * @type {boolean}
  13966. * @readonly
  13967. * @default true
  13968. */
  13969. this.isNodeMaterial = true;
  13970. /**
  13971. * Whether this material is affected by fog or not.
  13972. *
  13973. * @type {boolean}
  13974. * @default true
  13975. */
  13976. this.fog = true;
  13977. /**
  13978. * Whether this material is affected by lights or not.
  13979. *
  13980. * @type {boolean}
  13981. * @default false
  13982. */
  13983. this.lights = false;
  13984. /**
  13985. * Whether this material uses hardware clipping or not.
  13986. * This property is managed by the engine and should not be
  13987. * modified by apps.
  13988. *
  13989. * @type {boolean}
  13990. * @default false
  13991. */
  13992. this.hardwareClipping = false;
  13993. /**
  13994. * Node materials which set their `lights` property to `true`
  13995. * are affected by all lights of the scene. Sometimes selective
  13996. * lighting is wanted which means only _some_ lights in the scene
  13997. * affect a material. This can be achieved by creating an instance
  13998. * of {@link LightsNode} with a list of selective
  13999. * lights and assign the node to this property.
  14000. *
  14001. * ```js
  14002. * const customLightsNode = lights( [ light1, light2 ] );
  14003. * material.lightsNode = customLightsNode;
  14004. * ```
  14005. *
  14006. * @type {?LightsNode}
  14007. * @default null
  14008. */
  14009. this.lightsNode = null;
  14010. /**
  14011. * The environment of node materials can be defined by an environment
  14012. * map assigned to the `envMap` property or by `Scene.environment`
  14013. * if the node material is a PBR material. This node property allows to overwrite
  14014. * the default behavior and define the environment with a custom node.
  14015. *
  14016. * ```js
  14017. * material.envNode = pmremTexture( renderTarget.texture );
  14018. * ```
  14019. *
  14020. * @type {?Node<vec3>}
  14021. * @default null
  14022. */
  14023. this.envNode = null;
  14024. /**
  14025. * The lighting of node materials might be influenced by ambient occlusion.
  14026. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  14027. * and the respective `aoMapIntensity`. This node property allows to overwrite
  14028. * the default and define the ambient occlusion with a custom node instead.
  14029. *
  14030. * If you don't want to overwrite the diffuse color but modify the existing
  14031. * values instead, use {@link materialAO}.
  14032. *
  14033. * @type {?Node<float>}
  14034. * @default null
  14035. */
  14036. this.aoNode = null;
  14037. /**
  14038. * The diffuse color of node materials is by default inferred from the
  14039. * `color` and `map` properties. This node property allows to overwrite the default
  14040. * and define the diffuse color with a node instead.
  14041. *
  14042. * ```js
  14043. * material.colorNode = color( 0xff0000 ); // define red color
  14044. * ```
  14045. *
  14046. * If you don't want to overwrite the diffuse color but modify the existing
  14047. * values instead, use {@link materialColor}.
  14048. *
  14049. * ```js
  14050. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  14051. * ```
  14052. *
  14053. * @type {?Node<vec3>}
  14054. * @default null
  14055. */
  14056. this.colorNode = null;
  14057. /**
  14058. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  14059. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  14060. * and define the normals with a node instead.
  14061. *
  14062. * If you don't want to overwrite the normals but modify the existing values instead,
  14063. * use {@link materialNormal}.
  14064. *
  14065. * @type {?Node<vec3>}
  14066. * @default null
  14067. */
  14068. this.normalNode = null;
  14069. /**
  14070. * The opacity of node materials is by default inferred from the `opacity`
  14071. * and `alphaMap` properties. This node property allows to overwrite the default
  14072. * and define the opacity with a node instead.
  14073. *
  14074. * If you don't want to overwrite the opacity but modify the existing
  14075. * value instead, use {@link materialOpacity}.
  14076. *
  14077. * @type {?Node<float>}
  14078. * @default null
  14079. */
  14080. this.opacityNode = null;
  14081. /**
  14082. * This node can be used to implement a variety of filter-like effects. The idea is
  14083. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  14084. * to create an arbitrary effect and then assign the node composition to this property.
  14085. * Everything behind the object using this material will now be affected by a filter.
  14086. *
  14087. * ```js
  14088. * const material = new NodeMaterial()
  14089. * material.transparent = true;
  14090. *
  14091. * // everything behind the object will be monochromatic
  14092. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  14093. * ```
  14094. *
  14095. * Backdrop computations are part of the lighting so only lit materials can use this property.
  14096. *
  14097. * @type {?Node<vec3>}
  14098. * @default null
  14099. */
  14100. this.backdropNode = null;
  14101. /**
  14102. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  14103. *
  14104. * @type {?Node<float>}
  14105. * @default null
  14106. */
  14107. this.backdropAlphaNode = null;
  14108. /**
  14109. * The alpha test of node materials is by default inferred from the `alphaTest`
  14110. * property. This node property allows to overwrite the default and define the
  14111. * alpha test with a node instead.
  14112. *
  14113. * If you don't want to overwrite the alpha test but modify the existing
  14114. * value instead, use {@link materialAlphaTest}.
  14115. *
  14116. * @type {?Node<float>}
  14117. * @default null
  14118. */
  14119. this.alphaTestNode = null;
  14120. /**
  14121. * Discards the fragment if the mask value is `false`.
  14122. *
  14123. * @type {?Node<bool>}
  14124. * @default null
  14125. */
  14126. this.maskNode = null;
  14127. /**
  14128. * The local vertex positions are computed based on multiple factors like the
  14129. * attribute data, morphing or skinning. This node property allows to overwrite
  14130. * the default and define local vertex positions with nodes instead.
  14131. *
  14132. * If you don't want to overwrite the vertex positions but modify the existing
  14133. * values instead, use {@link positionLocal}.
  14134. *
  14135. *```js
  14136. * material.positionNode = positionLocal.add( displace );
  14137. * ```
  14138. *
  14139. * @type {?Node<vec3>}
  14140. * @default null
  14141. */
  14142. this.positionNode = null;
  14143. /**
  14144. * This node property is intended for logic which modifies geometry data once or per animation step.
  14145. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  14146. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  14147. * can be implemented.
  14148. *
  14149. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  14150. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  14151. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  14152. * eventually assigned to `geometryNode`.
  14153. *
  14154. * @type {?Function}
  14155. * @default null
  14156. */
  14157. this.geometryNode = null;
  14158. /**
  14159. * Allows to overwrite depth values in the fragment shader.
  14160. *
  14161. * @type {?Node<float>}
  14162. * @default null
  14163. */
  14164. this.depthNode = null;
  14165. /**
  14166. * Allows to overwrite the position used for shadow map rendering which
  14167. * is by default {@link positionWorld}, the vertex position
  14168. * in world space.
  14169. *
  14170. * @type {?Node<float>}
  14171. * @default null
  14172. */
  14173. this.receivedShadowPositionNode = null;
  14174. /**
  14175. * Allows to overwrite the geometry position used for shadow map projection which
  14176. * is by default {@link positionLocal}, the vertex position in local space.
  14177. *
  14178. * @type {?Node<float>}
  14179. * @default null
  14180. */
  14181. this.castShadowPositionNode = null;
  14182. /**
  14183. * This node can be used to influence how an object using this node material
  14184. * receive shadows.
  14185. *
  14186. * ```js
  14187. * const totalShadows = float( 1 ).toVar();
  14188. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  14189. * totalShadows.mulAssign( shadow );
  14190. * //return float( 1 ); // bypass received shadows
  14191. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  14192. * } );
  14193. *
  14194. * @type {?(Function|FunctionNode<vec4>)}
  14195. * @default null
  14196. */
  14197. this.receivedShadowNode = null;
  14198. /**
  14199. * This node can be used to influence how an object using this node material
  14200. * casts shadows. To apply a color to shadows, you can simply do:
  14201. *
  14202. * ```js
  14203. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  14204. * ```
  14205. *
  14206. * Which can be nice to fake colored shadows of semi-transparent objects. It
  14207. * is also common to use the property with `Fn` function so checks are performed
  14208. * per fragment.
  14209. *
  14210. * ```js
  14211. * materialCustomShadow.castShadowNode = Fn( () => {
  14212. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  14213. * return materialColor;
  14214. * } )();
  14215. * ```
  14216. *
  14217. * @type {?Node<vec4>}
  14218. * @default null
  14219. */
  14220. this.castShadowNode = null;
  14221. /**
  14222. * This node can be used to define the final output of the material.
  14223. *
  14224. * TODO: Explain the differences to `fragmentNode`.
  14225. *
  14226. * @type {?Node<vec4>}
  14227. * @default null
  14228. */
  14229. this.outputNode = null;
  14230. /**
  14231. * MRT configuration is done on renderer or pass level. This node allows to
  14232. * overwrite what values are written into MRT targets on material level. This
  14233. * can be useful for implementing selective FX features that should only affect
  14234. * specific objects.
  14235. *
  14236. * @type {?MRTNode}
  14237. * @default null
  14238. */
  14239. this.mrtNode = null;
  14240. /**
  14241. * This node property can be used if you need complete freedom in implementing
  14242. * the fragment shader. Assigning a node will replace the built-in material
  14243. * logic used in the fragment stage.
  14244. *
  14245. * @type {?Node<vec4>}
  14246. * @default null
  14247. */
  14248. this.fragmentNode = null;
  14249. /**
  14250. * This node property can be used if you need complete freedom in implementing
  14251. * the vertex shader. Assigning a node will replace the built-in material logic
  14252. * used in the vertex stage.
  14253. *
  14254. * @type {?Node<vec4>}
  14255. * @default null
  14256. */
  14257. this.vertexNode = null;
  14258. // Deprecated properties
  14259. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  14260. get: () => {
  14261. return this.receivedShadowPositionNode;
  14262. },
  14263. set: ( value ) => {
  14264. warn( 'NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  14265. this.receivedShadowPositionNode = value;
  14266. }
  14267. } );
  14268. }
  14269. /**
  14270. * Returns an array of child nodes for this material.
  14271. *
  14272. * @private
  14273. * @returns {Array<{property: string, childNode: Node}>}
  14274. */
  14275. _getNodeChildren() {
  14276. const children = [];
  14277. for ( const property of Object.getOwnPropertyNames( this ) ) {
  14278. if ( property.startsWith( '_' ) === true ) continue;
  14279. const object = this[ property ];
  14280. if ( object && object.isNode === true ) {
  14281. children.push( { property, childNode: object } );
  14282. }
  14283. }
  14284. return children;
  14285. }
  14286. /**
  14287. * Allows to define a custom cache key that influence the material key computation
  14288. * for render objects.
  14289. *
  14290. * @return {string} The custom cache key.
  14291. */
  14292. customProgramCacheKey() {
  14293. const values = [];
  14294. for ( const { property, childNode } of this._getNodeChildren() ) {
  14295. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey() );
  14296. }
  14297. return this.type + hashArray( values );
  14298. }
  14299. /**
  14300. * Builds this material with the given node builder.
  14301. *
  14302. * @param {NodeBuilder} builder - The current node builder.
  14303. */
  14304. build( builder ) {
  14305. this.setup( builder );
  14306. }
  14307. /**
  14308. * Setups a node material observer with the given builder.
  14309. *
  14310. * @param {NodeBuilder} builder - The current node builder.
  14311. * @return {NodeMaterialObserver} The node material observer.
  14312. */
  14313. setupObserver( builder ) {
  14314. return new NodeMaterialObserver( builder );
  14315. }
  14316. /**
  14317. * Setups the vertex and fragment stage of this node material.
  14318. *
  14319. * @param {NodeBuilder} builder - The current node builder.
  14320. */
  14321. setup( builder ) {
  14322. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  14323. builder.context.setupPositionView = () => this.setupPositionView( builder );
  14324. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  14325. const renderer = builder.renderer;
  14326. const renderTarget = renderer.getRenderTarget();
  14327. // < VERTEX STAGE >
  14328. builder.addStack();
  14329. const mvp = subBuild( this.setupVertex( builder ), 'VERTEX' );
  14330. const vertexNode = this.vertexNode || mvp;
  14331. builder.stack.outputNode = vertexNode;
  14332. this.setupHardwareClipping( builder );
  14333. if ( this.geometryNode !== null ) {
  14334. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  14335. }
  14336. builder.addFlow( 'vertex', builder.removeStack() );
  14337. // < FRAGMENT STAGE >
  14338. builder.addStack();
  14339. let resultNode;
  14340. const clippingNode = this.setupClipping( builder );
  14341. if ( this.depthWrite === true || this.depthTest === true ) {
  14342. // only write depth if depth buffer is configured
  14343. if ( renderTarget !== null ) {
  14344. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  14345. } else {
  14346. if ( renderer.depth === true ) this.setupDepth( builder );
  14347. }
  14348. }
  14349. if ( this.fragmentNode === null ) {
  14350. this.setupDiffuseColor( builder );
  14351. this.setupVariants( builder );
  14352. const outgoingLightNode = this.setupLighting( builder );
  14353. if ( clippingNode !== null ) builder.stack.addToStack( clippingNode );
  14354. // force unsigned floats - useful for RenderTargets
  14355. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  14356. resultNode = this.setupOutput( builder, basicOutput );
  14357. // OUTPUT NODE
  14358. output.assign( resultNode );
  14359. //
  14360. const isCustomOutput = this.outputNode !== null;
  14361. if ( isCustomOutput ) resultNode = this.outputNode;
  14362. // MRT
  14363. if ( renderTarget !== null ) {
  14364. const mrt = renderer.getMRT();
  14365. const materialMRT = this.mrtNode;
  14366. if ( mrt !== null ) {
  14367. if ( isCustomOutput ) output.assign( resultNode );
  14368. resultNode = mrt;
  14369. if ( materialMRT !== null ) {
  14370. resultNode = mrt.merge( materialMRT );
  14371. }
  14372. } else if ( materialMRT !== null ) {
  14373. resultNode = materialMRT;
  14374. }
  14375. }
  14376. } else {
  14377. let fragmentNode = this.fragmentNode;
  14378. if ( fragmentNode.isOutputStructNode !== true ) {
  14379. fragmentNode = vec4( fragmentNode );
  14380. }
  14381. resultNode = this.setupOutput( builder, fragmentNode );
  14382. }
  14383. builder.stack.outputNode = resultNode;
  14384. builder.addFlow( 'fragment', builder.removeStack() );
  14385. // < OBSERVER >
  14386. builder.observer = this.setupObserver( builder );
  14387. }
  14388. /**
  14389. * Setups the clipping node.
  14390. *
  14391. * @param {NodeBuilder} builder - The current node builder.
  14392. * @return {ClippingNode} The clipping node.
  14393. */
  14394. setupClipping( builder ) {
  14395. if ( builder.clippingContext === null ) return null;
  14396. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  14397. let result = null;
  14398. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  14399. const samples = builder.renderer.currentSamples;
  14400. if ( this.alphaToCoverage && samples > 1 ) {
  14401. // to be added to flow when the color/alpha value has been determined
  14402. result = clippingAlpha();
  14403. } else {
  14404. builder.stack.addToStack( clipping() );
  14405. }
  14406. }
  14407. return result;
  14408. }
  14409. /**
  14410. * Setups the hardware clipping if available on the current device.
  14411. *
  14412. * @param {NodeBuilder} builder - The current node builder.
  14413. */
  14414. setupHardwareClipping( builder ) {
  14415. this.hardwareClipping = false;
  14416. if ( builder.clippingContext === null ) return;
  14417. const candidateCount = builder.clippingContext.unionPlanes.length;
  14418. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  14419. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  14420. builder.stack.addToStack( hardwareClipping() );
  14421. this.hardwareClipping = true;
  14422. }
  14423. return;
  14424. }
  14425. /**
  14426. * Setups the depth of this material.
  14427. *
  14428. * @param {NodeBuilder} builder - The current node builder.
  14429. */
  14430. setupDepth( builder ) {
  14431. const { renderer, camera } = builder;
  14432. // Depth
  14433. let depthNode = this.depthNode;
  14434. if ( depthNode === null ) {
  14435. const mrt = renderer.getMRT();
  14436. if ( mrt && mrt.has( 'depth' ) ) {
  14437. depthNode = mrt.get( 'depth' );
  14438. } else if ( renderer.logarithmicDepthBuffer === true ) {
  14439. if ( camera.isPerspectiveCamera ) {
  14440. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  14441. } else {
  14442. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14443. }
  14444. }
  14445. }
  14446. if ( depthNode !== null ) {
  14447. depth.assign( depthNode ).toStack();
  14448. }
  14449. }
  14450. /**
  14451. * Setups the position node in view space. This method exists
  14452. * so derived node materials can modify the implementation e.g. sprite materials.
  14453. *
  14454. * @param {NodeBuilder} builder - The current node builder.
  14455. * @return {Node<vec3>} The position in view space.
  14456. */
  14457. setupPositionView( /*builder*/ ) {
  14458. return modelViewMatrix.mul( positionLocal ).xyz;
  14459. }
  14460. /**
  14461. * Setups the position in clip space.
  14462. *
  14463. * @param {NodeBuilder} builder - The current node builder.
  14464. * @return {Node<vec4>} The position in view space.
  14465. */
  14466. setupModelViewProjection( /*builder*/ ) {
  14467. return cameraProjectionMatrix.mul( positionView );
  14468. }
  14469. /**
  14470. * Setups the logic for the vertex stage.
  14471. *
  14472. * @param {NodeBuilder} builder - The current node builder.
  14473. * @return {Node<vec4>} The position in clip space.
  14474. */
  14475. setupVertex( builder ) {
  14476. builder.addStack();
  14477. this.setupPosition( builder );
  14478. builder.context.vertex = builder.removeStack();
  14479. return modelViewProjection;
  14480. }
  14481. /**
  14482. * Setups the computation of the position in local space.
  14483. *
  14484. * @param {NodeBuilder} builder - The current node builder.
  14485. * @return {Node<vec3>} The position in local space.
  14486. */
  14487. setupPosition( builder ) {
  14488. const { object, geometry } = builder;
  14489. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  14490. morphReference( object ).toStack();
  14491. }
  14492. if ( object.isSkinnedMesh === true ) {
  14493. skinning( object ).toStack();
  14494. }
  14495. if ( this.displacementMap ) {
  14496. const displacementMap = materialReference( 'displacementMap', 'texture' );
  14497. const displacementScale = materialReference( 'displacementScale', 'float' );
  14498. const displacementBias = materialReference( 'displacementBias', 'float' );
  14499. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  14500. }
  14501. if ( object.isBatchedMesh ) {
  14502. batch( object ).toStack();
  14503. }
  14504. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  14505. instancedMesh( object ).toStack();
  14506. }
  14507. if ( this.positionNode !== null ) {
  14508. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  14509. }
  14510. return positionLocal;
  14511. }
  14512. /**
  14513. * Setups the computation of the material's diffuse color.
  14514. *
  14515. * @param {NodeBuilder} builder - The current node builder.
  14516. * @param {BufferGeometry} geometry - The geometry.
  14517. */
  14518. setupDiffuseColor( builder ) {
  14519. const { object, geometry } = builder;
  14520. // MASK
  14521. if ( this.maskNode !== null ) {
  14522. // Discard if the mask is `false`
  14523. bool( this.maskNode ).not().discard();
  14524. }
  14525. // COLOR
  14526. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  14527. // VERTEX COLORS
  14528. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  14529. colorNode = colorNode.mul( vertexColor() );
  14530. }
  14531. // INSTANCED COLORS
  14532. if ( object.instanceColor ) {
  14533. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  14534. colorNode = instanceColor.mul( colorNode );
  14535. }
  14536. if ( object.isBatchedMesh && object._colorsTexture ) {
  14537. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  14538. colorNode = batchColor.mul( colorNode );
  14539. }
  14540. // DIFFUSE COLOR
  14541. diffuseColor.assign( colorNode );
  14542. // OPACITY
  14543. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14544. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  14545. // ALPHA TEST
  14546. let alphaTestNode = null;
  14547. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  14548. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  14549. if ( this.alphaToCoverage === true ) {
  14550. diffuseColor.a = smoothstep( alphaTestNode, alphaTestNode.add( fwidth( diffuseColor.a ) ), diffuseColor.a );
  14551. diffuseColor.a.lessThanEqual( 0 ).discard();
  14552. } else {
  14553. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  14554. }
  14555. }
  14556. // ALPHA HASH
  14557. if ( this.alphaHash === true ) {
  14558. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  14559. }
  14560. // OPAQUE
  14561. if ( builder.isOpaque() ) {
  14562. diffuseColor.a.assign( 1.0 );
  14563. }
  14564. }
  14565. /**
  14566. * Abstract interface method that can be implemented by derived materials
  14567. * to setup material-specific node variables.
  14568. *
  14569. * @abstract
  14570. * @param {NodeBuilder} builder - The current node builder.
  14571. */
  14572. setupVariants( /*builder*/ ) {
  14573. // Interface function.
  14574. }
  14575. /**
  14576. * Setups the outgoing light node variable
  14577. *
  14578. * @return {Node<vec3>} The outgoing light node.
  14579. */
  14580. setupOutgoingLight() {
  14581. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  14582. }
  14583. /**
  14584. * Setups the normal node from the material.
  14585. *
  14586. * @return {Node<vec3>} The normal node.
  14587. */
  14588. setupNormal() {
  14589. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  14590. }
  14591. /**
  14592. * Setups the environment node from the material.
  14593. *
  14594. * @param {NodeBuilder} builder - The current node builder.
  14595. * @return {Node<vec4>} The environment node.
  14596. */
  14597. setupEnvironment( /*builder*/ ) {
  14598. let node = null;
  14599. if ( this.envNode ) {
  14600. node = this.envNode;
  14601. } else if ( this.envMap ) {
  14602. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  14603. }
  14604. return node;
  14605. }
  14606. /**
  14607. * Setups the light map node from the material.
  14608. *
  14609. * @param {NodeBuilder} builder - The current node builder.
  14610. * @return {Node<vec3>} The light map node.
  14611. */
  14612. setupLightMap( builder ) {
  14613. let node = null;
  14614. if ( builder.material.lightMap ) {
  14615. node = new IrradianceNode( materialLightMap );
  14616. }
  14617. return node;
  14618. }
  14619. /**
  14620. * Setups the lights node based on the scene, environment and material.
  14621. *
  14622. * @param {NodeBuilder} builder - The current node builder.
  14623. * @return {LightsNode} The lights node.
  14624. */
  14625. setupLights( builder ) {
  14626. const materialLightsNode = [];
  14627. //
  14628. const envNode = this.setupEnvironment( builder );
  14629. if ( envNode && envNode.isLightingNode ) {
  14630. materialLightsNode.push( envNode );
  14631. }
  14632. const lightMapNode = this.setupLightMap( builder );
  14633. if ( lightMapNode && lightMapNode.isLightingNode ) {
  14634. materialLightsNode.push( lightMapNode );
  14635. }
  14636. if ( this.aoNode !== null || builder.material.aoMap ) {
  14637. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  14638. materialLightsNode.push( new AONode( aoNode ) );
  14639. }
  14640. let lightsN = this.lightsNode || builder.lightsNode;
  14641. if ( materialLightsNode.length > 0 ) {
  14642. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  14643. }
  14644. return lightsN;
  14645. }
  14646. /**
  14647. * This method should be implemented by most derived materials
  14648. * since it defines the material's lighting model.
  14649. *
  14650. * @abstract
  14651. * @param {NodeBuilder} builder - The current node builder.
  14652. * @return {LightingModel} The lighting model.
  14653. */
  14654. setupLightingModel( /*builder*/ ) {
  14655. // Interface function.
  14656. }
  14657. /**
  14658. * Setups the outgoing light node.
  14659. *
  14660. * @param {NodeBuilder} builder - The current node builder.
  14661. * @return {Node<vec3>} The outgoing light node.
  14662. */
  14663. setupLighting( builder ) {
  14664. const { material } = builder;
  14665. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  14666. // OUTGOING LIGHT
  14667. const lights = this.lights === true || this.lightsNode !== null;
  14668. const lightsNode = lights ? this.setupLights( builder ) : null;
  14669. let outgoingLightNode = this.setupOutgoingLight( builder );
  14670. if ( lightsNode && lightsNode.getScope().hasLights ) {
  14671. const lightingModel = this.setupLightingModel( builder ) || null;
  14672. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  14673. } else if ( backdropNode !== null ) {
  14674. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  14675. }
  14676. // EMISSIVE
  14677. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  14678. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  14679. outgoingLightNode = outgoingLightNode.add( emissive );
  14680. }
  14681. return outgoingLightNode;
  14682. }
  14683. /**
  14684. * Setup the fog.
  14685. *
  14686. * @param {NodeBuilder} builder - The current node builder.
  14687. * @param {Node<vec4>} outputNode - The existing output node.
  14688. * @return {Node<vec4>} The output node.
  14689. */
  14690. setupFog( builder, outputNode ) {
  14691. const fogNode = builder.fogNode;
  14692. if ( fogNode ) {
  14693. output.assign( outputNode );
  14694. outputNode = vec4( fogNode.toVar() );
  14695. }
  14696. return outputNode;
  14697. }
  14698. /**
  14699. * Setups premultiplied alpha.
  14700. *
  14701. * @param {NodeBuilder} builder - The current node builder.
  14702. * @param {Node<vec4>} outputNode - The existing output node.
  14703. * @return {Node<vec4>} The output node.
  14704. */
  14705. setupPremultipliedAlpha( builder, outputNode ) {
  14706. return premultiplyAlpha( outputNode );
  14707. }
  14708. /**
  14709. * Setups the output node.
  14710. *
  14711. * @param {NodeBuilder} builder - The current node builder.
  14712. * @param {Node<vec4>} outputNode - The existing output node.
  14713. * @return {Node<vec4>} The output node.
  14714. */
  14715. setupOutput( builder, outputNode ) {
  14716. // FOG
  14717. if ( this.fog === true ) {
  14718. outputNode = this.setupFog( builder, outputNode );
  14719. }
  14720. // PREMULTIPLIED ALPHA
  14721. if ( this.premultipliedAlpha === true ) {
  14722. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  14723. }
  14724. return outputNode;
  14725. }
  14726. /**
  14727. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  14728. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  14729. * defining all material properties of the classic type in the node type.
  14730. *
  14731. * @param {Material} material - The material to copy properties with their values to this node material.
  14732. */
  14733. setDefaultValues( material ) {
  14734. // This approach is to reuse the native refreshUniforms*
  14735. // and turn available the use of features like transmission and environment in core
  14736. for ( const property in material ) {
  14737. const value = material[ property ];
  14738. if ( this[ property ] === undefined ) {
  14739. this[ property ] = value;
  14740. if ( value && value.clone ) this[ property ] = value.clone();
  14741. }
  14742. }
  14743. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  14744. for ( const key in descriptors ) {
  14745. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  14746. descriptors[ key ].get !== undefined ) {
  14747. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  14748. }
  14749. }
  14750. }
  14751. /**
  14752. * Serializes this material to JSON.
  14753. *
  14754. * @param {?(Object|string)} meta - The meta information for serialization.
  14755. * @return {Object} The serialized node.
  14756. */
  14757. toJSON( meta ) {
  14758. const isRoot = ( meta === undefined || typeof meta === 'string' );
  14759. if ( isRoot ) {
  14760. meta = {
  14761. textures: {},
  14762. images: {},
  14763. nodes: {}
  14764. };
  14765. }
  14766. const data = Material.prototype.toJSON.call( this, meta );
  14767. data.inputNodes = {};
  14768. for ( const { property, childNode } of this._getNodeChildren() ) {
  14769. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  14770. }
  14771. // TODO: Copied from Object3D.toJSON
  14772. function extractFromCache( cache ) {
  14773. const values = [];
  14774. for ( const key in cache ) {
  14775. const data = cache[ key ];
  14776. delete data.metadata;
  14777. values.push( data );
  14778. }
  14779. return values;
  14780. }
  14781. if ( isRoot ) {
  14782. const textures = extractFromCache( meta.textures );
  14783. const images = extractFromCache( meta.images );
  14784. const nodes = extractFromCache( meta.nodes );
  14785. if ( textures.length > 0 ) data.textures = textures;
  14786. if ( images.length > 0 ) data.images = images;
  14787. if ( nodes.length > 0 ) data.nodes = nodes;
  14788. }
  14789. return data;
  14790. }
  14791. /**
  14792. * Copies the properties of the given node material to this instance.
  14793. *
  14794. * @param {NodeMaterial} source - The material to copy.
  14795. * @return {NodeMaterial} A reference to this node material.
  14796. */
  14797. copy( source ) {
  14798. this.lightsNode = source.lightsNode;
  14799. this.envNode = source.envNode;
  14800. this.aoNode = source.aoNode;
  14801. this.colorNode = source.colorNode;
  14802. this.normalNode = source.normalNode;
  14803. this.opacityNode = source.opacityNode;
  14804. this.backdropNode = source.backdropNode;
  14805. this.backdropAlphaNode = source.backdropAlphaNode;
  14806. this.alphaTestNode = source.alphaTestNode;
  14807. this.maskNode = source.maskNode;
  14808. this.positionNode = source.positionNode;
  14809. this.geometryNode = source.geometryNode;
  14810. this.depthNode = source.depthNode;
  14811. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  14812. this.castShadowPositionNode = source.castShadowPositionNode;
  14813. this.receivedShadowNode = source.receivedShadowNode;
  14814. this.castShadowNode = source.castShadowNode;
  14815. this.outputNode = source.outputNode;
  14816. this.mrtNode = source.mrtNode;
  14817. this.fragmentNode = source.fragmentNode;
  14818. this.vertexNode = source.vertexNode;
  14819. return super.copy( source );
  14820. }
  14821. }
  14822. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  14823. /**
  14824. * Node material version of {@link LineBasicMaterial}.
  14825. *
  14826. * @augments NodeMaterial
  14827. */
  14828. class LineBasicNodeMaterial extends NodeMaterial {
  14829. static get type() {
  14830. return 'LineBasicNodeMaterial';
  14831. }
  14832. /**
  14833. * Constructs a new line basic node material.
  14834. *
  14835. * @param {Object} [parameters] - The configuration parameter.
  14836. */
  14837. constructor( parameters ) {
  14838. super();
  14839. /**
  14840. * This flag can be used for type testing.
  14841. *
  14842. * @type {boolean}
  14843. * @readonly
  14844. * @default true
  14845. */
  14846. this.isLineBasicNodeMaterial = true;
  14847. this.setDefaultValues( _defaultValues$d );
  14848. this.setValues( parameters );
  14849. }
  14850. }
  14851. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  14852. /**
  14853. * Node material version of {@link LineDashedMaterial}.
  14854. *
  14855. * @augments NodeMaterial
  14856. */
  14857. class LineDashedNodeMaterial extends NodeMaterial {
  14858. static get type() {
  14859. return 'LineDashedNodeMaterial';
  14860. }
  14861. /**
  14862. * Constructs a new line dashed node material.
  14863. *
  14864. * @param {Object} [parameters] - The configuration parameter.
  14865. */
  14866. constructor( parameters ) {
  14867. super();
  14868. /**
  14869. * This flag can be used for type testing.
  14870. *
  14871. * @type {boolean}
  14872. * @readonly
  14873. * @default true
  14874. */
  14875. this.isLineDashedNodeMaterial = true;
  14876. this.setDefaultValues( _defaultValues$c );
  14877. /**
  14878. * The dash offset.
  14879. *
  14880. * @type {number}
  14881. * @default 0
  14882. */
  14883. this.dashOffset = 0;
  14884. /**
  14885. * The offset of dash materials is by default inferred from the `dashOffset`
  14886. * property. This node property allows to overwrite the default
  14887. * and define the offset with a node instead.
  14888. *
  14889. * If you don't want to overwrite the offset but modify the existing
  14890. * value instead, use {@link materialLineDashOffset}.
  14891. *
  14892. * @type {?Node<float>}
  14893. * @default null
  14894. */
  14895. this.offsetNode = null;
  14896. /**
  14897. * The scale of dash materials is by default inferred from the `scale`
  14898. * property. This node property allows to overwrite the default
  14899. * and define the scale with a node instead.
  14900. *
  14901. * If you don't want to overwrite the scale but modify the existing
  14902. * value instead, use {@link materialLineScale}.
  14903. *
  14904. * @type {?Node<float>}
  14905. * @default null
  14906. */
  14907. this.dashScaleNode = null;
  14908. /**
  14909. * The dash size of dash materials is by default inferred from the `dashSize`
  14910. * property. This node property allows to overwrite the default
  14911. * and define the dash size with a node instead.
  14912. *
  14913. * If you don't want to overwrite the dash size but modify the existing
  14914. * value instead, use {@link materialLineDashSize}.
  14915. *
  14916. * @type {?Node<float>}
  14917. * @default null
  14918. */
  14919. this.dashSizeNode = null;
  14920. /**
  14921. * The gap size of dash materials is by default inferred from the `gapSize`
  14922. * property. This node property allows to overwrite the default
  14923. * and define the gap size with a node instead.
  14924. *
  14925. * If you don't want to overwrite the gap size but modify the existing
  14926. * value instead, use {@link materialLineGapSize}.
  14927. *
  14928. * @type {?Node<float>}
  14929. * @default null
  14930. */
  14931. this.gapSizeNode = null;
  14932. this.setValues( parameters );
  14933. }
  14934. /**
  14935. * Setups the dash specific node variables.
  14936. *
  14937. * @param {NodeBuilder} builder - The current node builder.
  14938. */
  14939. setupVariants( /* builder */ ) {
  14940. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  14941. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  14942. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  14943. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  14944. dashSize.assign( dashSizeNode );
  14945. gapSize.assign( gapSizeNode );
  14946. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  14947. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  14948. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  14949. }
  14950. }
  14951. let _sharedFramebuffer = null;
  14952. /**
  14953. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  14954. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  14955. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  14956. *
  14957. * @augments ViewportTextureNode
  14958. */
  14959. class ViewportSharedTextureNode extends ViewportTextureNode {
  14960. static get type() {
  14961. return 'ViewportSharedTextureNode';
  14962. }
  14963. /**
  14964. * Constructs a new viewport shared texture node.
  14965. *
  14966. * @param {Node} [uvNode=screenUV] - The uv node.
  14967. * @param {?Node} [levelNode=null] - The level node.
  14968. */
  14969. constructor( uvNode = screenUV, levelNode = null ) {
  14970. if ( _sharedFramebuffer === null ) {
  14971. _sharedFramebuffer = new FramebufferTexture();
  14972. }
  14973. super( uvNode, levelNode, _sharedFramebuffer );
  14974. }
  14975. /**
  14976. * Overwritten so the method always returns the unique shared
  14977. * framebuffer texture.
  14978. *
  14979. * @return {FramebufferTexture} The shared framebuffer texture.
  14980. */
  14981. getTextureForReference() {
  14982. return _sharedFramebuffer;
  14983. }
  14984. updateReference() {
  14985. return this;
  14986. }
  14987. }
  14988. /**
  14989. * TSL function for creating a shared viewport texture node.
  14990. *
  14991. * @tsl
  14992. * @function
  14993. * @param {?Node} [uvNode=screenUV] - The uv node.
  14994. * @param {?Node} [levelNode=null] - The level node.
  14995. * @returns {ViewportSharedTextureNode}
  14996. */
  14997. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  14998. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  14999. /**
  15000. * This node material can be used to render lines with a size larger than one
  15001. * by representing them as instanced meshes.
  15002. *
  15003. * @augments NodeMaterial
  15004. */
  15005. class Line2NodeMaterial extends NodeMaterial {
  15006. static get type() {
  15007. return 'Line2NodeMaterial';
  15008. }
  15009. /**
  15010. * Constructs a new node material for wide line rendering.
  15011. *
  15012. * @param {Object} [parameters={}] - The configuration parameter.
  15013. */
  15014. constructor( parameters = {} ) {
  15015. super();
  15016. /**
  15017. * This flag can be used for type testing.
  15018. *
  15019. * @type {boolean}
  15020. * @readonly
  15021. * @default true
  15022. */
  15023. this.isLine2NodeMaterial = true;
  15024. this.setDefaultValues( _defaultValues$b );
  15025. /**
  15026. * Whether vertex colors should be used or not.
  15027. *
  15028. * @type {boolean}
  15029. * @default false
  15030. */
  15031. this.useColor = parameters.vertexColors;
  15032. /**
  15033. * The dash offset.
  15034. *
  15035. * @type {number}
  15036. * @default 0
  15037. */
  15038. this.dashOffset = 0;
  15039. /**
  15040. * Defines the lines color.
  15041. *
  15042. * @type {?Node<vec3>}
  15043. * @default null
  15044. */
  15045. this.lineColorNode = null;
  15046. /**
  15047. * Defines the offset.
  15048. *
  15049. * @type {?Node<float>}
  15050. * @default null
  15051. */
  15052. this.offsetNode = null;
  15053. /**
  15054. * Defines the dash scale.
  15055. *
  15056. * @type {?Node<float>}
  15057. * @default null
  15058. */
  15059. this.dashScaleNode = null;
  15060. /**
  15061. * Defines the dash size.
  15062. *
  15063. * @type {?Node<float>}
  15064. * @default null
  15065. */
  15066. this.dashSizeNode = null;
  15067. /**
  15068. * Defines the gap size.
  15069. *
  15070. * @type {?Node<float>}
  15071. * @default null
  15072. */
  15073. this.gapSizeNode = null;
  15074. /**
  15075. * Blending is set to `NoBlending` since transparency
  15076. * is not supported, yet.
  15077. *
  15078. * @type {number}
  15079. * @default 0
  15080. */
  15081. this.blending = NoBlending;
  15082. this._useDash = parameters.dashed;
  15083. this._useAlphaToCoverage = true;
  15084. this._useWorldUnits = false;
  15085. this.setValues( parameters );
  15086. }
  15087. /**
  15088. * Setups the vertex and fragment stage of this node material.
  15089. *
  15090. * @param {NodeBuilder} builder - The current node builder.
  15091. */
  15092. setup( builder ) {
  15093. const { renderer } = builder;
  15094. const useAlphaToCoverage = this._useAlphaToCoverage;
  15095. const useColor = this.useColor;
  15096. const useDash = this._useDash;
  15097. const useWorldUnits = this._useWorldUnits;
  15098. const trimSegment = Fn( ( { start, end } ) => {
  15099. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  15100. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  15101. const nearEstimate = b.mul( -0.5 ).div( a );
  15102. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  15103. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  15104. } ).setLayout( {
  15105. name: 'trimSegment',
  15106. type: 'vec4',
  15107. inputs: [
  15108. { name: 'start', type: 'vec4' },
  15109. { name: 'end', type: 'vec4' }
  15110. ]
  15111. } );
  15112. this.vertexNode = Fn( () => {
  15113. const instanceStart = attribute( 'instanceStart' );
  15114. const instanceEnd = attribute( 'instanceEnd' );
  15115. // camera space
  15116. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  15117. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  15118. if ( useDash ) {
  15119. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15120. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15121. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  15122. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  15123. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  15124. lineDistance = lineDistance.add( offsetNode );
  15125. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  15126. }
  15127. if ( useWorldUnits ) {
  15128. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  15129. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  15130. }
  15131. const aspect = viewport.z.div( viewport.w );
  15132. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  15133. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  15134. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  15135. // perhaps there is a more elegant solution -- WestLangley
  15136. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  15137. If( perspective, () => {
  15138. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  15139. end.assign( trimSegment( { start: start, end: end } ) );
  15140. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  15141. start.assign( trimSegment( { start: end, end: start } ) );
  15142. } );
  15143. } );
  15144. // clip space
  15145. const clipStart = cameraProjectionMatrix.mul( start );
  15146. const clipEnd = cameraProjectionMatrix.mul( end );
  15147. // ndc space
  15148. const ndcStart = clipStart.xyz.div( clipStart.w );
  15149. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  15150. // direction
  15151. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  15152. // account for clip-space aspect ratio
  15153. dir.x.assign( dir.x.mul( aspect ) );
  15154. dir.assign( dir.normalize() );
  15155. const clip = vec4().toVar();
  15156. if ( useWorldUnits ) {
  15157. // get the offset direction as perpendicular to the view vector
  15158. const worldDir = end.xyz.sub( start.xyz ).normalize();
  15159. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  15160. const worldUp = worldDir.cross( tmpFwd ).normalize();
  15161. const worldFwd = worldDir.cross( worldUp );
  15162. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  15163. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  15164. // height offset
  15165. const hw = materialLineWidth.mul( 0.5 );
  15166. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  15167. // don't extend the line if we're rendering dashes because we
  15168. // won't be rendering the endcaps
  15169. if ( ! useDash ) {
  15170. // cap extension
  15171. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  15172. // add width to the box
  15173. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  15174. // endcaps
  15175. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  15176. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  15177. } );
  15178. }
  15179. // project the worldpos
  15180. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  15181. // shift the depth of the projected points so the line
  15182. // segments overlap neatly
  15183. const clipPose = vec3().toVar();
  15184. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  15185. clip.z.assign( clipPose.z.mul( clip.w ) );
  15186. } else {
  15187. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  15188. // undo aspect ratio adjustment
  15189. dir.x.assign( dir.x.div( aspect ) );
  15190. offset.x.assign( offset.x.div( aspect ) );
  15191. // sign flip
  15192. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  15193. // endcaps
  15194. If( positionGeometry.y.lessThan( 0.0 ), () => {
  15195. offset.assign( offset.sub( dir ) );
  15196. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  15197. offset.assign( offset.add( dir ) );
  15198. } );
  15199. // adjust for linewidth
  15200. offset.assign( offset.mul( materialLineWidth ) );
  15201. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  15202. offset.assign( offset.div( viewport.w ) );
  15203. // select end
  15204. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  15205. // back to clip space
  15206. offset.assign( offset.mul( clip.w ) );
  15207. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  15208. }
  15209. return clip;
  15210. } )();
  15211. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  15212. const p13 = p1.sub( p3 );
  15213. const p43 = p4.sub( p3 );
  15214. const p21 = p2.sub( p1 );
  15215. const d1343 = p13.dot( p43 );
  15216. const d4321 = p43.dot( p21 );
  15217. const d1321 = p13.dot( p21 );
  15218. const d4343 = p43.dot( p43 );
  15219. const d2121 = p21.dot( p21 );
  15220. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  15221. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  15222. const mua = numer.div( denom ).clamp();
  15223. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  15224. return vec2( mua, mub );
  15225. } );
  15226. this.colorNode = Fn( () => {
  15227. const vUv = uv$1();
  15228. if ( useDash ) {
  15229. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15230. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15231. dashSize.assign( dashSizeNode );
  15232. gapSize.assign( gapSizeNode );
  15233. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  15234. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  15235. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  15236. }
  15237. const alpha = float( 1 ).toVar( 'alpha' );
  15238. if ( useWorldUnits ) {
  15239. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  15240. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  15241. // Find the closest points on the view ray and the line segment
  15242. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  15243. const lineDir = worldEnd.sub( worldStart );
  15244. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  15245. const p1 = worldStart.add( lineDir.mul( params.x ) );
  15246. const p2 = rayEnd.mul( params.y );
  15247. const delta = p1.sub( p2 );
  15248. const len = delta.length();
  15249. const norm = len.div( materialLineWidth );
  15250. if ( ! useDash ) {
  15251. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15252. const dnorm = norm.fwidth();
  15253. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  15254. } else {
  15255. norm.greaterThan( 0.5 ).discard();
  15256. }
  15257. }
  15258. } else {
  15259. // round endcaps
  15260. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15261. const a = vUv.x;
  15262. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15263. const len2 = a.mul( a ).add( b.mul( b ) );
  15264. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  15265. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15266. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  15267. } );
  15268. } else {
  15269. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15270. const a = vUv.x;
  15271. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15272. const len2 = a.mul( a ).add( b.mul( b ) );
  15273. len2.greaterThan( 1.0 ).discard();
  15274. } );
  15275. }
  15276. }
  15277. let lineColorNode;
  15278. if ( this.lineColorNode ) {
  15279. lineColorNode = this.lineColorNode;
  15280. } else {
  15281. if ( useColor ) {
  15282. const instanceColorStart = attribute( 'instanceColorStart' );
  15283. const instanceColorEnd = attribute( 'instanceColorEnd' );
  15284. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  15285. lineColorNode = instanceColor.mul( materialColor );
  15286. } else {
  15287. lineColorNode = materialColor;
  15288. }
  15289. }
  15290. return vec4( lineColorNode, alpha );
  15291. } )();
  15292. if ( this.transparent ) {
  15293. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15294. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  15295. }
  15296. super.setup( builder );
  15297. }
  15298. /**
  15299. * Whether the lines should sized in world units or not.
  15300. * When set to `false` the unit is pixel.
  15301. *
  15302. * @type {boolean}
  15303. * @default false
  15304. */
  15305. get worldUnits() {
  15306. return this._useWorldUnits;
  15307. }
  15308. set worldUnits( value ) {
  15309. if ( this._useWorldUnits !== value ) {
  15310. this._useWorldUnits = value;
  15311. this.needsUpdate = true;
  15312. }
  15313. }
  15314. /**
  15315. * Whether the lines should be dashed or not.
  15316. *
  15317. * @type {boolean}
  15318. * @default false
  15319. */
  15320. get dashed() {
  15321. return this._useDash;
  15322. }
  15323. set dashed( value ) {
  15324. if ( this._useDash !== value ) {
  15325. this._useDash = value;
  15326. this.needsUpdate = true;
  15327. }
  15328. }
  15329. /**
  15330. * Whether alpha to coverage should be used or not.
  15331. *
  15332. * @type {boolean}
  15333. * @default true
  15334. */
  15335. get alphaToCoverage() {
  15336. return this._useAlphaToCoverage;
  15337. }
  15338. set alphaToCoverage( value ) {
  15339. if ( this._useAlphaToCoverage !== value ) {
  15340. this._useAlphaToCoverage = value;
  15341. this.needsUpdate = true;
  15342. }
  15343. }
  15344. }
  15345. /**
  15346. * Packs a direction vector into a color value.
  15347. *
  15348. * @tsl
  15349. * @function
  15350. * @param {Node<vec3>} node - The direction to pack.
  15351. * @return {Node<vec3>} The color.
  15352. */
  15353. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  15354. /**
  15355. * Unpacks a color value into a direction vector.
  15356. *
  15357. * @tsl
  15358. * @function
  15359. * @param {Node<vec3>} node - The color to unpack.
  15360. * @return {Node<vec3>} The direction.
  15361. */
  15362. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  15363. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  15364. /**
  15365. * Node material version of {@link MeshNormalMaterial}.
  15366. *
  15367. * @augments NodeMaterial
  15368. */
  15369. class MeshNormalNodeMaterial extends NodeMaterial {
  15370. static get type() {
  15371. return 'MeshNormalNodeMaterial';
  15372. }
  15373. /**
  15374. * Constructs a new mesh normal node material.
  15375. *
  15376. * @param {Object} [parameters] - The configuration parameter.
  15377. */
  15378. constructor( parameters ) {
  15379. super();
  15380. /**
  15381. * This flag can be used for type testing.
  15382. *
  15383. * @type {boolean}
  15384. * @readonly
  15385. * @default true
  15386. */
  15387. this.isMeshNormalNodeMaterial = true;
  15388. this.setDefaultValues( _defaultValues$a );
  15389. this.setValues( parameters );
  15390. }
  15391. /**
  15392. * Overwrites the default implementation by computing the diffuse color
  15393. * based on the normal data.
  15394. */
  15395. setupDiffuseColor() {
  15396. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15397. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  15398. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  15399. }
  15400. }
  15401. /**
  15402. * TSL function for creating an equirect uv node.
  15403. *
  15404. * Can be used to compute texture coordinates for projecting an
  15405. * equirectangular texture onto a mesh for using it as the scene's
  15406. * background.
  15407. *
  15408. * ```js
  15409. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  15410. * ```
  15411. *
  15412. * @tsl
  15413. * @function
  15414. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  15415. * @returns {Node<vec2>}
  15416. */
  15417. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  15418. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  15419. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  15420. return vec2( u, v );
  15421. } );
  15422. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  15423. /**
  15424. * This class represents a cube render target. It is a special version
  15425. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  15426. *
  15427. * @augments WebGLCubeRenderTarget
  15428. */
  15429. class CubeRenderTarget extends WebGLCubeRenderTarget {
  15430. /**
  15431. * Constructs a new cube render target.
  15432. *
  15433. * @param {number} [size=1] - The size of the render target.
  15434. * @param {RenderTarget~Options} [options] - The configuration object.
  15435. */
  15436. constructor( size = 1, options = {} ) {
  15437. super( size, options );
  15438. /**
  15439. * This flag can be used for type testing.
  15440. *
  15441. * @type {boolean}
  15442. * @readonly
  15443. * @default true
  15444. */
  15445. this.isCubeRenderTarget = true;
  15446. }
  15447. /**
  15448. * Converts the given equirectangular texture to a cube map.
  15449. *
  15450. * @param {Renderer} renderer - The renderer.
  15451. * @param {Texture} texture - The equirectangular texture.
  15452. * @return {CubeRenderTarget} A reference to this cube render target.
  15453. */
  15454. fromEquirectangularTexture( renderer, texture$1 ) {
  15455. const currentMinFilter = texture$1.minFilter;
  15456. const currentGenerateMipmaps = texture$1.generateMipmaps;
  15457. texture$1.generateMipmaps = true;
  15458. this.texture.type = texture$1.type;
  15459. this.texture.colorSpace = texture$1.colorSpace;
  15460. this.texture.generateMipmaps = texture$1.generateMipmaps;
  15461. this.texture.minFilter = texture$1.minFilter;
  15462. this.texture.magFilter = texture$1.magFilter;
  15463. const geometry = new BoxGeometry( 5, 5, 5 );
  15464. const uvNode = equirectUV( positionWorldDirection );
  15465. const material = new NodeMaterial();
  15466. material.colorNode = texture( texture$1, uvNode, 0 );
  15467. material.side = BackSide;
  15468. material.blending = NoBlending;
  15469. const mesh = new Mesh( geometry, material );
  15470. const scene = new Scene();
  15471. scene.add( mesh );
  15472. // Avoid blurred poles
  15473. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  15474. const camera = new CubeCamera( 1, 10, this );
  15475. const currentMRT = renderer.getMRT();
  15476. renderer.setMRT( null );
  15477. camera.update( renderer, scene );
  15478. renderer.setMRT( currentMRT );
  15479. texture$1.minFilter = currentMinFilter;
  15480. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  15481. mesh.geometry.dispose();
  15482. mesh.material.dispose();
  15483. return this;
  15484. }
  15485. }
  15486. const _cache$1 = new WeakMap();
  15487. /**
  15488. * This node can be used to automatically convert environment maps in the
  15489. * equirectangular format into the cube map format.
  15490. *
  15491. * @augments TempNode
  15492. */
  15493. class CubeMapNode extends TempNode {
  15494. static get type() {
  15495. return 'CubeMapNode';
  15496. }
  15497. /**
  15498. * Constructs a new cube map node.
  15499. *
  15500. * @param {Node} envNode - The node representing the environment map.
  15501. */
  15502. constructor( envNode ) {
  15503. super( 'vec3' );
  15504. /**
  15505. * The node representing the environment map.
  15506. *
  15507. * @type {Node}
  15508. */
  15509. this.envNode = envNode;
  15510. /**
  15511. * A reference to the internal cube texture.
  15512. *
  15513. * @private
  15514. * @type {?CubeTexture}
  15515. * @default null
  15516. */
  15517. this._cubeTexture = null;
  15518. /**
  15519. * A reference to the internal cube texture node.
  15520. *
  15521. * @private
  15522. * @type {CubeTextureNode}
  15523. */
  15524. this._cubeTextureNode = cubeTexture( null );
  15525. const defaultTexture = new CubeTexture();
  15526. defaultTexture.isRenderTargetTexture = true;
  15527. /**
  15528. * A default cube texture that acts as a placeholder.
  15529. * It is used when the conversion from equirectangular to cube
  15530. * map has not finished yet for a given texture.
  15531. *
  15532. * @private
  15533. * @type {CubeTexture}
  15534. */
  15535. this._defaultTexture = defaultTexture;
  15536. /**
  15537. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  15538. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  15539. *
  15540. * @type {string}
  15541. * @default 'render'
  15542. */
  15543. this.updateBeforeType = NodeUpdateType.RENDER;
  15544. }
  15545. updateBefore( frame ) {
  15546. const { renderer, material } = frame;
  15547. const envNode = this.envNode;
  15548. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  15549. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  15550. if ( texture && texture.isTexture ) {
  15551. const mapping = texture.mapping;
  15552. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  15553. // check for converted cubemap map
  15554. if ( _cache$1.has( texture ) ) {
  15555. const cubeMap = _cache$1.get( texture );
  15556. mapTextureMapping( cubeMap, texture.mapping );
  15557. this._cubeTexture = cubeMap;
  15558. } else {
  15559. // create cube map from equirectangular map
  15560. const image = texture.image;
  15561. if ( isEquirectangularMapReady$1( image ) ) {
  15562. const renderTarget = new CubeRenderTarget( image.height );
  15563. renderTarget.fromEquirectangularTexture( renderer, texture );
  15564. mapTextureMapping( renderTarget.texture, texture.mapping );
  15565. this._cubeTexture = renderTarget.texture;
  15566. _cache$1.set( texture, renderTarget.texture );
  15567. texture.addEventListener( 'dispose', onTextureDispose );
  15568. } else {
  15569. // default cube texture as fallback when equirectangular texture is not yet loaded
  15570. this._cubeTexture = this._defaultTexture;
  15571. }
  15572. }
  15573. //
  15574. this._cubeTextureNode.value = this._cubeTexture;
  15575. } else {
  15576. // envNode already refers to a cube map
  15577. this._cubeTextureNode = this.envNode;
  15578. }
  15579. }
  15580. }
  15581. }
  15582. setup( builder ) {
  15583. this.updateBefore( builder );
  15584. return this._cubeTextureNode;
  15585. }
  15586. }
  15587. /**
  15588. * Returns true if the given equirectangular image has been fully loaded
  15589. * and is ready for further processing.
  15590. *
  15591. * @private
  15592. * @param {Image} image - The equirectangular image to check.
  15593. * @return {boolean} Whether the image is ready or not.
  15594. */
  15595. function isEquirectangularMapReady$1( image ) {
  15596. if ( image === null || image === undefined ) return false;
  15597. return image.height > 0;
  15598. }
  15599. /**
  15600. * This function is executed when `dispose()` is called on the equirectangular
  15601. * texture. In this case, the generated cube map with its render target
  15602. * is deleted as well.
  15603. *
  15604. * @private
  15605. * @param {Object} event - The event object.
  15606. */
  15607. function onTextureDispose( event ) {
  15608. const texture = event.target;
  15609. texture.removeEventListener( 'dispose', onTextureDispose );
  15610. const renderTarget = _cache$1.get( texture );
  15611. if ( renderTarget !== undefined ) {
  15612. _cache$1.delete( texture );
  15613. renderTarget.dispose();
  15614. }
  15615. }
  15616. /**
  15617. * This function makes sure the generated cube map uses the correct
  15618. * texture mapping that corresponds to the equirectangular original.
  15619. *
  15620. * @private
  15621. * @param {Texture} texture - The cube texture.
  15622. * @param {number} mapping - The original texture mapping.
  15623. */
  15624. function mapTextureMapping( texture, mapping ) {
  15625. if ( mapping === EquirectangularReflectionMapping ) {
  15626. texture.mapping = CubeReflectionMapping;
  15627. } else if ( mapping === EquirectangularRefractionMapping ) {
  15628. texture.mapping = CubeRefractionMapping;
  15629. }
  15630. }
  15631. /**
  15632. * TSL function for creating a cube map node.
  15633. *
  15634. * @tsl
  15635. * @function
  15636. * @param {Node} envNode - The node representing the environment map.
  15637. * @returns {CubeMapNode}
  15638. */
  15639. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  15640. /**
  15641. * Represents a basic model for Image-based lighting (IBL). The environment
  15642. * is defined via environment maps in the equirectangular or cube map format.
  15643. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  15644. * or {@link MeshPhongNodeMaterial}.
  15645. *
  15646. * @augments LightingNode
  15647. */
  15648. class BasicEnvironmentNode extends LightingNode {
  15649. static get type() {
  15650. return 'BasicEnvironmentNode';
  15651. }
  15652. /**
  15653. * Constructs a new basic environment node.
  15654. *
  15655. * @param {Node} [envNode=null] - A node representing the environment.
  15656. */
  15657. constructor( envNode = null ) {
  15658. super();
  15659. /**
  15660. * A node representing the environment.
  15661. *
  15662. * @type {Node}
  15663. * @default null
  15664. */
  15665. this.envNode = envNode;
  15666. }
  15667. setup( builder ) {
  15668. // environment property is used in the finish() method of BasicLightingModel
  15669. builder.context.environment = cubeMapNode( this.envNode );
  15670. }
  15671. }
  15672. /**
  15673. * A specific version of {@link IrradianceNode} that is only relevant
  15674. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  15675. * requires a special scaling factor for the light map.
  15676. *
  15677. * @augments LightingNode
  15678. */
  15679. class BasicLightMapNode extends LightingNode {
  15680. static get type() {
  15681. return 'BasicLightMapNode';
  15682. }
  15683. /**
  15684. * Constructs a new basic light map node.
  15685. *
  15686. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  15687. */
  15688. constructor( lightMapNode = null ) {
  15689. super();
  15690. /**
  15691. * The light map node.
  15692. *
  15693. * @type {?Node<vec3>}
  15694. */
  15695. this.lightMapNode = lightMapNode;
  15696. }
  15697. setup( builder ) {
  15698. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  15699. const RECIPROCAL_PI = float( 1 / Math.PI );
  15700. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  15701. }
  15702. }
  15703. /**
  15704. * Abstract class for implementing lighting models. The module defines
  15705. * multiple methods that concrete lighting models can implement. These
  15706. * methods are executed at different points during the light evaluation
  15707. * process.
  15708. */
  15709. class LightingModel {
  15710. /**
  15711. * This method is intended for setting up lighting model and context data
  15712. * which are later used in the evaluation process.
  15713. *
  15714. * @abstract
  15715. * @param {NodeBuilder} builder - The current node builder.
  15716. */
  15717. start( builder ) {
  15718. // lights ( direct )
  15719. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  15720. // indirect
  15721. this.indirect( builder );
  15722. }
  15723. /**
  15724. * This method is intended for executing final tasks like final updates
  15725. * to the outgoing light.
  15726. *
  15727. * @abstract
  15728. * @param {NodeBuilder} builder - The current node builder.
  15729. */
  15730. finish( /*builder*/ ) { }
  15731. /**
  15732. * This method is intended for implementing the direct light term and
  15733. * executed during the build process of directional, point and spot light nodes.
  15734. *
  15735. * @abstract
  15736. * @param {Object} lightData - The light data.
  15737. * @param {NodeBuilder} builder - The current node builder.
  15738. */
  15739. direct( /*lightData, builder*/ ) { }
  15740. /**
  15741. * This method is intended for implementing the direct light term for
  15742. * rect area light nodes.
  15743. *
  15744. * @abstract
  15745. * @param {Object} lightData - The light data.
  15746. * @param {NodeBuilder} builder - The current node builder.
  15747. */
  15748. directRectArea( /*lightData, builder*/ ) {}
  15749. /**
  15750. * This method is intended for implementing the indirect light term.
  15751. *
  15752. * @abstract
  15753. * @param {NodeBuilder} builder - The current node builder.
  15754. */
  15755. indirect( /*builder*/ ) { }
  15756. /**
  15757. * This method is intended for implementing the ambient occlusion term.
  15758. * Unlike other methods, this method must be called manually by the lighting
  15759. * model in its indirect term.
  15760. *
  15761. * @abstract
  15762. * @param {NodeBuilder} builder - The current node builder.
  15763. */
  15764. ambientOcclusion( /*input, stack, builder*/ ) { }
  15765. }
  15766. /**
  15767. * Represents the lighting model for unlit materials. The only light contribution
  15768. * is baked indirect lighting modulated with ambient occlusion and the material's
  15769. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  15770. *
  15771. * @augments LightingModel
  15772. */
  15773. class BasicLightingModel extends LightingModel {
  15774. /**
  15775. * Constructs a new basic lighting model.
  15776. */
  15777. constructor() {
  15778. super();
  15779. }
  15780. /**
  15781. * Implements the baked indirect lighting with its modulation.
  15782. *
  15783. * @param {NodeBuilder} builder - The current node builder.
  15784. */
  15785. indirect( { context } ) {
  15786. const ambientOcclusion = context.ambientOcclusion;
  15787. const reflectedLight = context.reflectedLight;
  15788. const irradianceLightMap = context.irradianceLightMap;
  15789. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  15790. // accumulation (baked indirect lighting only)
  15791. if ( irradianceLightMap ) {
  15792. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  15793. } else {
  15794. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  15795. }
  15796. // modulation
  15797. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15798. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  15799. }
  15800. /**
  15801. * Implements the environment mapping.
  15802. *
  15803. * @param {NodeBuilder} builder - The current node builder.
  15804. */
  15805. finish( builder ) {
  15806. const { material, context } = builder;
  15807. const outgoingLight = context.outgoingLight;
  15808. const envNode = builder.context.environment;
  15809. if ( envNode ) {
  15810. switch ( material.combine ) {
  15811. case MultiplyOperation:
  15812. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  15813. break;
  15814. case MixOperation:
  15815. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  15816. break;
  15817. case AddOperation:
  15818. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  15819. break;
  15820. default:
  15821. warn( 'BasicLightingModel: Unsupported .combine value:', material.combine );
  15822. break;
  15823. }
  15824. }
  15825. }
  15826. }
  15827. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  15828. /**
  15829. * Node material version of {@link MeshBasicMaterial}.
  15830. *
  15831. * @augments NodeMaterial
  15832. */
  15833. class MeshBasicNodeMaterial extends NodeMaterial {
  15834. static get type() {
  15835. return 'MeshBasicNodeMaterial';
  15836. }
  15837. /**
  15838. * Constructs a new mesh basic node material.
  15839. *
  15840. * @param {Object} [parameters] - The configuration parameter.
  15841. */
  15842. constructor( parameters ) {
  15843. super();
  15844. /**
  15845. * This flag can be used for type testing.
  15846. *
  15847. * @type {boolean}
  15848. * @readonly
  15849. * @default true
  15850. */
  15851. this.isMeshBasicNodeMaterial = true;
  15852. /**
  15853. * Although the basic material is by definition unlit, we set
  15854. * this property to `true` since we use a lighting model to compute
  15855. * the outgoing light of the fragment shader.
  15856. *
  15857. * @type {boolean}
  15858. * @default true
  15859. */
  15860. this.lights = true;
  15861. this.setDefaultValues( _defaultValues$9 );
  15862. this.setValues( parameters );
  15863. }
  15864. /**
  15865. * Basic materials are not affected by normal and bump maps so we
  15866. * return by default {@link normalViewGeometry}.
  15867. *
  15868. * @return {Node<vec3>} The normal node.
  15869. */
  15870. setupNormal() {
  15871. return directionToFaceDirection( normalViewGeometry ); // see #28839
  15872. }
  15873. /**
  15874. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15875. * to implement the default environment mapping.
  15876. *
  15877. * @param {NodeBuilder} builder - The current node builder.
  15878. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15879. */
  15880. setupEnvironment( builder ) {
  15881. const envNode = super.setupEnvironment( builder );
  15882. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15883. }
  15884. /**
  15885. * This method must be overwritten since light maps are evaluated
  15886. * with a special scaling factor for basic materials.
  15887. *
  15888. * @param {NodeBuilder} builder - The current node builder.
  15889. * @return {?BasicLightMapNode<vec3>} The light map node.
  15890. */
  15891. setupLightMap( builder ) {
  15892. let node = null;
  15893. if ( builder.material.lightMap ) {
  15894. node = new BasicLightMapNode( materialLightMap );
  15895. }
  15896. return node;
  15897. }
  15898. /**
  15899. * The material overwrites this method because `lights` is set to `true` but
  15900. * we still want to return the diffuse color as the outgoing light.
  15901. *
  15902. * @return {Node<vec3>} The outgoing light node.
  15903. */
  15904. setupOutgoingLight() {
  15905. return diffuseColor.rgb;
  15906. }
  15907. /**
  15908. * Setups the lighting model.
  15909. *
  15910. * @return {BasicLightingModel} The lighting model.
  15911. */
  15912. setupLightingModel() {
  15913. return new BasicLightingModel();
  15914. }
  15915. }
  15916. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  15917. // Original approximation by Christophe Schlick '94
  15918. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  15919. // Optimized variant (presented by Epic at SIGGRAPH '13)
  15920. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  15921. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  15922. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  15923. } ); // validated
  15924. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  15925. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  15926. } ); // validated
  15927. const G_BlinnPhong_Implicit = () => float( 0.25 );
  15928. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  15929. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  15930. } );
  15931. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  15932. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15933. const dotNH = normalView.dot( halfDir ).clamp();
  15934. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  15935. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  15936. const G = G_BlinnPhong_Implicit();
  15937. const D = D_BlinnPhong( { dotNH } );
  15938. return F.mul( G ).mul( D );
  15939. } );
  15940. /**
  15941. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  15942. *
  15943. * @augments BasicLightingModel
  15944. */
  15945. class PhongLightingModel extends BasicLightingModel {
  15946. /**
  15947. * Constructs a new phong lighting model.
  15948. *
  15949. * @param {boolean} [specular=true] - Whether specular is supported or not.
  15950. */
  15951. constructor( specular = true ) {
  15952. super();
  15953. /**
  15954. * Whether specular is supported or not. Set this to `false` if you are
  15955. * looking for a Lambert-like material meaning a material for non-shiny
  15956. * surfaces, without specular highlights.
  15957. *
  15958. * @type {boolean}
  15959. * @default true
  15960. */
  15961. this.specular = specular;
  15962. }
  15963. /**
  15964. * Implements the direct lighting. The specular portion is optional an can be controlled
  15965. * with the {@link PhongLightingModel#specular} flag.
  15966. *
  15967. * @param {Object} lightData - The light data.
  15968. */
  15969. direct( { lightDirection, lightColor, reflectedLight } ) {
  15970. const dotNL = normalView.dot( lightDirection ).clamp();
  15971. const irradiance = dotNL.mul( lightColor );
  15972. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15973. if ( this.specular === true ) {
  15974. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  15975. }
  15976. }
  15977. /**
  15978. * Implements the indirect lighting.
  15979. *
  15980. * @param {NodeBuilder} builder - The current node builder.
  15981. */
  15982. indirect( builder ) {
  15983. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  15984. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15985. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15986. }
  15987. }
  15988. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  15989. /**
  15990. * Node material version of {@link MeshLambertMaterial}.
  15991. *
  15992. * @augments NodeMaterial
  15993. */
  15994. class MeshLambertNodeMaterial extends NodeMaterial {
  15995. static get type() {
  15996. return 'MeshLambertNodeMaterial';
  15997. }
  15998. /**
  15999. * Constructs a new mesh lambert node material.
  16000. *
  16001. * @param {Object} [parameters] - The configuration parameter.
  16002. */
  16003. constructor( parameters ) {
  16004. super();
  16005. /**
  16006. * This flag can be used for type testing.
  16007. *
  16008. * @type {boolean}
  16009. * @readonly
  16010. * @default true
  16011. */
  16012. this.isMeshLambertNodeMaterial = true;
  16013. /**
  16014. * Set to `true` because lambert materials react on lights.
  16015. *
  16016. * @type {boolean}
  16017. * @default true
  16018. */
  16019. this.lights = true;
  16020. this.setDefaultValues( _defaultValues$8 );
  16021. this.setValues( parameters );
  16022. }
  16023. /**
  16024. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16025. * to implement the default environment mapping.
  16026. *
  16027. * @param {NodeBuilder} builder - The current node builder.
  16028. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16029. */
  16030. setupEnvironment( builder ) {
  16031. const envNode = super.setupEnvironment( builder );
  16032. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16033. }
  16034. /**
  16035. * Setups the lighting model.
  16036. *
  16037. * @return {PhongLightingModel} The lighting model.
  16038. */
  16039. setupLightingModel( /*builder*/ ) {
  16040. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  16041. }
  16042. }
  16043. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  16044. /**
  16045. * Node material version of {@link MeshPhongMaterial}.
  16046. *
  16047. * @augments NodeMaterial
  16048. */
  16049. class MeshPhongNodeMaterial extends NodeMaterial {
  16050. static get type() {
  16051. return 'MeshPhongNodeMaterial';
  16052. }
  16053. /**
  16054. * Constructs a new mesh lambert 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.isMeshPhongNodeMaterial = true;
  16068. /**
  16069. * Set to `true` because phong materials react on lights.
  16070. *
  16071. * @type {boolean}
  16072. * @default true
  16073. */
  16074. this.lights = true;
  16075. /**
  16076. * The shininess of phong materials is by default inferred from the `shininess`
  16077. * property. This node property allows to overwrite the default
  16078. * and define the shininess with a node instead.
  16079. *
  16080. * If you don't want to overwrite the shininess but modify the existing
  16081. * value instead, use {@link materialShininess}.
  16082. *
  16083. * @type {?Node<float>}
  16084. * @default null
  16085. */
  16086. this.shininessNode = null;
  16087. /**
  16088. * The specular color of phong materials is by default inferred from the
  16089. * `specular` property. This node property allows to overwrite the default
  16090. * and define the specular color with a node instead.
  16091. *
  16092. * If you don't want to overwrite the specular color but modify the existing
  16093. * value instead, use {@link materialSpecular}.
  16094. *
  16095. * @type {?Node<vec3>}
  16096. * @default null
  16097. */
  16098. this.specularNode = null;
  16099. this.setDefaultValues( _defaultValues$7 );
  16100. this.setValues( parameters );
  16101. }
  16102. /**
  16103. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16104. * to implement the default environment mapping.
  16105. *
  16106. * @param {NodeBuilder} builder - The current node builder.
  16107. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16108. */
  16109. setupEnvironment( builder ) {
  16110. const envNode = super.setupEnvironment( builder );
  16111. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16112. }
  16113. /**
  16114. * Setups the lighting model.
  16115. *
  16116. * @return {PhongLightingModel} The lighting model.
  16117. */
  16118. setupLightingModel( /*builder*/ ) {
  16119. return new PhongLightingModel();
  16120. }
  16121. /**
  16122. * Setups the phong specific node variables.
  16123. *
  16124. * @param {NodeBuilder} builder - The current node builder.
  16125. */
  16126. setupVariants( /*builder*/ ) {
  16127. // SHININESS
  16128. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16129. shininess.assign( shininessNode );
  16130. // SPECULAR COLOR
  16131. const specularNode = this.specularNode || materialSpecular;
  16132. specularColor.assign( specularNode );
  16133. }
  16134. copy( source ) {
  16135. this.shininessNode = source.shininessNode;
  16136. this.specularNode = source.specularNode;
  16137. return super.copy( source );
  16138. }
  16139. }
  16140. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  16141. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  16142. return float( 0 );
  16143. }
  16144. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  16145. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  16146. return geometryRoughness;
  16147. } );
  16148. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  16149. const { roughness } = inputs;
  16150. const geometryRoughness = getGeometryRoughness();
  16151. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  16152. roughnessFactor = roughnessFactor.add( geometryRoughness );
  16153. roughnessFactor = roughnessFactor.min( 1.0 );
  16154. return roughnessFactor;
  16155. } );
  16156. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  16157. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  16158. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  16159. const a2 = alpha.pow2();
  16160. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  16161. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  16162. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  16163. } ).setLayout( {
  16164. name: 'V_GGX_SmithCorrelated',
  16165. type: 'float',
  16166. inputs: [
  16167. { name: 'alpha', type: 'float' },
  16168. { name: 'dotNL', type: 'float' },
  16169. { name: 'dotNV', type: 'float' }
  16170. ]
  16171. } ); // validated
  16172. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16173. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  16174. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  16175. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  16176. const v = div( 0.5, gv.add( gl ) );
  16177. return v.saturate();
  16178. } ).setLayout( {
  16179. name: 'V_GGX_SmithCorrelated_Anisotropic',
  16180. type: 'float',
  16181. inputs: [
  16182. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16183. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16184. { name: 'dotTV', type: 'float', qualifier: 'in' },
  16185. { name: 'dotBV', type: 'float', qualifier: 'in' },
  16186. { name: 'dotTL', type: 'float', qualifier: 'in' },
  16187. { name: 'dotBL', type: 'float', qualifier: 'in' },
  16188. { name: 'dotNV', type: 'float', qualifier: 'in' },
  16189. { name: 'dotNL', type: 'float', qualifier: 'in' }
  16190. ]
  16191. } );
  16192. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  16193. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  16194. // alpha is "roughness squared" in Disney’s reparameterization
  16195. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  16196. const a2 = alpha.pow2();
  16197. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  16198. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  16199. } ).setLayout( {
  16200. name: 'D_GGX',
  16201. type: 'float',
  16202. inputs: [
  16203. { name: 'alpha', type: 'float' },
  16204. { name: 'dotNH', type: 'float' }
  16205. ]
  16206. } ); // validated
  16207. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  16208. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16209. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  16210. const a2 = alphaT.mul( alphaB );
  16211. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  16212. const v2 = v.dot( v );
  16213. const w2 = a2.div( v2 );
  16214. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  16215. } ).setLayout( {
  16216. name: 'D_GGX_Anisotropic',
  16217. type: 'float',
  16218. inputs: [
  16219. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16220. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16221. { name: 'dotNH', type: 'float', qualifier: 'in' },
  16222. { name: 'dotTH', type: 'float', qualifier: 'in' },
  16223. { name: 'dotBH', type: 'float', qualifier: 'in' }
  16224. ]
  16225. } );
  16226. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  16227. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16228. const alpha = roughness.pow2(); // UE4's roughness
  16229. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16230. const dotNL = normalView$1.dot( lightDirection ).clamp();
  16231. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16232. const dotNH = normalView$1.dot( halfDir ).clamp();
  16233. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16234. let F = F_Schlick( { f0, f90, dotVH } );
  16235. let V, D;
  16236. if ( defined( USE_IRIDESCENCE ) ) {
  16237. F = iridescence.mix( F, f );
  16238. }
  16239. if ( defined( USE_ANISOTROPY ) ) {
  16240. const dotTL = anisotropyT.dot( lightDirection );
  16241. const dotTV = anisotropyT.dot( positionViewDirection );
  16242. const dotTH = anisotropyT.dot( halfDir );
  16243. const dotBL = anisotropyB.dot( lightDirection );
  16244. const dotBV = anisotropyB.dot( positionViewDirection );
  16245. const dotBH = anisotropyB.dot( halfDir );
  16246. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  16247. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  16248. } else {
  16249. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  16250. D = D_GGX( { alpha, dotNH } );
  16251. }
  16252. return F.mul( V ).mul( D );
  16253. } ); // validated
  16254. /**
  16255. * Precomputed DFG LUT for Image-Based Lighting
  16256. * Resolution: 32x32
  16257. * Samples: 4096 per texel
  16258. * Format: RG16F (2 half floats per texel: scale, bias)
  16259. */
  16260. const DATA = new Uint16Array( [
  16261. 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,
  16262. 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,
  16263. 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,
  16264. 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,
  16265. 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,
  16266. 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,
  16267. 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,
  16268. 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,
  16269. 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,
  16270. 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,
  16271. 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,
  16272. 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,
  16273. 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,
  16274. 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,
  16275. 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,
  16276. 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,
  16277. 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,
  16278. 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,
  16279. 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,
  16280. 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,
  16281. 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,
  16282. 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,
  16283. 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,
  16284. 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,
  16285. 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,
  16286. 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,
  16287. 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,
  16288. 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,
  16289. 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,
  16290. 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,
  16291. 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,
  16292. 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
  16293. ] );
  16294. let lut = null;
  16295. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  16296. if ( lut === null ) {
  16297. lut = new DataTexture( DATA, 32, 32, RGFormat, HalfFloatType );
  16298. lut.minFilter = LinearFilter;
  16299. lut.magFilter = LinearFilter;
  16300. lut.wrapS = ClampToEdgeWrapping;
  16301. lut.wrapT = ClampToEdgeWrapping;
  16302. lut.generateMipmaps = false;
  16303. lut.needsUpdate = true;
  16304. }
  16305. const uv = vec2( roughness, dotNV );
  16306. return texture( lut, uv ).rg;
  16307. } );
  16308. // GGX BRDF with multi-scattering energy compensation for direct lighting
  16309. // This provides more accurate energy conservation, especially for rough materials
  16310. // Based on "Practical Multiple Scattering Compensation for Microfacet Models"
  16311. // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf
  16312. const BRDF_GGX_Multiscatter = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16313. // Single-scattering BRDF (standard GGX)
  16314. const singleScatter = BRDF_GGX( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } );
  16315. // Multi-scattering compensation
  16316. const dotNL = normalView.dot( lightDirection ).clamp();
  16317. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16318. // Precomputed DFG values for view and light directions
  16319. const dfgV = DFGApprox( { roughness: _roughness, dotNV } );
  16320. const dfgL = DFGApprox( { roughness: _roughness, dotNV: dotNL } );
  16321. // Single-scattering energy for view and light
  16322. const FssEss_V = f0.mul( dfgV.x ).add( f90.mul( dfgV.y ) );
  16323. const FssEss_L = f0.mul( dfgL.x ).add( f90.mul( dfgL.y ) );
  16324. const Ess_V = dfgV.x.add( dfgV.y );
  16325. const Ess_L = dfgL.x.add( dfgL.y );
  16326. // Energy lost to multiple scattering
  16327. const Ems_V = float( 1.0 ).sub( Ess_V );
  16328. const Ems_L = float( 1.0 ).sub( Ess_L );
  16329. // Average Fresnel reflectance
  16330. const Favg = f0.add( f0.oneMinus().mul( 0.047619 ) ); // 1/21
  16331. // Multiple scattering contribution
  16332. // Uses geometric mean of view and light contributions for better energy distribution
  16333. 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 ) );
  16334. // Energy compensation factor
  16335. const compensationFactor = Ems_V.mul( Ems_L );
  16336. const multiScatter = Fms.mul( compensationFactor );
  16337. return singleScatter.add( multiScatter );
  16338. } );
  16339. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  16340. const { dotNV, specularColor, specularF90, roughness } = inputs;
  16341. const fab = DFGApprox( { dotNV, roughness } );
  16342. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16343. } );
  16344. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  16345. const x = dotVH.oneMinus().saturate();
  16346. const x2 = x.mul( x );
  16347. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  16348. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  16349. } ).setLayout( {
  16350. name: 'Schlick_to_F0',
  16351. type: 'vec3',
  16352. inputs: [
  16353. { name: 'f', type: 'vec3' },
  16354. { name: 'f90', type: 'float' },
  16355. { name: 'dotVH', type: 'float' }
  16356. ]
  16357. } );
  16358. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16359. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  16360. const alpha = roughness.pow2();
  16361. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  16362. const invAlpha = float( 1.0 ).div( alpha );
  16363. const cos2h = dotNH.pow2();
  16364. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  16365. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  16366. } ).setLayout( {
  16367. name: 'D_Charlie',
  16368. type: 'float',
  16369. inputs: [
  16370. { name: 'roughness', type: 'float' },
  16371. { name: 'dotNH', type: 'float' }
  16372. ]
  16373. } );
  16374. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16375. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  16376. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  16377. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  16378. } ).setLayout( {
  16379. name: 'V_Neubelt',
  16380. type: 'float',
  16381. inputs: [
  16382. { name: 'dotNV', type: 'float' },
  16383. { name: 'dotNL', type: 'float' }
  16384. ]
  16385. } );
  16386. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16387. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16388. const dotNL = normalView.dot( lightDirection ).clamp();
  16389. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16390. const dotNH = normalView.dot( halfDir ).clamp();
  16391. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  16392. const V = V_Neubelt( { dotNV, dotNL } );
  16393. return sheen.mul( D ).mul( V );
  16394. } );
  16395. // Rect Area Light
  16396. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  16397. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  16398. // code: https://github.com/selfshadow/ltc_code/
  16399. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  16400. const LUT_SIZE = 64.0;
  16401. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  16402. const LUT_BIAS = 0.5 / LUT_SIZE;
  16403. const dotNV = N.dot( V ).saturate();
  16404. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  16405. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  16406. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  16407. return uv;
  16408. } ).setLayout( {
  16409. name: 'LTC_Uv',
  16410. type: 'vec2',
  16411. inputs: [
  16412. { name: 'N', type: 'vec3' },
  16413. { name: 'V', type: 'vec3' },
  16414. { name: 'roughness', type: 'float' }
  16415. ]
  16416. } );
  16417. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  16418. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  16419. // An approximation of the form factor of a horizon-clipped rectangle.
  16420. const l = f.length();
  16421. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  16422. } ).setLayout( {
  16423. name: 'LTC_ClippedSphereFormFactor',
  16424. type: 'float',
  16425. inputs: [
  16426. { name: 'f', type: 'vec3' }
  16427. ]
  16428. } );
  16429. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  16430. const x = v1.dot( v2 );
  16431. const y = x.abs().toVar();
  16432. // rational polynomial approximation to theta / sin( theta ) / 2PI
  16433. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  16434. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  16435. const v = a.div( b );
  16436. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  16437. return v1.cross( v2 ).mul( theta_sintheta );
  16438. } ).setLayout( {
  16439. name: 'LTC_EdgeVectorFormFactor',
  16440. type: 'vec3',
  16441. inputs: [
  16442. { name: 'v1', type: 'vec3' },
  16443. { name: 'v2', type: 'vec3' }
  16444. ]
  16445. } );
  16446. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  16447. // bail if point is on back side of plane of light
  16448. // assumes ccw winding order of light vertices
  16449. const v1 = p1.sub( p0 ).toVar();
  16450. const v2 = p3.sub( p0 ).toVar();
  16451. const lightNormal = v1.cross( v2 );
  16452. const result = vec3().toVar();
  16453. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16454. // construct orthonormal basis around N
  16455. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  16456. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  16457. // compute transform
  16458. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  16459. // transform rect
  16460. // & project rect onto sphere
  16461. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  16462. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  16463. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  16464. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  16465. // calculate vector form factor
  16466. const vectorFormFactor = vec3( 0 ).toVar();
  16467. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16468. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16469. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16470. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16471. // adjust for horizon clipping
  16472. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  16473. } );
  16474. return result;
  16475. } ).setLayout( {
  16476. name: 'LTC_Evaluate',
  16477. type: 'vec3',
  16478. inputs: [
  16479. { name: 'N', type: 'vec3' },
  16480. { name: 'V', type: 'vec3' },
  16481. { name: 'P', type: 'vec3' },
  16482. { name: 'mInv', type: 'mat3' },
  16483. { name: 'p0', type: 'vec3' },
  16484. { name: 'p1', type: 'vec3' },
  16485. { name: 'p2', type: 'vec3' },
  16486. { name: 'p3', type: 'vec3' }
  16487. ]
  16488. } );
  16489. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  16490. // bail if point is on back side of plane of light
  16491. // assumes ccw winding order of light vertices
  16492. const v1 = p1.sub( p0 ).toVar();
  16493. const v2 = p3.sub( p0 ).toVar();
  16494. const lightNormal = v1.cross( v2 );
  16495. const result = vec3().toVar();
  16496. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16497. // transform rect
  16498. // & project rect onto sphere
  16499. const coords0 = p0.sub( P ).normalize().toVar();
  16500. const coords1 = p1.sub( P ).normalize().toVar();
  16501. const coords2 = p2.sub( P ).normalize().toVar();
  16502. const coords3 = p3.sub( P ).normalize().toVar();
  16503. // calculate vector form factor
  16504. const vectorFormFactor = vec3( 0 ).toVar();
  16505. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16506. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16507. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16508. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16509. // adjust for horizon clipping
  16510. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  16511. } );
  16512. return result;
  16513. } ).setLayout( {
  16514. name: 'LTC_Evaluate',
  16515. type: 'vec3',
  16516. inputs: [
  16517. { name: 'P', type: 'vec3' },
  16518. { name: 'p0', type: 'vec3' },
  16519. { name: 'p1', type: 'vec3' },
  16520. { name: 'p2', type: 'vec3' },
  16521. { name: 'p3', type: 'vec3' }
  16522. ]
  16523. } );
  16524. // Mipped Bicubic Texture Filtering by N8
  16525. // https://www.shadertoy.com/view/Dl2SDW
  16526. const bC = 1.0 / 6.0;
  16527. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  16528. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  16529. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  16530. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  16531. const g0 = ( a ) => w0( a ).add( w1( a ) );
  16532. const g1 = ( a ) => w2( a ).add( w3( a ) );
  16533. // h0 and h1 are the two offset functions
  16534. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  16535. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  16536. const bicubic = ( textureNode, texelSize, lod ) => {
  16537. const uv = textureNode.uvNode;
  16538. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  16539. const iuv = floor( uvScaled );
  16540. const fuv = fract( uvScaled );
  16541. const g0x = g0( fuv.x );
  16542. const g1x = g1( fuv.x );
  16543. const h0x = h0( fuv.x );
  16544. const h1x = h1( fuv.x );
  16545. const h0y = h0( fuv.y );
  16546. const h1y = h1( fuv.y );
  16547. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16548. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16549. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16550. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16551. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  16552. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  16553. return a.add( b );
  16554. };
  16555. /**
  16556. * Applies mipped bicubic texture filtering to the given texture node.
  16557. *
  16558. * @tsl
  16559. * @function
  16560. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16561. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  16562. * @return {Node} The filtered texture sample.
  16563. */
  16564. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  16565. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  16566. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  16567. const fLodSizeInv = div( 1.0, fLodSize );
  16568. const cLodSizeInv = div( 1.0, cLodSize );
  16569. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  16570. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  16571. return fract( lodNode ).mix( fSample, cSample );
  16572. } );
  16573. /**
  16574. * Applies mipped bicubic texture filtering to the given texture node.
  16575. *
  16576. * @tsl
  16577. * @function
  16578. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16579. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  16580. * @return {Node} The filtered texture sample.
  16581. */
  16582. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  16583. const lod = strength.mul( maxMipLevel( textureNode ) );
  16584. return textureBicubicLevel( textureNode, lod );
  16585. } );
  16586. //
  16587. // Transmission
  16588. //
  16589. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  16590. // Direction of refracted light.
  16591. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  16592. // Compute rotation-independent scaling of the model matrix.
  16593. const modelScale = vec3(
  16594. length( modelMatrix[ 0 ].xyz ),
  16595. length( modelMatrix[ 1 ].xyz ),
  16596. length( modelMatrix[ 2 ].xyz )
  16597. );
  16598. // The thickness is specified in local space.
  16599. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  16600. } ).setLayout( {
  16601. name: 'getVolumeTransmissionRay',
  16602. type: 'vec3',
  16603. inputs: [
  16604. { name: 'n', type: 'vec3' },
  16605. { name: 'v', type: 'vec3' },
  16606. { name: 'thickness', type: 'float' },
  16607. { name: 'ior', type: 'float' },
  16608. { name: 'modelMatrix', type: 'mat4' }
  16609. ]
  16610. } );
  16611. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  16612. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  16613. // an IOR of 1.5 results in the default amount of microfacet refraction.
  16614. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  16615. } ).setLayout( {
  16616. name: 'applyIorToRoughness',
  16617. type: 'float',
  16618. inputs: [
  16619. { name: 'roughness', type: 'float' },
  16620. { name: 'ior', type: 'float' }
  16621. ]
  16622. } );
  16623. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  16624. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  16625. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  16626. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  16627. const transmissionSample = vTexture.sample( fragCoord );
  16628. //const transmissionSample = viewportMipTexture( fragCoord );
  16629. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  16630. return textureBicubicLevel( transmissionSample, lod );
  16631. } );
  16632. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  16633. If( attenuationDistance.notEqual( 0 ), () => {
  16634. // Compute light attenuation using Beer's law.
  16635. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  16636. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  16637. return transmittance;
  16638. } );
  16639. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  16640. return vec3( 1.0 );
  16641. } ).setLayout( {
  16642. name: 'volumeAttenuation',
  16643. type: 'vec3',
  16644. inputs: [
  16645. { name: 'transmissionDistance', type: 'float' },
  16646. { name: 'attenuationColor', type: 'vec3' },
  16647. { name: 'attenuationDistance', type: 'float' }
  16648. ]
  16649. } );
  16650. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  16651. let transmittedLight, transmittance;
  16652. if ( dispersion ) {
  16653. transmittedLight = vec4().toVar();
  16654. transmittance = vec3().toVar();
  16655. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  16656. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  16657. Loop( { start: 0, end: 3 }, ( { i } ) => {
  16658. const ior = iors.element( i );
  16659. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16660. const refractedRayExit = position.add( transmissionRay );
  16661. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16662. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16663. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16664. refractionCoords.addAssign( 1.0 );
  16665. refractionCoords.divAssign( 2.0 );
  16666. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16667. // Sample framebuffer to get pixel the refracted ray hits.
  16668. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  16669. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  16670. transmittedLight.a.addAssign( transmissionSample.a );
  16671. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  16672. } );
  16673. transmittedLight.a.divAssign( 3.0 );
  16674. } else {
  16675. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16676. const refractedRayExit = position.add( transmissionRay );
  16677. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16678. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16679. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16680. refractionCoords.addAssign( 1.0 );
  16681. refractionCoords.divAssign( 2.0 );
  16682. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16683. // Sample framebuffer to get pixel the refracted ray hits.
  16684. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  16685. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  16686. }
  16687. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  16688. const dotNV = n.dot( v ).clamp();
  16689. // Get the specular component.
  16690. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  16691. dotNV,
  16692. specularColor,
  16693. specularF90,
  16694. roughness
  16695. } ) );
  16696. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  16697. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  16698. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  16699. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  16700. } );
  16701. //
  16702. // Iridescence
  16703. //
  16704. // XYZ to linear-sRGB color space
  16705. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  16706. 3.2404542, -0.969266, 0.0556434,
  16707. -1.5371385, 1.8760108, -0.2040259,
  16708. -0.4985314, 0.0415560, 1.0572252
  16709. );
  16710. // Assume air interface for top
  16711. // Note: We don't handle the case fresnel0 == 1
  16712. const Fresnel0ToIor = ( fresnel0 ) => {
  16713. const sqrtF0 = fresnel0.sqrt();
  16714. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  16715. };
  16716. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  16717. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  16718. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  16719. };
  16720. // Fresnel equations for dielectric/dielectric interfaces.
  16721. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  16722. // Evaluation XYZ sensitivity curves in Fourier space
  16723. const evalSensitivity = ( OPD, shift ) => {
  16724. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  16725. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  16726. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  16727. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  16728. 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() );
  16729. 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() );
  16730. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  16731. const rgb = XYZ_TO_REC709.mul( xyz );
  16732. return rgb;
  16733. };
  16734. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  16735. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  16736. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  16737. // Evaluate the cosTheta on the base layer (Snell law)
  16738. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  16739. // Handle TIR:
  16740. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  16741. If( cosTheta2Sq.lessThan( 0 ), () => {
  16742. return vec3( 1.0 );
  16743. } );
  16744. const cosTheta2 = cosTheta2Sq.sqrt();
  16745. // First interface
  16746. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  16747. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  16748. //const R21 = R12;
  16749. const T121 = R12.oneMinus();
  16750. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  16751. const phi21 = float( Math.PI ).sub( phi12 );
  16752. // Second interface
  16753. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  16754. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  16755. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  16756. const phi23 = vec3(
  16757. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16758. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16759. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  16760. );
  16761. // Phase shift
  16762. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  16763. const phi = vec3( phi21 ).add( phi23 );
  16764. // Compound terms
  16765. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  16766. const r123 = R123.sqrt();
  16767. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  16768. // Reflectance term for m = 0 (DC term amplitude)
  16769. const C0 = R12.add( Rs );
  16770. const I = C0.toVar();
  16771. // Reflectance term for m > 0 (pairs of diracs)
  16772. const Cm = Rs.sub( T121 ).toVar();
  16773. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  16774. Cm.mulAssign( r123 );
  16775. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  16776. I.addAssign( Cm.mul( Sm ) );
  16777. } );
  16778. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  16779. return I.max( vec3( 0.0 ) );
  16780. } ).setLayout( {
  16781. name: 'evalIridescence',
  16782. type: 'vec3',
  16783. inputs: [
  16784. { name: 'outsideIOR', type: 'float' },
  16785. { name: 'eta2', type: 'float' },
  16786. { name: 'cosTheta1', type: 'float' },
  16787. { name: 'thinFilmThickness', type: 'float' },
  16788. { name: 'baseF0', type: 'vec3' }
  16789. ]
  16790. } );
  16791. //
  16792. // Sheen
  16793. //
  16794. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  16795. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  16796. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  16797. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  16798. const dotNV = normal.dot( viewDir ).saturate();
  16799. const r2 = roughness.pow2();
  16800. const a = select(
  16801. roughness.lessThan( 0.25 ),
  16802. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  16803. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  16804. );
  16805. const b = select(
  16806. roughness.lessThan( 0.25 ),
  16807. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  16808. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  16809. );
  16810. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  16811. return DG.mul( 1.0 / Math.PI ).saturate();
  16812. } );
  16813. const clearcoatF0 = vec3( 0.04 );
  16814. const clearcoatF90 = float( 1 );
  16815. /**
  16816. * Represents the lighting model for a PBR material.
  16817. *
  16818. * @augments LightingModel
  16819. */
  16820. class PhysicalLightingModel extends LightingModel {
  16821. /**
  16822. * Constructs a new physical lighting model.
  16823. *
  16824. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  16825. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  16826. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  16827. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  16828. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  16829. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  16830. */
  16831. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  16832. super();
  16833. /**
  16834. * Whether clearcoat is supported or not.
  16835. *
  16836. * @type {boolean}
  16837. * @default false
  16838. */
  16839. this.clearcoat = clearcoat;
  16840. /**
  16841. * Whether sheen is supported or not.
  16842. *
  16843. * @type {boolean}
  16844. * @default false
  16845. */
  16846. this.sheen = sheen;
  16847. /**
  16848. * Whether iridescence is supported or not.
  16849. *
  16850. * @type {boolean}
  16851. * @default false
  16852. */
  16853. this.iridescence = iridescence;
  16854. /**
  16855. * Whether anisotropy is supported or not.
  16856. *
  16857. * @type {boolean}
  16858. * @default false
  16859. */
  16860. this.anisotropy = anisotropy;
  16861. /**
  16862. * Whether transmission is supported or not.
  16863. *
  16864. * @type {boolean}
  16865. * @default false
  16866. */
  16867. this.transmission = transmission;
  16868. /**
  16869. * Whether dispersion is supported or not.
  16870. *
  16871. * @type {boolean}
  16872. * @default false
  16873. */
  16874. this.dispersion = dispersion;
  16875. /**
  16876. * The clear coat radiance.
  16877. *
  16878. * @type {?Node}
  16879. * @default null
  16880. */
  16881. this.clearcoatRadiance = null;
  16882. /**
  16883. * The clear coat specular direct.
  16884. *
  16885. * @type {?Node}
  16886. * @default null
  16887. */
  16888. this.clearcoatSpecularDirect = null;
  16889. /**
  16890. * The clear coat specular indirect.
  16891. *
  16892. * @type {?Node}
  16893. * @default null
  16894. */
  16895. this.clearcoatSpecularIndirect = null;
  16896. /**
  16897. * The sheen specular direct.
  16898. *
  16899. * @type {?Node}
  16900. * @default null
  16901. */
  16902. this.sheenSpecularDirect = null;
  16903. /**
  16904. * The sheen specular indirect.
  16905. *
  16906. * @type {?Node}
  16907. * @default null
  16908. */
  16909. this.sheenSpecularIndirect = null;
  16910. /**
  16911. * The iridescence Fresnel.
  16912. *
  16913. * @type {?Node}
  16914. * @default null
  16915. */
  16916. this.iridescenceFresnel = null;
  16917. /**
  16918. * The iridescence F0.
  16919. *
  16920. * @type {?Node}
  16921. * @default null
  16922. */
  16923. this.iridescenceF0 = null;
  16924. }
  16925. /**
  16926. * Depending on what features are requested, the method prepares certain node variables
  16927. * which are later used for lighting computations.
  16928. *
  16929. * @param {NodeBuilder} builder - The current node builder.
  16930. */
  16931. start( builder ) {
  16932. if ( this.clearcoat === true ) {
  16933. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  16934. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  16935. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  16936. }
  16937. if ( this.sheen === true ) {
  16938. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  16939. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  16940. }
  16941. if ( this.iridescence === true ) {
  16942. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  16943. this.iridescenceFresnel = evalIridescence( {
  16944. outsideIOR: float( 1.0 ),
  16945. eta2: iridescenceIOR,
  16946. cosTheta1: dotNVi,
  16947. thinFilmThickness: iridescenceThickness,
  16948. baseF0: specularColor
  16949. } );
  16950. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  16951. }
  16952. if ( this.transmission === true ) {
  16953. const position = positionWorld;
  16954. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  16955. const n = normalWorld;
  16956. const context = builder.context;
  16957. context.backdrop = getIBLVolumeRefraction(
  16958. n,
  16959. v,
  16960. roughness,
  16961. diffuseColor,
  16962. specularColor,
  16963. specularF90, // specularF90
  16964. position, // positionWorld
  16965. modelWorldMatrix, // modelMatrix
  16966. cameraViewMatrix, // viewMatrix
  16967. cameraProjectionMatrix, // projMatrix
  16968. ior,
  16969. thickness,
  16970. attenuationColor,
  16971. attenuationDistance,
  16972. this.dispersion ? dispersion : null
  16973. );
  16974. context.backdropAlpha = transmission;
  16975. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  16976. }
  16977. super.start( builder );
  16978. }
  16979. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  16980. // Approximates multi-scattering in order to preserve energy.
  16981. // http://www.jcgt.org/published/0008/01/03/
  16982. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  16983. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16984. const fab = DFGApprox( { roughness, dotNV } );
  16985. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  16986. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16987. const Ess = fab.x.add( fab.y );
  16988. const Ems = Ess.oneMinus();
  16989. const Favg = Fr.add( Fr.oneMinus().mul( 0.047619 ) ); // 1/21
  16990. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  16991. singleScatter.addAssign( FssEss );
  16992. multiScatter.addAssign( Fms.mul( Ems ) );
  16993. }
  16994. /**
  16995. * Implements the direct light.
  16996. *
  16997. * @param {Object} lightData - The light data.
  16998. * @param {NodeBuilder} builder - The current node builder.
  16999. */
  17000. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  17001. const dotNL = normalView.dot( lightDirection ).clamp();
  17002. const irradiance = dotNL.mul( lightColor );
  17003. if ( this.sheen === true ) {
  17004. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  17005. }
  17006. if ( this.clearcoat === true ) {
  17007. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  17008. const ccIrradiance = dotNLcc.mul( lightColor );
  17009. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  17010. }
  17011. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  17012. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_GGX_Multiscatter( { lightDirection, f0: specularColor, f90: 1, roughness, f: this.iridescenceFresnel, USE_IRIDESCENCE: this.iridescence, USE_ANISOTROPY: this.anisotropy } ) ) );
  17013. }
  17014. /**
  17015. * This method is intended for implementing the direct light term for
  17016. * rect area light nodes.
  17017. *
  17018. * @param {Object} input - The input data.
  17019. * @param {NodeBuilder} builder - The current node builder.
  17020. */
  17021. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  17022. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  17023. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  17024. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  17025. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  17026. const N = normalView;
  17027. const V = positionViewDirection;
  17028. const P = positionView.toVar();
  17029. const uv = LTC_Uv( { N, V, roughness } );
  17030. const t1 = ltc_1.sample( uv ).toVar();
  17031. const t2 = ltc_2.sample( uv ).toVar();
  17032. const mInv = mat3(
  17033. vec3( t1.x, 0, t1.y ),
  17034. vec3( 0, 1, 0 ),
  17035. vec3( t1.z, 0, t1.w )
  17036. ).toVar();
  17037. // LTC Fresnel Approximation by Stephen Hill
  17038. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  17039. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  17040. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  17041. reflectedLight.directDiffuse.addAssign( lightColor.mul( diffuseColor ).mul( LTC_Evaluate( { N, V, P, mInv: mat3( 1, 0, 0, 0, 1, 0, 0, 0, 1 ), p0, p1, p2, p3 } ) ) );
  17042. }
  17043. /**
  17044. * Implements the indirect lighting.
  17045. *
  17046. * @param {NodeBuilder} builder - The current node builder.
  17047. */
  17048. indirect( builder ) {
  17049. this.indirectDiffuse( builder );
  17050. this.indirectSpecular( builder );
  17051. this.ambientOcclusion( builder );
  17052. }
  17053. /**
  17054. * Implements the indirect diffuse term.
  17055. *
  17056. * @param {NodeBuilder} builder - The current node builder.
  17057. */
  17058. indirectDiffuse( builder ) {
  17059. const { irradiance, reflectedLight } = builder.context;
  17060. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  17061. }
  17062. /**
  17063. * Implements the indirect specular term.
  17064. *
  17065. * @param {NodeBuilder} builder - The current node builder.
  17066. */
  17067. indirectSpecular( builder ) {
  17068. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  17069. if ( this.sheen === true ) {
  17070. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  17071. sheen,
  17072. IBLSheenBRDF( {
  17073. normal: normalView,
  17074. viewDir: positionViewDirection,
  17075. roughness: sheenRoughness
  17076. } )
  17077. ) );
  17078. }
  17079. if ( this.clearcoat === true ) {
  17080. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17081. const clearcoatEnv = EnvironmentBRDF( {
  17082. dotNV: dotNVcc,
  17083. specularColor: clearcoatF0,
  17084. specularF90: clearcoatF90,
  17085. roughness: clearcoatRoughness
  17086. } );
  17087. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  17088. }
  17089. // Both indirect specular and indirect diffuse light accumulate here
  17090. const singleScattering = vec3().toVar( 'singleScattering' );
  17091. const multiScattering = vec3().toVar( 'multiScattering' );
  17092. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  17093. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  17094. const totalScattering = singleScattering.add( multiScattering );
  17095. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  17096. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  17097. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  17098. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  17099. }
  17100. /**
  17101. * Implements the ambient occlusion term.
  17102. *
  17103. * @param {NodeBuilder} builder - The current node builder.
  17104. */
  17105. ambientOcclusion( builder ) {
  17106. const { ambientOcclusion, reflectedLight } = builder.context;
  17107. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17108. const aoNV = dotNV.add( ambientOcclusion );
  17109. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  17110. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  17111. if ( this.clearcoat === true ) {
  17112. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  17113. }
  17114. if ( this.sheen === true ) {
  17115. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  17116. }
  17117. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  17118. reflectedLight.indirectSpecular.mulAssign( aoNode );
  17119. }
  17120. /**
  17121. * Used for final lighting accumulations depending on the requested features.
  17122. *
  17123. * @param {NodeBuilder} builder - The current node builder.
  17124. */
  17125. finish( { context } ) {
  17126. const { outgoingLight } = context;
  17127. if ( this.clearcoat === true ) {
  17128. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17129. const Fcc = F_Schlick( {
  17130. dotVH: dotNVcc,
  17131. f0: clearcoatF0,
  17132. f90: clearcoatF90
  17133. } );
  17134. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  17135. outgoingLight.assign( clearcoatLight );
  17136. }
  17137. if ( this.sheen === true ) {
  17138. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  17139. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  17140. outgoingLight.assign( sheenLight );
  17141. }
  17142. }
  17143. }
  17144. // These defines must match with PMREMGenerator
  17145. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  17146. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  17147. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  17148. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  17149. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  17150. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  17151. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  17152. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  17153. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  17154. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  17155. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  17156. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  17157. // These shader functions convert between the UV coordinates of a single face of
  17158. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  17159. // sampling a textureCube (not generally normalized ).
  17160. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  17161. const absDirection = vec3( abs( direction ) ).toVar();
  17162. const face = float( -1 ).toVar();
  17163. If( absDirection.x.greaterThan( absDirection.z ), () => {
  17164. If( absDirection.x.greaterThan( absDirection.y ), () => {
  17165. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  17166. } ).Else( () => {
  17167. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17168. } );
  17169. } ).Else( () => {
  17170. If( absDirection.z.greaterThan( absDirection.y ), () => {
  17171. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  17172. } ).Else( () => {
  17173. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17174. } );
  17175. } );
  17176. return face;
  17177. } ).setLayout( {
  17178. name: 'getFace',
  17179. type: 'float',
  17180. inputs: [
  17181. { name: 'direction', type: 'vec3' }
  17182. ]
  17183. } );
  17184. // RH coordinate system; PMREM face-indexing convention
  17185. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  17186. const uv = vec2().toVar();
  17187. If( face.equal( 0.0 ), () => {
  17188. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  17189. } ).ElseIf( face.equal( 1.0 ), () => {
  17190. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  17191. } ).ElseIf( face.equal( 2.0 ), () => {
  17192. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  17193. } ).ElseIf( face.equal( 3.0 ), () => {
  17194. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  17195. } ).ElseIf( face.equal( 4.0 ), () => {
  17196. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  17197. } ).Else( () => {
  17198. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  17199. } );
  17200. return mul( 0.5, uv.add( 1.0 ) );
  17201. } ).setLayout( {
  17202. name: 'getUV',
  17203. type: 'vec2',
  17204. inputs: [
  17205. { name: 'direction', type: 'vec3' },
  17206. { name: 'face', type: 'float' }
  17207. ]
  17208. } );
  17209. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  17210. const mip = float( 0.0 ).toVar();
  17211. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  17212. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  17213. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  17214. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  17215. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  17216. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  17217. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  17218. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  17219. } ).Else( () => {
  17220. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  17221. } );
  17222. return mip;
  17223. } ).setLayout( {
  17224. name: 'roughnessToMip',
  17225. type: 'float',
  17226. inputs: [
  17227. { name: 'roughness', type: 'float' }
  17228. ]
  17229. } );
  17230. // RH coordinate system; PMREM face-indexing convention
  17231. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  17232. const uv = uv_immutable.toVar();
  17233. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  17234. const direction = vec3( uv, 1.0 ).toVar();
  17235. If( face.equal( 0.0 ), () => {
  17236. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  17237. } ).ElseIf( face.equal( 1.0 ), () => {
  17238. direction.assign( direction.xzy );
  17239. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  17240. } ).ElseIf( face.equal( 2.0 ), () => {
  17241. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  17242. } ).ElseIf( face.equal( 3.0 ), () => {
  17243. direction.assign( direction.zyx );
  17244. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  17245. } ).ElseIf( face.equal( 4.0 ), () => {
  17246. direction.assign( direction.xzy );
  17247. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  17248. } ).ElseIf( face.equal( 5.0 ), () => {
  17249. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  17250. } );
  17251. return direction;
  17252. } ).setLayout( {
  17253. name: 'getDirection',
  17254. type: 'vec3',
  17255. inputs: [
  17256. { name: 'uv', type: 'vec2' },
  17257. { name: 'face', type: 'float' }
  17258. ]
  17259. } );
  17260. //
  17261. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17262. const roughness = float( roughness_immutable );
  17263. const sampleDir = vec3( sampleDir_immutable );
  17264. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  17265. const mipF = fract( mip );
  17266. const mipInt = floor( mip );
  17267. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17268. If( mipF.notEqual( 0.0 ), () => {
  17269. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17270. color0.assign( mix( color0, color1, mipF ) );
  17271. } );
  17272. return color0;
  17273. } );
  17274. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17275. const mipInt = float( mipInt_immutable ).toVar();
  17276. const direction = vec3( direction_immutable );
  17277. const face = float( getFace( direction ) ).toVar();
  17278. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  17279. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  17280. const faceSize = float( exp2( mipInt ) ).toVar();
  17281. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  17282. If( face.greaterThan( 2.0 ), () => {
  17283. uv.y.addAssign( faceSize );
  17284. face.subAssign( 3.0 );
  17285. } );
  17286. uv.x.addAssign( face.mul( faceSize ) );
  17287. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  17288. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  17289. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  17290. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  17291. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  17292. } );
  17293. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17294. const cosTheta = cos( theta );
  17295. // Rodrigues' axis-angle rotation
  17296. const sampleDirection = outputDirection.mul( cosTheta )
  17297. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  17298. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  17299. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  17300. } );
  17301. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17302. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  17303. If( axis.equal( vec3( 0.0 ) ), () => {
  17304. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  17305. } );
  17306. axis.assign( normalize( axis ) );
  17307. const gl_FragColor = vec3().toVar();
  17308. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17309. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  17310. If( i.greaterThanEqual( samples ), () => {
  17311. Break();
  17312. } );
  17313. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  17314. 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 } ) ) );
  17315. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17316. } );
  17317. return vec4( gl_FragColor, 1 );
  17318. } );
  17319. const LOD_MIN = 4;
  17320. // The standard deviations (radians) associated with the extra mips. These are
  17321. // chosen to approximate a Trowbridge-Reitz distribution function times the
  17322. // geometric shadowing function. These sigma values squared must match the
  17323. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  17324. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  17325. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  17326. // samples and exit early, but not recompile the shader.
  17327. const MAX_SAMPLES = 20;
  17328. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  17329. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  17330. const _clearColor$2 = /*@__PURE__*/ new Color();
  17331. let _oldTarget = null;
  17332. let _oldActiveCubeFace = 0;
  17333. let _oldActiveMipmapLevel = 0;
  17334. // Golden Ratio
  17335. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  17336. const INV_PHI = 1 / PHI;
  17337. // Vertices of a dodecahedron (except the opposites, which represent the
  17338. // same axis), used as axis directions evenly spread on a sphere.
  17339. const _axisDirections = [
  17340. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  17341. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  17342. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  17343. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  17344. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  17345. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  17346. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  17347. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  17348. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  17349. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  17350. ];
  17351. const _origin = /*@__PURE__*/ new Vector3();
  17352. // maps blur materials to their uniforms dictionary
  17353. const _uniformsMap = new WeakMap();
  17354. // WebGPU Face indices
  17355. const _faceLib = [
  17356. 3, 1, 5,
  17357. 0, 4, 2
  17358. ];
  17359. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  17360. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  17361. /**
  17362. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  17363. * (PMREM) from a cubeMap environment texture. This allows different levels of
  17364. * blur to be quickly accessed based on material roughness. It is packed into a
  17365. * special CubeUV format that allows us to perform custom interpolation so that
  17366. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  17367. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  17368. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  17369. * higher roughness levels. In this way we maintain resolution to smoothly
  17370. * interpolate diffuse lighting while limiting sampling computation.
  17371. *
  17372. * Paper: Fast, Accurate Image-Based Lighting:
  17373. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  17374. */
  17375. class PMREMGenerator {
  17376. /**
  17377. * Constructs a new PMREM generator.
  17378. *
  17379. * @param {Renderer} renderer - The renderer.
  17380. */
  17381. constructor( renderer ) {
  17382. this._renderer = renderer;
  17383. this._pingPongRenderTarget = null;
  17384. this._lodMax = 0;
  17385. this._cubeSize = 0;
  17386. this._lodPlanes = [];
  17387. this._sizeLods = [];
  17388. this._sigmas = [];
  17389. this._lodMeshes = [];
  17390. this._blurMaterial = null;
  17391. this._cubemapMaterial = null;
  17392. this._equirectMaterial = null;
  17393. this._backgroundBox = null;
  17394. }
  17395. get _hasInitialized() {
  17396. return this._renderer.hasInitialized();
  17397. }
  17398. /**
  17399. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17400. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17401. * in radians to be applied to the scene before PMREM generation. Optional near
  17402. * and far planes ensure the scene is rendered in its entirety.
  17403. *
  17404. * @param {Scene} scene - The scene to be captured.
  17405. * @param {number} [sigma=0] - The blur radius in radians.
  17406. * @param {number} [near=0.1] - The near plane distance.
  17407. * @param {number} [far=100] - The far plane distance.
  17408. * @param {Object} [options={}] - The configuration options.
  17409. * @param {number} [options.size=256] - The texture size of the PMREM.
  17410. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  17411. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17412. * @return {RenderTarget} The resulting PMREM.
  17413. * @see {@link PMREMGenerator#fromScene}
  17414. */
  17415. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17416. const {
  17417. size = 256,
  17418. position = _origin,
  17419. renderTarget = null,
  17420. } = options;
  17421. this._setSize( size );
  17422. if ( this._hasInitialized === false ) {
  17423. warn( 'PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.' );
  17424. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17425. options.renderTarget = cubeUVRenderTarget;
  17426. this.fromSceneAsync( scene, sigma, near, far, options );
  17427. return cubeUVRenderTarget;
  17428. }
  17429. _oldTarget = this._renderer.getRenderTarget();
  17430. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17431. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17432. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17433. cubeUVRenderTarget.depthBuffer = true;
  17434. this._init( cubeUVRenderTarget );
  17435. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  17436. if ( sigma > 0 ) {
  17437. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  17438. }
  17439. this._applyPMREM( cubeUVRenderTarget );
  17440. this._cleanup( cubeUVRenderTarget );
  17441. return cubeUVRenderTarget;
  17442. }
  17443. /**
  17444. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17445. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17446. * in radians to be applied to the scene before PMREM generation. Optional near
  17447. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  17448. * is placed at the origin).
  17449. *
  17450. * @deprecated
  17451. * @param {Scene} scene - The scene to be captured.
  17452. * @param {number} [sigma=0] - The blur radius in radians.
  17453. * @param {number} [near=0.1] - The near plane distance.
  17454. * @param {number} [far=100] - The far plane distance.
  17455. * @param {Object} [options={}] - The configuration options.
  17456. * @param {number} [options.size=256] - The texture size of the PMREM.
  17457. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  17458. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17459. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  17460. * @see {@link PMREMGenerator#fromScene}
  17461. */
  17462. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17463. warnOnce( 'PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17464. await this._renderer.init();
  17465. return this.fromScene( scene, sigma, near, far, options );
  17466. }
  17467. /**
  17468. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17469. * or HDR. The ideal input image size is 1k (1024 x 512),
  17470. * as this matches best with the 256 x 256 cubemap output.
  17471. *
  17472. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17473. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17474. * @return {RenderTarget} The resulting PMREM.
  17475. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  17476. */
  17477. fromEquirectangular( equirectangular, renderTarget = null ) {
  17478. if ( this._hasInitialized === false ) {
  17479. warn( 'PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.' );
  17480. this._setSizeFromTexture( equirectangular );
  17481. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17482. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  17483. return cubeUVRenderTarget;
  17484. }
  17485. return this._fromTexture( equirectangular, renderTarget );
  17486. }
  17487. /**
  17488. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17489. * or HDR. The ideal input image size is 1k (1024 x 512),
  17490. * as this matches best with the 256 x 256 cubemap output.
  17491. *
  17492. * @deprecated
  17493. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17494. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17495. * @return {Promise<RenderTarget>} The resulting PMREM.
  17496. * @see {@link PMREMGenerator#fromEquirectangular}
  17497. */
  17498. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  17499. warnOnce( 'PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17500. await this._renderer.init();
  17501. return this._fromTexture( equirectangular, renderTarget );
  17502. }
  17503. /**
  17504. * Generates a PMREM from an cubemap texture, which can be either LDR
  17505. * or HDR. The ideal input cube size is 256 x 256,
  17506. * as this matches best with the 256 x 256 cubemap output.
  17507. *
  17508. * @param {Texture} cubemap - The cubemap texture to be converted.
  17509. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17510. * @return {RenderTarget} The resulting PMREM.
  17511. * @see {@link PMREMGenerator#fromCubemapAsync}
  17512. */
  17513. fromCubemap( cubemap, renderTarget = null ) {
  17514. if ( this._hasInitialized === false ) {
  17515. warn( 'PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  17516. this._setSizeFromTexture( cubemap );
  17517. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17518. this.fromCubemapAsync( cubemap, renderTarget );
  17519. return cubeUVRenderTarget;
  17520. }
  17521. return this._fromTexture( cubemap, renderTarget );
  17522. }
  17523. /**
  17524. * Generates a PMREM from an cubemap texture, which can be either LDR
  17525. * or HDR. The ideal input cube size is 256 x 256,
  17526. * with the 256 x 256 cubemap output.
  17527. *
  17528. * @deprecated
  17529. * @param {Texture} cubemap - The cubemap texture to be converted.
  17530. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17531. * @return {Promise<RenderTarget>} The resulting PMREM.
  17532. * @see {@link PMREMGenerator#fromCubemap}
  17533. */
  17534. async fromCubemapAsync( cubemap, renderTarget = null ) {
  17535. warnOnce( 'PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17536. await this._renderer.init();
  17537. return this._fromTexture( cubemap, renderTarget );
  17538. }
  17539. /**
  17540. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  17541. * your texture's network fetch for increased concurrency.
  17542. *
  17543. * @returns {Promise}
  17544. */
  17545. async compileCubemapShader() {
  17546. if ( this._cubemapMaterial === null ) {
  17547. this._cubemapMaterial = _getCubemapMaterial();
  17548. await this._compileMaterial( this._cubemapMaterial );
  17549. }
  17550. }
  17551. /**
  17552. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  17553. * your texture's network fetch for increased concurrency.
  17554. *
  17555. * @returns {Promise}
  17556. */
  17557. async compileEquirectangularShader() {
  17558. if ( this._equirectMaterial === null ) {
  17559. this._equirectMaterial = _getEquirectMaterial();
  17560. await this._compileMaterial( this._equirectMaterial );
  17561. }
  17562. }
  17563. /**
  17564. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  17565. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  17566. * one of them will cause any others to also become unusable.
  17567. */
  17568. dispose() {
  17569. this._dispose();
  17570. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  17571. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  17572. if ( this._backgroundBox !== null ) {
  17573. this._backgroundBox.geometry.dispose();
  17574. this._backgroundBox.material.dispose();
  17575. }
  17576. }
  17577. // private interface
  17578. _setSizeFromTexture( texture ) {
  17579. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  17580. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  17581. } else { // Equirectangular
  17582. this._setSize( texture.image.width / 4 );
  17583. }
  17584. }
  17585. _setSize( cubeSize ) {
  17586. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  17587. this._cubeSize = Math.pow( 2, this._lodMax );
  17588. }
  17589. _dispose() {
  17590. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  17591. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  17592. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  17593. this._lodPlanes[ i ].dispose();
  17594. }
  17595. }
  17596. _cleanup( outputTarget ) {
  17597. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  17598. outputTarget.scissorTest = false;
  17599. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  17600. }
  17601. _fromTexture( texture, renderTarget ) {
  17602. this._setSizeFromTexture( texture );
  17603. _oldTarget = this._renderer.getRenderTarget();
  17604. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17605. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17606. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17607. this._init( cubeUVRenderTarget );
  17608. this._textureToCubeUV( texture, cubeUVRenderTarget );
  17609. this._applyPMREM( cubeUVRenderTarget );
  17610. this._cleanup( cubeUVRenderTarget );
  17611. return cubeUVRenderTarget;
  17612. }
  17613. _allocateTarget() {
  17614. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  17615. const height = 4 * this._cubeSize;
  17616. const cubeUVRenderTarget = _createRenderTarget( width, height );
  17617. return cubeUVRenderTarget;
  17618. }
  17619. _init( renderTarget ) {
  17620. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  17621. if ( this._pingPongRenderTarget !== null ) {
  17622. this._dispose();
  17623. }
  17624. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  17625. const { _lodMax } = this;
  17626. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  17627. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  17628. }
  17629. }
  17630. async _compileMaterial( material ) {
  17631. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  17632. await this._renderer.compile( tmpMesh, _flatCamera );
  17633. }
  17634. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  17635. const cubeCamera = _cubeCamera;
  17636. cubeCamera.near = near;
  17637. cubeCamera.far = far;
  17638. // px, py, pz, nx, ny, nz
  17639. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  17640. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  17641. const renderer = this._renderer;
  17642. const originalAutoClear = renderer.autoClear;
  17643. renderer.getClearColor( _clearColor$2 );
  17644. renderer.autoClear = false;
  17645. let backgroundBox = this._backgroundBox;
  17646. if ( backgroundBox === null ) {
  17647. const backgroundMaterial = new MeshBasicMaterial( {
  17648. name: 'PMREM.Background',
  17649. side: BackSide,
  17650. depthWrite: false,
  17651. depthTest: false
  17652. } );
  17653. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  17654. }
  17655. let useSolidColor = false;
  17656. const background = scene.background;
  17657. if ( background ) {
  17658. if ( background.isColor ) {
  17659. backgroundBox.material.color.copy( background );
  17660. scene.background = null;
  17661. useSolidColor = true;
  17662. }
  17663. } else {
  17664. backgroundBox.material.color.copy( _clearColor$2 );
  17665. useSolidColor = true;
  17666. }
  17667. renderer.setRenderTarget( cubeUVRenderTarget );
  17668. renderer.clear();
  17669. if ( useSolidColor ) {
  17670. renderer.render( backgroundBox, cubeCamera );
  17671. }
  17672. for ( let i = 0; i < 6; i ++ ) {
  17673. const col = i % 3;
  17674. if ( col === 0 ) {
  17675. cubeCamera.up.set( 0, upSign[ i ], 0 );
  17676. cubeCamera.position.set( position.x, position.y, position.z );
  17677. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  17678. } else if ( col === 1 ) {
  17679. cubeCamera.up.set( 0, 0, upSign[ i ] );
  17680. cubeCamera.position.set( position.x, position.y, position.z );
  17681. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  17682. } else {
  17683. cubeCamera.up.set( 0, upSign[ i ], 0 );
  17684. cubeCamera.position.set( position.x, position.y, position.z );
  17685. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  17686. }
  17687. const size = this._cubeSize;
  17688. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  17689. renderer.render( scene, cubeCamera );
  17690. }
  17691. renderer.autoClear = originalAutoClear;
  17692. scene.background = background;
  17693. }
  17694. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  17695. const renderer = this._renderer;
  17696. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  17697. if ( isCubeTexture ) {
  17698. if ( this._cubemapMaterial === null ) {
  17699. this._cubemapMaterial = _getCubemapMaterial( texture );
  17700. }
  17701. } else {
  17702. if ( this._equirectMaterial === null ) {
  17703. this._equirectMaterial = _getEquirectMaterial( texture );
  17704. }
  17705. }
  17706. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  17707. material.fragmentNode.value = texture;
  17708. const mesh = this._lodMeshes[ 0 ];
  17709. mesh.material = material;
  17710. const size = this._cubeSize;
  17711. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  17712. renderer.setRenderTarget( cubeUVRenderTarget );
  17713. renderer.render( mesh, _flatCamera );
  17714. }
  17715. _applyPMREM( cubeUVRenderTarget ) {
  17716. const renderer = this._renderer;
  17717. const autoClear = renderer.autoClear;
  17718. renderer.autoClear = false;
  17719. const n = this._lodPlanes.length;
  17720. for ( let i = 1; i < n; i ++ ) {
  17721. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  17722. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  17723. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  17724. }
  17725. renderer.autoClear = autoClear;
  17726. }
  17727. /**
  17728. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  17729. * vertically and horizontally, but this breaks down on a cube. Here we apply
  17730. * the blur latitudinally (around the poles), and then longitudinally (towards
  17731. * the poles) to approximate the orthogonally-separable blur. It is least
  17732. * accurate at the poles, but still does a decent job.
  17733. *
  17734. * @private
  17735. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  17736. * @param {number} lodIn - The input level-of-detail.
  17737. * @param {number} lodOut - The output level-of-detail.
  17738. * @param {number} sigma - The blur radius in radians.
  17739. * @param {Vector3} [poleAxis] - The pole axis.
  17740. */
  17741. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  17742. const pingPongRenderTarget = this._pingPongRenderTarget;
  17743. this._halfBlur(
  17744. cubeUVRenderTarget,
  17745. pingPongRenderTarget,
  17746. lodIn,
  17747. lodOut,
  17748. sigma,
  17749. 'latitudinal',
  17750. poleAxis );
  17751. this._halfBlur(
  17752. pingPongRenderTarget,
  17753. cubeUVRenderTarget,
  17754. lodOut,
  17755. lodOut,
  17756. sigma,
  17757. 'longitudinal',
  17758. poleAxis );
  17759. }
  17760. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  17761. const renderer = this._renderer;
  17762. const blurMaterial = this._blurMaterial;
  17763. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  17764. error( 'blur direction must be either latitudinal or longitudinal!' );
  17765. }
  17766. // Number of standard deviations at which to cut off the discrete approximation.
  17767. const STANDARD_DEVIATIONS = 3;
  17768. const blurMesh = this._lodMeshes[ lodOut ];
  17769. blurMesh.material = blurMaterial;
  17770. const blurUniforms = _uniformsMap.get( blurMaterial );
  17771. const pixels = this._sizeLods[ lodIn ] - 1;
  17772. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  17773. const sigmaPixels = sigmaRadians / radiansPerPixel;
  17774. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  17775. if ( samples > MAX_SAMPLES ) {
  17776. warn( `sigmaRadians, ${
  17777. sigmaRadians}, is too large and will clip, as it requested ${
  17778. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  17779. }
  17780. const weights = [];
  17781. let sum = 0;
  17782. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  17783. const x = i / sigmaPixels;
  17784. const weight = Math.exp( - x * x / 2 );
  17785. weights.push( weight );
  17786. if ( i === 0 ) {
  17787. sum += weight;
  17788. } else if ( i < samples ) {
  17789. sum += 2 * weight;
  17790. }
  17791. }
  17792. for ( let i = 0; i < weights.length; i ++ ) {
  17793. weights[ i ] = weights[ i ] / sum;
  17794. }
  17795. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  17796. blurUniforms.envMap.value = targetIn.texture;
  17797. blurUniforms.samples.value = samples;
  17798. blurUniforms.weights.array = weights;
  17799. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  17800. if ( poleAxis ) {
  17801. blurUniforms.poleAxis.value = poleAxis;
  17802. }
  17803. const { _lodMax } = this;
  17804. blurUniforms.dTheta.value = radiansPerPixel;
  17805. blurUniforms.mipInt.value = _lodMax - lodIn;
  17806. const outputSize = this._sizeLods[ lodOut ];
  17807. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  17808. const y = 4 * ( this._cubeSize - outputSize );
  17809. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  17810. renderer.setRenderTarget( targetOut );
  17811. renderer.render( blurMesh, _flatCamera );
  17812. }
  17813. }
  17814. function _createPlanes( lodMax ) {
  17815. const lodPlanes = [];
  17816. const sizeLods = [];
  17817. const sigmas = [];
  17818. const lodMeshes = [];
  17819. let lod = lodMax;
  17820. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  17821. for ( let i = 0; i < totalLods; i ++ ) {
  17822. const sizeLod = Math.pow( 2, lod );
  17823. sizeLods.push( sizeLod );
  17824. let sigma = 1.0 / sizeLod;
  17825. if ( i > lodMax - LOD_MIN ) {
  17826. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  17827. } else if ( i === 0 ) {
  17828. sigma = 0;
  17829. }
  17830. sigmas.push( sigma );
  17831. const texelSize = 1.0 / ( sizeLod - 2 );
  17832. const min = - texelSize;
  17833. const max = 1 + texelSize;
  17834. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  17835. const cubeFaces = 6;
  17836. const vertices = 6;
  17837. const positionSize = 3;
  17838. const uvSize = 2;
  17839. const faceIndexSize = 1;
  17840. const position = new Float32Array( positionSize * vertices * cubeFaces );
  17841. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  17842. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  17843. for ( let face = 0; face < cubeFaces; face ++ ) {
  17844. const x = ( face % 3 ) * 2 / 3 - 1;
  17845. const y = face > 2 ? 0 : -1;
  17846. const coordinates = [
  17847. x, y, 0,
  17848. x + 2 / 3, y, 0,
  17849. x + 2 / 3, y + 1, 0,
  17850. x, y, 0,
  17851. x + 2 / 3, y + 1, 0,
  17852. x, y + 1, 0
  17853. ];
  17854. const faceIdx = _faceLib[ face ];
  17855. position.set( coordinates, positionSize * vertices * faceIdx );
  17856. uv.set( uv1, uvSize * vertices * faceIdx );
  17857. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  17858. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  17859. }
  17860. const planes = new BufferGeometry();
  17861. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  17862. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  17863. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  17864. lodPlanes.push( planes );
  17865. lodMeshes.push( new Mesh( planes, null ) );
  17866. if ( lod > LOD_MIN ) {
  17867. lod --;
  17868. }
  17869. }
  17870. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  17871. }
  17872. function _createRenderTarget( width, height ) {
  17873. const params = {
  17874. magFilter: LinearFilter,
  17875. minFilter: LinearFilter,
  17876. generateMipmaps: false,
  17877. type: HalfFloatType,
  17878. format: RGBAFormat,
  17879. colorSpace: LinearSRGBColorSpace,
  17880. //depthBuffer: false
  17881. };
  17882. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  17883. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  17884. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  17885. cubeUVRenderTarget.texture.isPMREMTexture = true;
  17886. cubeUVRenderTarget.scissorTest = true;
  17887. return cubeUVRenderTarget;
  17888. }
  17889. function _setViewport( target, x, y, width, height ) {
  17890. target.viewport.set( x, y, width, height );
  17891. target.scissor.set( x, y, width, height );
  17892. }
  17893. function _getMaterial( type ) {
  17894. const material = new NodeMaterial();
  17895. material.depthTest = false;
  17896. material.depthWrite = false;
  17897. material.blending = NoBlending;
  17898. material.name = `PMREM_${ type }`;
  17899. return material;
  17900. }
  17901. function _getBlurShader( lodMax, width, height ) {
  17902. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  17903. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  17904. const dTheta = uniform( 0 );
  17905. const n = float( MAX_SAMPLES );
  17906. const latitudinal = uniform( 0 ); // false, bool
  17907. const samples = uniform( 1 ); // int
  17908. const envMap = texture( null );
  17909. const mipInt = uniform( 0 ); // int
  17910. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  17911. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  17912. const CUBEUV_MAX_MIP = float( lodMax );
  17913. const materialUniforms = {
  17914. n,
  17915. latitudinal,
  17916. weights,
  17917. poleAxis,
  17918. outputDirection: _outputDirection,
  17919. dTheta,
  17920. samples,
  17921. envMap,
  17922. mipInt,
  17923. CUBEUV_TEXEL_WIDTH,
  17924. CUBEUV_TEXEL_HEIGHT,
  17925. CUBEUV_MAX_MIP
  17926. };
  17927. const material = _getMaterial( 'blur' );
  17928. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  17929. _uniformsMap.set( material, materialUniforms );
  17930. return material;
  17931. }
  17932. function _getCubemapMaterial( envTexture ) {
  17933. const material = _getMaterial( 'cubemap' );
  17934. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  17935. return material;
  17936. }
  17937. function _getEquirectMaterial( envTexture ) {
  17938. const material = _getMaterial( 'equirect' );
  17939. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  17940. return material;
  17941. }
  17942. const _cache = new WeakMap();
  17943. /**
  17944. * Generates the cubeUV size based on the given image height.
  17945. *
  17946. * @private
  17947. * @param {number} imageHeight - The image height.
  17948. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  17949. */
  17950. function _generateCubeUVSize( imageHeight ) {
  17951. const maxMip = Math.log2( imageHeight ) - 2;
  17952. const texelHeight = 1.0 / imageHeight;
  17953. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  17954. return { texelWidth, texelHeight, maxMip };
  17955. }
  17956. /**
  17957. * Generates a PMREM from the given texture.
  17958. *
  17959. * @private
  17960. * @param {Texture} texture - The texture to create the PMREM for.
  17961. * @param {Renderer} renderer - The renderer.
  17962. * @param {PMREMGenerator} generator - The PMREM generator.
  17963. * @return {?Texture} The PMREM.
  17964. */
  17965. function _getPMREMFromTexture( texture, renderer, generator ) {
  17966. const cache = _getCache( renderer );
  17967. let cacheTexture = cache.get( texture );
  17968. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  17969. if ( pmremVersion !== texture.pmremVersion ) {
  17970. const image = texture.image;
  17971. if ( texture.isCubeTexture ) {
  17972. if ( isCubeMapReady( image ) ) {
  17973. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  17974. } else {
  17975. return null;
  17976. }
  17977. } else {
  17978. if ( isEquirectangularMapReady( image ) ) {
  17979. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  17980. } else {
  17981. return null;
  17982. }
  17983. }
  17984. cacheTexture.pmremVersion = texture.pmremVersion;
  17985. cache.set( texture, cacheTexture );
  17986. }
  17987. return cacheTexture.texture;
  17988. }
  17989. /**
  17990. * Returns a cache that stores generated PMREMs for the respective textures.
  17991. * A cache must be maintained per renderer since PMREMs are render target textures
  17992. * which can't be shared across render contexts.
  17993. *
  17994. * @private
  17995. * @param {Renderer} renderer - The renderer.
  17996. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  17997. */
  17998. function _getCache( renderer ) {
  17999. let rendererCache = _cache.get( renderer );
  18000. if ( rendererCache === undefined ) {
  18001. rendererCache = new WeakMap();
  18002. _cache.set( renderer, rendererCache );
  18003. }
  18004. return rendererCache;
  18005. }
  18006. /**
  18007. * This node represents a PMREM which is a special type of preprocessed
  18008. * environment map intended for PBR materials.
  18009. *
  18010. * ```js
  18011. * const material = new MeshStandardNodeMaterial();
  18012. * material.envNode = pmremTexture( envMap );
  18013. * ```
  18014. *
  18015. * @augments TempNode
  18016. */
  18017. class PMREMNode extends TempNode {
  18018. static get type() {
  18019. return 'PMREMNode';
  18020. }
  18021. /**
  18022. * Constructs a new function overloading node.
  18023. *
  18024. * @param {Texture} value - The input texture.
  18025. * @param {Node<vec2>} [uvNode=null] - The uv node.
  18026. * @param {Node<float>} [levelNode=null] - The level node.
  18027. */
  18028. constructor( value, uvNode = null, levelNode = null ) {
  18029. super( 'vec3' );
  18030. /**
  18031. * Reference to the input texture.
  18032. *
  18033. * @private
  18034. * @type {Texture}
  18035. */
  18036. this._value = value;
  18037. /**
  18038. * Reference to the generated PMREM.
  18039. *
  18040. * @private
  18041. * @type {Texture | null}
  18042. * @default null
  18043. */
  18044. this._pmrem = null;
  18045. /**
  18046. * The uv node.
  18047. *
  18048. * @type {Node<vec2>}
  18049. */
  18050. this.uvNode = uvNode;
  18051. /**
  18052. * The level node.
  18053. *
  18054. * @type {Node<float>}
  18055. */
  18056. this.levelNode = levelNode;
  18057. /**
  18058. * Reference to a PMREM generator.
  18059. *
  18060. * @private
  18061. * @type {?PMREMGenerator}
  18062. * @default null
  18063. */
  18064. this._generator = null;
  18065. const defaultTexture = new Texture();
  18066. defaultTexture.isRenderTargetTexture = true;
  18067. /**
  18068. * The texture node holding the generated PMREM.
  18069. *
  18070. * @private
  18071. * @type {TextureNode}
  18072. */
  18073. this._texture = texture( defaultTexture );
  18074. /**
  18075. * A uniform representing the PMREM's width.
  18076. *
  18077. * @private
  18078. * @type {UniformNode<float>}
  18079. */
  18080. this._width = uniform( 0 );
  18081. /**
  18082. * A uniform representing the PMREM's height.
  18083. *
  18084. * @private
  18085. * @type {UniformNode<float>}
  18086. */
  18087. this._height = uniform( 0 );
  18088. /**
  18089. * A uniform representing the PMREM's max Mip.
  18090. *
  18091. * @private
  18092. * @type {UniformNode<float>}
  18093. */
  18094. this._maxMip = uniform( 0 );
  18095. /**
  18096. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  18097. *
  18098. * @type {string}
  18099. * @default 'render'
  18100. */
  18101. this.updateBeforeType = NodeUpdateType.RENDER;
  18102. }
  18103. set value( value ) {
  18104. this._value = value;
  18105. this._pmrem = null;
  18106. }
  18107. /**
  18108. * The node's texture value.
  18109. *
  18110. * @type {Texture}
  18111. */
  18112. get value() {
  18113. return this._value;
  18114. }
  18115. /**
  18116. * Uses the given PMREM texture to update internal values.
  18117. *
  18118. * @param {Texture} texture - The PMREM texture.
  18119. */
  18120. updateFromTexture( texture ) {
  18121. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  18122. this._texture.value = texture;
  18123. this._width.value = cubeUVSize.texelWidth;
  18124. this._height.value = cubeUVSize.texelHeight;
  18125. this._maxMip.value = cubeUVSize.maxMip;
  18126. }
  18127. updateBefore( frame ) {
  18128. let pmrem = this._pmrem;
  18129. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  18130. const texture = this._value;
  18131. if ( pmremVersion !== texture.pmremVersion ) {
  18132. if ( texture.isPMREMTexture === true ) {
  18133. pmrem = texture;
  18134. } else {
  18135. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  18136. }
  18137. if ( pmrem !== null ) {
  18138. this._pmrem = pmrem;
  18139. this.updateFromTexture( pmrem );
  18140. }
  18141. }
  18142. }
  18143. setup( builder ) {
  18144. if ( this._generator === null ) {
  18145. this._generator = new PMREMGenerator( builder.renderer );
  18146. }
  18147. this.updateBefore( builder );
  18148. //
  18149. let uvNode = this.uvNode;
  18150. if ( uvNode === null && builder.context.getUV ) {
  18151. uvNode = builder.context.getUV( this );
  18152. }
  18153. //
  18154. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  18155. //
  18156. let levelNode = this.levelNode;
  18157. if ( levelNode === null && builder.context.getTextureLevel ) {
  18158. levelNode = builder.context.getTextureLevel( this );
  18159. }
  18160. //
  18161. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  18162. }
  18163. dispose() {
  18164. super.dispose();
  18165. if ( this._generator !== null ) this._generator.dispose();
  18166. }
  18167. }
  18168. /**
  18169. * Returns `true` if the given cube map image has been fully loaded.
  18170. *
  18171. * @private
  18172. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  18173. * @return {boolean} Whether the given cube map is ready or not.
  18174. */
  18175. function isCubeMapReady( image ) {
  18176. if ( image === null || image === undefined ) return false;
  18177. let count = 0;
  18178. const length = 6;
  18179. for ( let i = 0; i < length; i ++ ) {
  18180. if ( image[ i ] !== undefined ) count ++;
  18181. }
  18182. return count === length;
  18183. }
  18184. /**
  18185. * Returns `true` if the given equirectangular image has been fully loaded.
  18186. *
  18187. * @private
  18188. * @param {(Image|Object)} image - The equirectangular image.
  18189. * @return {boolean} Whether the given cube map is ready or not.
  18190. */
  18191. function isEquirectangularMapReady( image ) {
  18192. if ( image === null || image === undefined ) return false;
  18193. return image.height > 0;
  18194. }
  18195. /**
  18196. * TSL function for creating a PMREM node.
  18197. *
  18198. * @tsl
  18199. * @function
  18200. * @param {Texture} value - The input texture.
  18201. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  18202. * @param {?Node<float>} [levelNode=null] - The level node.
  18203. * @returns {PMREMNode}
  18204. */
  18205. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  18206. const _envNodeCache = new WeakMap();
  18207. /**
  18208. * Represents a physical model for Image-based lighting (IBL). The environment
  18209. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  18210. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  18211. *
  18212. * @augments LightingNode
  18213. */
  18214. class EnvironmentNode extends LightingNode {
  18215. static get type() {
  18216. return 'EnvironmentNode';
  18217. }
  18218. /**
  18219. * Constructs a new environment node.
  18220. *
  18221. * @param {Node} [envNode=null] - A node representing the environment.
  18222. */
  18223. constructor( envNode = null ) {
  18224. super();
  18225. /**
  18226. * A node representing the environment.
  18227. *
  18228. * @type {?Node}
  18229. * @default null
  18230. */
  18231. this.envNode = envNode;
  18232. }
  18233. setup( builder ) {
  18234. const { material } = builder;
  18235. let envNode = this.envNode;
  18236. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  18237. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  18238. let cacheEnvNode = _envNodeCache.get( value );
  18239. if ( cacheEnvNode === undefined ) {
  18240. cacheEnvNode = pmremTexture( value );
  18241. _envNodeCache.set( value, cacheEnvNode );
  18242. }
  18243. envNode = cacheEnvNode;
  18244. }
  18245. //
  18246. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  18247. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  18248. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  18249. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  18250. const isolateRadiance = isolate( radiance );
  18251. const isolateIrradiance = isolate( irradiance );
  18252. //
  18253. builder.context.radiance.addAssign( isolateRadiance );
  18254. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  18255. //
  18256. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  18257. if ( clearcoatRadiance ) {
  18258. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  18259. const isolateClearcoatRadiance = isolate( clearcoatRadianceContext );
  18260. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  18261. }
  18262. }
  18263. }
  18264. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  18265. let reflectVec = null;
  18266. return {
  18267. getUV: () => {
  18268. if ( reflectVec === null ) {
  18269. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  18270. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  18271. reflectVec = pow4( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  18272. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  18273. }
  18274. return reflectVec;
  18275. },
  18276. getTextureLevel: () => {
  18277. return roughnessNode;
  18278. }
  18279. };
  18280. };
  18281. const createIrradianceContext = ( normalWorldNode ) => {
  18282. return {
  18283. getUV: () => {
  18284. return normalWorldNode;
  18285. },
  18286. getTextureLevel: () => {
  18287. return float( 1.0 );
  18288. }
  18289. };
  18290. };
  18291. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  18292. /**
  18293. * Node material version of {@link MeshStandardMaterial}.
  18294. *
  18295. * @augments NodeMaterial
  18296. */
  18297. class MeshStandardNodeMaterial extends NodeMaterial {
  18298. static get type() {
  18299. return 'MeshStandardNodeMaterial';
  18300. }
  18301. /**
  18302. * Constructs a new mesh standard node material.
  18303. *
  18304. * @param {Object} [parameters] - The configuration parameter.
  18305. */
  18306. constructor( parameters ) {
  18307. super();
  18308. /**
  18309. * This flag can be used for type testing.
  18310. *
  18311. * @type {boolean}
  18312. * @readonly
  18313. * @default true
  18314. */
  18315. this.isMeshStandardNodeMaterial = true;
  18316. /**
  18317. * Set to `true` because standard materials react on lights.
  18318. *
  18319. * @type {boolean}
  18320. * @default true
  18321. */
  18322. this.lights = true;
  18323. /**
  18324. * The emissive color of standard materials is by default inferred from the `emissive`,
  18325. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  18326. * overwrite the default and define the emissive color with a node instead.
  18327. *
  18328. * If you don't want to overwrite the emissive color but modify the existing
  18329. * value instead, use {@link materialEmissive}.
  18330. *
  18331. * @type {?Node<vec3>}
  18332. * @default null
  18333. */
  18334. this.emissiveNode = null;
  18335. /**
  18336. * The metalness of standard materials is by default inferred from the `metalness`,
  18337. * and `metalnessMap` properties. This node property allows to
  18338. * overwrite the default and define the metalness with a node instead.
  18339. *
  18340. * If you don't want to overwrite the metalness but modify the existing
  18341. * value instead, use {@link materialMetalness}.
  18342. *
  18343. * @type {?Node<float>}
  18344. * @default null
  18345. */
  18346. this.metalnessNode = null;
  18347. /**
  18348. * The roughness of standard materials is by default inferred from the `roughness`,
  18349. * and `roughnessMap` properties. This node property allows to
  18350. * overwrite the default and define the roughness with a node instead.
  18351. *
  18352. * If you don't want to overwrite the roughness but modify the existing
  18353. * value instead, use {@link materialRoughness}.
  18354. *
  18355. * @type {?Node<float>}
  18356. * @default null
  18357. */
  18358. this.roughnessNode = null;
  18359. this.setDefaultValues( _defaultValues$6 );
  18360. this.setValues( parameters );
  18361. }
  18362. /**
  18363. * Overwritten since this type of material uses {@link EnvironmentNode}
  18364. * to implement the PBR (PMREM based) environment mapping. Besides, the
  18365. * method honors `Scene.environment`.
  18366. *
  18367. * @param {NodeBuilder} builder - The current node builder.
  18368. * @return {?EnvironmentNode<vec3>} The environment node.
  18369. */
  18370. setupEnvironment( builder ) {
  18371. let envNode = super.setupEnvironment( builder );
  18372. if ( envNode === null && builder.environmentNode ) {
  18373. envNode = builder.environmentNode;
  18374. }
  18375. return envNode ? new EnvironmentNode( envNode ) : null;
  18376. }
  18377. /**
  18378. * Setups the lighting model.
  18379. *
  18380. * @return {PhysicalLightingModel} The lighting model.
  18381. */
  18382. setupLightingModel( /*builder*/ ) {
  18383. return new PhysicalLightingModel();
  18384. }
  18385. /**
  18386. * Setups the specular related node variables.
  18387. */
  18388. setupSpecular() {
  18389. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  18390. specularColor.assign( specularColorNode );
  18391. specularF90.assign( 1.0 );
  18392. }
  18393. /**
  18394. * Setups the standard specific node variables.
  18395. *
  18396. * @param {NodeBuilder} builder - The current node builder.
  18397. */
  18398. setupVariants() {
  18399. // METALNESS
  18400. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  18401. metalness.assign( metalnessNode );
  18402. // ROUGHNESS
  18403. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  18404. roughnessNode = getRoughness( { roughness: roughnessNode } );
  18405. roughness.assign( roughnessNode );
  18406. // SPECULAR COLOR
  18407. this.setupSpecular();
  18408. // DIFFUSE COLOR
  18409. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  18410. }
  18411. copy( source ) {
  18412. this.emissiveNode = source.emissiveNode;
  18413. this.metalnessNode = source.metalnessNode;
  18414. this.roughnessNode = source.roughnessNode;
  18415. return super.copy( source );
  18416. }
  18417. }
  18418. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  18419. /**
  18420. * Node material version of {@link MeshPhysicalMaterial}.
  18421. *
  18422. * @augments MeshStandardNodeMaterial
  18423. */
  18424. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  18425. static get type() {
  18426. return 'MeshPhysicalNodeMaterial';
  18427. }
  18428. /**
  18429. * Constructs a new mesh physical node material.
  18430. *
  18431. * @param {Object} [parameters] - The configuration parameter.
  18432. */
  18433. constructor( parameters ) {
  18434. super();
  18435. /**
  18436. * This flag can be used for type testing.
  18437. *
  18438. * @type {boolean}
  18439. * @readonly
  18440. * @default true
  18441. */
  18442. this.isMeshPhysicalNodeMaterial = true;
  18443. /**
  18444. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  18445. * and `clearcoatMap` properties. This node property allows to overwrite the default
  18446. * and define the clearcoat with a node instead.
  18447. *
  18448. * If you don't want to overwrite the clearcoat but modify the existing
  18449. * value instead, use {@link materialClearcoat}.
  18450. *
  18451. * @type {?Node<float>}
  18452. * @default null
  18453. */
  18454. this.clearcoatNode = null;
  18455. /**
  18456. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  18457. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  18458. * and define the clearcoat roughness with a node instead.
  18459. *
  18460. * If you don't want to overwrite the clearcoat roughness but modify the existing
  18461. * value instead, use {@link materialClearcoatRoughness}.
  18462. *
  18463. * @type {?Node<float>}
  18464. * @default null
  18465. */
  18466. this.clearcoatRoughnessNode = null;
  18467. /**
  18468. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  18469. * property. This node property allows to overwrite the default
  18470. * and define the clearcoat normal with a node instead.
  18471. *
  18472. * If you don't want to overwrite the clearcoat normal but modify the existing
  18473. * value instead, use {@link materialClearcoatNormal}.
  18474. *
  18475. * @type {?Node<vec3>}
  18476. * @default null
  18477. */
  18478. this.clearcoatNormalNode = null;
  18479. /**
  18480. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  18481. * and `sheenColorMap` properties. This node property allows to overwrite the default
  18482. * and define the sheen with a node instead.
  18483. *
  18484. * If you don't want to overwrite the sheen but modify the existing
  18485. * value instead, use {@link materialSheen}.
  18486. *
  18487. * @type {?Node<vec3>}
  18488. * @default null
  18489. */
  18490. this.sheenNode = null;
  18491. /**
  18492. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  18493. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  18494. * and define the sheen roughness with a node instead.
  18495. *
  18496. * If you don't want to overwrite the sheen roughness but modify the existing
  18497. * value instead, use {@link materialSheenRoughness}.
  18498. *
  18499. * @type {?Node<float>}
  18500. * @default null
  18501. */
  18502. this.sheenRoughnessNode = null;
  18503. /**
  18504. * The iridescence of physical materials is by default inferred from the `iridescence`
  18505. * property. This node property allows to overwrite the default
  18506. * and define the iridescence with a node instead.
  18507. *
  18508. * If you don't want to overwrite the iridescence but modify the existing
  18509. * value instead, use {@link materialIridescence}.
  18510. *
  18511. * @type {?Node<float>}
  18512. * @default null
  18513. */
  18514. this.iridescenceNode = null;
  18515. /**
  18516. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  18517. * property. This node property allows to overwrite the default
  18518. * and define the iridescence IOR with a node instead.
  18519. *
  18520. * If you don't want to overwrite the iridescence IOR but modify the existing
  18521. * value instead, use {@link materialIridescenceIOR}.
  18522. *
  18523. * @type {?Node<float>}
  18524. * @default null
  18525. */
  18526. this.iridescenceIORNode = null;
  18527. /**
  18528. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  18529. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  18530. * and define the iridescence thickness with a node instead.
  18531. *
  18532. * If you don't want to overwrite the iridescence thickness but modify the existing
  18533. * value instead, use {@link materialIridescenceThickness}.
  18534. *
  18535. * @type {?Node<float>}
  18536. * @default null
  18537. */
  18538. this.iridescenceThicknessNode = null;
  18539. /**
  18540. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  18541. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  18542. * and define the specular intensity with a node instead.
  18543. *
  18544. * If you don't want to overwrite the specular intensity but modify the existing
  18545. * value instead, use {@link materialSpecularIntensity}.
  18546. *
  18547. * @type {?Node<float>}
  18548. * @default null
  18549. */
  18550. this.specularIntensityNode = null;
  18551. /**
  18552. * The specular color of physical materials is by default inferred from the `specularColor`
  18553. * and `specularColorMap` properties. This node property allows to overwrite the default
  18554. * and define the specular color with a node instead.
  18555. *
  18556. * If you don't want to overwrite the specular color but modify the existing
  18557. * value instead, use {@link materialSpecularColor}.
  18558. *
  18559. * @type {?Node<vec3>}
  18560. * @default null
  18561. */
  18562. this.specularColorNode = null;
  18563. /**
  18564. * The ior of physical materials is by default inferred from the `ior`
  18565. * property. This node property allows to overwrite the default
  18566. * and define the ior with a node instead.
  18567. *
  18568. * If you don't want to overwrite the ior but modify the existing
  18569. * value instead, use {@link materialIOR}.
  18570. *
  18571. * @type {?Node<float>}
  18572. * @default null
  18573. */
  18574. this.iorNode = null;
  18575. /**
  18576. * The transmission of physical materials is by default inferred from the `transmission` and
  18577. * `transmissionMap` properties. This node property allows to overwrite the default
  18578. * and define the transmission with a node instead.
  18579. *
  18580. * If you don't want to overwrite the transmission but modify the existing
  18581. * value instead, use {@link materialTransmission}.
  18582. *
  18583. * @type {?Node<float>}
  18584. * @default null
  18585. */
  18586. this.transmissionNode = null;
  18587. /**
  18588. * The thickness of physical materials is by default inferred from the `thickness` and
  18589. * `thicknessMap` properties. This node property allows to overwrite the default
  18590. * and define the thickness with a node instead.
  18591. *
  18592. * If you don't want to overwrite the thickness but modify the existing
  18593. * value instead, use {@link materialThickness}.
  18594. *
  18595. * @type {?Node<float>}
  18596. * @default null
  18597. */
  18598. this.thicknessNode = null;
  18599. /**
  18600. * The attenuation distance of physical materials is by default inferred from the
  18601. * `attenuationDistance` property. This node property allows to overwrite the default
  18602. * and define the attenuation distance with a node instead.
  18603. *
  18604. * If you don't want to overwrite the attenuation distance but modify the existing
  18605. * value instead, use {@link materialAttenuationDistance}.
  18606. *
  18607. * @type {?Node<float>}
  18608. * @default null
  18609. */
  18610. this.attenuationDistanceNode = null;
  18611. /**
  18612. * The attenuation color of physical materials is by default inferred from the
  18613. * `attenuationColor` property. This node property allows to overwrite the default
  18614. * and define the attenuation color with a node instead.
  18615. *
  18616. * If you don't want to overwrite the attenuation color but modify the existing
  18617. * value instead, use {@link materialAttenuationColor}.
  18618. *
  18619. * @type {?Node<vec3>}
  18620. * @default null
  18621. */
  18622. this.attenuationColorNode = null;
  18623. /**
  18624. * The dispersion of physical materials is by default inferred from the
  18625. * `dispersion` property. This node property allows to overwrite the default
  18626. * and define the dispersion with a node instead.
  18627. *
  18628. * If you don't want to overwrite the dispersion but modify the existing
  18629. * value instead, use {@link materialDispersion}.
  18630. *
  18631. * @type {?Node<float>}
  18632. * @default null
  18633. */
  18634. this.dispersionNode = null;
  18635. /**
  18636. * The anisotropy of physical materials is by default inferred from the
  18637. * `anisotropy` property. This node property allows to overwrite the default
  18638. * and define the anisotropy with a node instead.
  18639. *
  18640. * If you don't want to overwrite the anisotropy but modify the existing
  18641. * value instead, use {@link materialAnisotropy}.
  18642. *
  18643. * @type {?Node<float>}
  18644. * @default null
  18645. */
  18646. this.anisotropyNode = null;
  18647. this.setDefaultValues( _defaultValues$5 );
  18648. this.setValues( parameters );
  18649. }
  18650. /**
  18651. * Whether the lighting model should use clearcoat or not.
  18652. *
  18653. * @type {boolean}
  18654. * @default true
  18655. */
  18656. get useClearcoat() {
  18657. return this.clearcoat > 0 || this.clearcoatNode !== null;
  18658. }
  18659. /**
  18660. * Whether the lighting model should use iridescence or not.
  18661. *
  18662. * @type {boolean}
  18663. * @default true
  18664. */
  18665. get useIridescence() {
  18666. return this.iridescence > 0 || this.iridescenceNode !== null;
  18667. }
  18668. /**
  18669. * Whether the lighting model should use sheen or not.
  18670. *
  18671. * @type {boolean}
  18672. * @default true
  18673. */
  18674. get useSheen() {
  18675. return this.sheen > 0 || this.sheenNode !== null;
  18676. }
  18677. /**
  18678. * Whether the lighting model should use anisotropy or not.
  18679. *
  18680. * @type {boolean}
  18681. * @default true
  18682. */
  18683. get useAnisotropy() {
  18684. return this.anisotropy > 0 || this.anisotropyNode !== null;
  18685. }
  18686. /**
  18687. * Whether the lighting model should use transmission or not.
  18688. *
  18689. * @type {boolean}
  18690. * @default true
  18691. */
  18692. get useTransmission() {
  18693. return this.transmission > 0 || this.transmissionNode !== null;
  18694. }
  18695. /**
  18696. * Whether the lighting model should use dispersion or not.
  18697. *
  18698. * @type {boolean}
  18699. * @default true
  18700. */
  18701. get useDispersion() {
  18702. return this.dispersion > 0 || this.dispersionNode !== null;
  18703. }
  18704. /**
  18705. * Setups the specular related node variables.
  18706. */
  18707. setupSpecular() {
  18708. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  18709. ior.assign( iorNode );
  18710. specularColor.assign( mix( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ), diffuseColor.rgb, metalness ) );
  18711. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  18712. }
  18713. /**
  18714. * Setups the lighting model.
  18715. *
  18716. * @return {PhysicalLightingModel} The lighting model.
  18717. */
  18718. setupLightingModel( /*builder*/ ) {
  18719. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  18720. }
  18721. /**
  18722. * Setups the physical specific node variables.
  18723. *
  18724. * @param {NodeBuilder} builder - The current node builder.
  18725. */
  18726. setupVariants( builder ) {
  18727. super.setupVariants( builder );
  18728. // CLEARCOAT
  18729. if ( this.useClearcoat ) {
  18730. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  18731. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  18732. clearcoat.assign( clearcoatNode );
  18733. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  18734. }
  18735. // SHEEN
  18736. if ( this.useSheen ) {
  18737. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  18738. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  18739. sheen.assign( sheenNode );
  18740. sheenRoughness.assign( sheenRoughnessNode );
  18741. }
  18742. // IRIDESCENCE
  18743. if ( this.useIridescence ) {
  18744. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  18745. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  18746. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  18747. iridescence.assign( iridescenceNode );
  18748. iridescenceIOR.assign( iridescenceIORNode );
  18749. iridescenceThickness.assign( iridescenceThicknessNode );
  18750. }
  18751. // ANISOTROPY
  18752. if ( this.useAnisotropy ) {
  18753. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  18754. anisotropy.assign( anisotropyV.length() );
  18755. If( anisotropy.equal( 0.0 ), () => {
  18756. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  18757. } ).Else( () => {
  18758. anisotropyV.divAssign( vec2( anisotropy ) );
  18759. anisotropy.assign( anisotropy.saturate() );
  18760. } );
  18761. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  18762. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  18763. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  18764. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  18765. }
  18766. // TRANSMISSION
  18767. if ( this.useTransmission ) {
  18768. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  18769. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  18770. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  18771. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  18772. transmission.assign( transmissionNode );
  18773. thickness.assign( thicknessNode );
  18774. attenuationDistance.assign( attenuationDistanceNode );
  18775. attenuationColor.assign( attenuationColorNode );
  18776. if ( this.useDispersion ) {
  18777. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  18778. dispersion.assign( dispersionNode );
  18779. }
  18780. }
  18781. }
  18782. /**
  18783. * Setups the clearcoat normal node.
  18784. *
  18785. * @return {Node<vec3>} The clearcoat normal.
  18786. */
  18787. setupClearcoatNormal() {
  18788. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  18789. }
  18790. setup( builder ) {
  18791. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  18792. super.setup( builder );
  18793. }
  18794. copy( source ) {
  18795. this.clearcoatNode = source.clearcoatNode;
  18796. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  18797. this.clearcoatNormalNode = source.clearcoatNormalNode;
  18798. this.sheenNode = source.sheenNode;
  18799. this.sheenRoughnessNode = source.sheenRoughnessNode;
  18800. this.iridescenceNode = source.iridescenceNode;
  18801. this.iridescenceIORNode = source.iridescenceIORNode;
  18802. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  18803. this.specularIntensityNode = source.specularIntensityNode;
  18804. this.specularColorNode = source.specularColorNode;
  18805. this.transmissionNode = source.transmissionNode;
  18806. this.thicknessNode = source.thicknessNode;
  18807. this.attenuationDistanceNode = source.attenuationDistanceNode;
  18808. this.attenuationColorNode = source.attenuationColorNode;
  18809. this.dispersionNode = source.dispersionNode;
  18810. this.anisotropyNode = source.anisotropyNode;
  18811. return super.copy( source );
  18812. }
  18813. }
  18814. /**
  18815. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  18816. *
  18817. * @augments PhysicalLightingModel
  18818. */
  18819. class SSSLightingModel extends PhysicalLightingModel {
  18820. /**
  18821. * Constructs a new physical lighting model.
  18822. *
  18823. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  18824. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  18825. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  18826. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  18827. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  18828. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  18829. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  18830. */
  18831. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  18832. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  18833. /**
  18834. * Whether the lighting model should use SSS or not.
  18835. *
  18836. * @type {boolean}
  18837. * @default false
  18838. */
  18839. this.useSSS = sss;
  18840. }
  18841. /**
  18842. * Extends the default implementation with a SSS term.
  18843. *
  18844. * 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/)
  18845. *
  18846. * @param {Object} input - The input data.
  18847. * @param {NodeBuilder} builder - The current node builder.
  18848. */
  18849. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  18850. if ( this.useSSS === true ) {
  18851. const material = builder.material;
  18852. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  18853. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  18854. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  18855. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  18856. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  18857. }
  18858. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  18859. }
  18860. }
  18861. /**
  18862. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  18863. * that implements a Subsurface scattering (SSS) term.
  18864. *
  18865. * @augments MeshPhysicalNodeMaterial
  18866. */
  18867. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  18868. static get type() {
  18869. return 'MeshSSSNodeMaterial';
  18870. }
  18871. /**
  18872. * Constructs a new mesh SSS node material.
  18873. *
  18874. * @param {Object} [parameters] - The configuration parameter.
  18875. */
  18876. constructor( parameters ) {
  18877. super( parameters );
  18878. /**
  18879. * Represents the thickness color.
  18880. *
  18881. * @type {?Node<vec3>}
  18882. * @default null
  18883. */
  18884. this.thicknessColorNode = null;
  18885. /**
  18886. * Represents the distortion factor.
  18887. *
  18888. * @type {?Node<float>}
  18889. */
  18890. this.thicknessDistortionNode = float( 0.1 );
  18891. /**
  18892. * Represents the thickness ambient factor.
  18893. *
  18894. * @type {?Node<float>}
  18895. */
  18896. this.thicknessAmbientNode = float( 0.0 );
  18897. /**
  18898. * Represents the thickness attenuation.
  18899. *
  18900. * @type {?Node<float>}
  18901. */
  18902. this.thicknessAttenuationNode = float( .1 );
  18903. /**
  18904. * Represents the thickness power.
  18905. *
  18906. * @type {?Node<float>}
  18907. */
  18908. this.thicknessPowerNode = float( 2.0 );
  18909. /**
  18910. * Represents the thickness scale.
  18911. *
  18912. * @type {?Node<float>}
  18913. */
  18914. this.thicknessScaleNode = float( 10.0 );
  18915. }
  18916. /**
  18917. * Whether the lighting model should use SSS or not.
  18918. *
  18919. * @type {boolean}
  18920. * @default true
  18921. */
  18922. get useSSS() {
  18923. return this.thicknessColorNode !== null;
  18924. }
  18925. /**
  18926. * Setups the lighting model.
  18927. *
  18928. * @return {SSSLightingModel} The lighting model.
  18929. */
  18930. setupLightingModel( /*builder*/ ) {
  18931. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  18932. }
  18933. copy( source ) {
  18934. this.thicknessColorNode = source.thicknessColorNode;
  18935. this.thicknessDistortionNode = source.thicknessDistortionNode;
  18936. this.thicknessAmbientNode = source.thicknessAmbientNode;
  18937. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  18938. this.thicknessPowerNode = source.thicknessPowerNode;
  18939. this.thicknessScaleNode = source.thicknessScaleNode;
  18940. return super.copy( source );
  18941. }
  18942. }
  18943. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  18944. // dotNL will be from -1.0 to 1.0
  18945. const dotNL = normal.dot( lightDirection );
  18946. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  18947. if ( builder.material.gradientMap ) {
  18948. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  18949. return vec3( gradientMap.r );
  18950. } else {
  18951. const fw = coord.fwidth().mul( 0.5 );
  18952. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  18953. }
  18954. } );
  18955. /**
  18956. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  18957. *
  18958. * @augments LightingModel
  18959. */
  18960. class ToonLightingModel extends LightingModel {
  18961. /**
  18962. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  18963. * reduced to a small number of discrete shades to create a comic-like, flat look.
  18964. *
  18965. * @param {Object} lightData - The light data.
  18966. * @param {NodeBuilder} builder - The current node builder.
  18967. */
  18968. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  18969. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  18970. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  18971. }
  18972. /**
  18973. * Implements the indirect lighting.
  18974. *
  18975. * @param {NodeBuilder} builder - The current node builder.
  18976. */
  18977. indirect( builder ) {
  18978. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  18979. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  18980. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  18981. }
  18982. }
  18983. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  18984. /**
  18985. * Node material version of {@link MeshToonMaterial}.
  18986. *
  18987. * @augments NodeMaterial
  18988. */
  18989. class MeshToonNodeMaterial extends NodeMaterial {
  18990. static get type() {
  18991. return 'MeshToonNodeMaterial';
  18992. }
  18993. /**
  18994. * Constructs a new mesh toon node material.
  18995. *
  18996. * @param {Object} [parameters] - The configuration parameter.
  18997. */
  18998. constructor( parameters ) {
  18999. super();
  19000. /**
  19001. * This flag can be used for type testing.
  19002. *
  19003. * @type {boolean}
  19004. * @readonly
  19005. * @default true
  19006. */
  19007. this.isMeshToonNodeMaterial = true;
  19008. /**
  19009. * Set to `true` because toon materials react on lights.
  19010. *
  19011. * @type {boolean}
  19012. * @default true
  19013. */
  19014. this.lights = true;
  19015. this.setDefaultValues( _defaultValues$4 );
  19016. this.setValues( parameters );
  19017. }
  19018. /**
  19019. * Setups the lighting model.
  19020. *
  19021. * @return {ToonLightingModel} The lighting model.
  19022. */
  19023. setupLightingModel( /*builder*/ ) {
  19024. return new ToonLightingModel();
  19025. }
  19026. }
  19027. /**
  19028. * TSL function for creating a matcap uv node.
  19029. *
  19030. * Can be used to compute texture coordinates for projecting a
  19031. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  19032. *
  19033. * @tsl
  19034. * @function
  19035. * @returns {Node<vec2>} The matcap UV coordinates.
  19036. */
  19037. const matcapUV = /*@__PURE__*/ Fn( () => {
  19038. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  19039. const y = positionViewDirection.cross( x );
  19040. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  19041. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  19042. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  19043. /**
  19044. * Node material version of {@link MeshMatcapMaterial}.
  19045. *
  19046. * @augments NodeMaterial
  19047. */
  19048. class MeshMatcapNodeMaterial extends NodeMaterial {
  19049. static get type() {
  19050. return 'MeshMatcapNodeMaterial';
  19051. }
  19052. /**
  19053. * Constructs a new mesh normal node material.
  19054. *
  19055. * @param {Object} [parameters] - The configuration parameter.
  19056. */
  19057. constructor( parameters ) {
  19058. super();
  19059. /**
  19060. * This flag can be used for type testing.
  19061. *
  19062. * @type {boolean}
  19063. * @readonly
  19064. * @default true
  19065. */
  19066. this.isMeshMatcapNodeMaterial = true;
  19067. this.setDefaultValues( _defaultValues$3 );
  19068. this.setValues( parameters );
  19069. }
  19070. /**
  19071. * Setups the matcap specific node variables.
  19072. *
  19073. * @param {NodeBuilder} builder - The current node builder.
  19074. */
  19075. setupVariants( builder ) {
  19076. const uv = matcapUV;
  19077. let matcapColor;
  19078. if ( builder.material.matcap ) {
  19079. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  19080. } else {
  19081. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  19082. }
  19083. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  19084. }
  19085. }
  19086. /**
  19087. * Applies a rotation to the given position node.
  19088. *
  19089. * @augments TempNode
  19090. */
  19091. class RotateNode extends TempNode {
  19092. static get type() {
  19093. return 'RotateNode';
  19094. }
  19095. /**
  19096. * Constructs a new rotate node.
  19097. *
  19098. * @param {Node} positionNode - The position node.
  19099. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19100. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19101. */
  19102. constructor( positionNode, rotationNode ) {
  19103. super();
  19104. /**
  19105. * The position node.
  19106. *
  19107. * @type {Node}
  19108. */
  19109. this.positionNode = positionNode;
  19110. /**
  19111. * Represents the rotation that is applied to the position node.
  19112. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19113. *
  19114. * @type {Node}
  19115. */
  19116. this.rotationNode = rotationNode;
  19117. }
  19118. /**
  19119. * The type of the {@link RotateNode#positionNode} defines the node's type.
  19120. *
  19121. * @param {NodeBuilder} builder - The current node builder.
  19122. * @return {string} The node's type.
  19123. */
  19124. getNodeType( builder ) {
  19125. return this.positionNode.getNodeType( builder );
  19126. }
  19127. setup( builder ) {
  19128. const { rotationNode, positionNode } = this;
  19129. const nodeType = this.getNodeType( builder );
  19130. if ( nodeType === 'vec2' ) {
  19131. const cosAngle = rotationNode.cos();
  19132. const sinAngle = rotationNode.sin();
  19133. const rotationMatrix = mat2(
  19134. cosAngle, sinAngle,
  19135. sinAngle.negate(), cosAngle
  19136. );
  19137. return rotationMatrix.mul( positionNode );
  19138. } else {
  19139. const rotation = rotationNode;
  19140. 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 ) );
  19141. 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 ) );
  19142. 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 ) );
  19143. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  19144. }
  19145. }
  19146. }
  19147. /**
  19148. * TSL function for creating a rotate node.
  19149. *
  19150. * @tsl
  19151. * @function
  19152. * @param {Node} positionNode - The position node.
  19153. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19154. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19155. * @returns {RotateNode}
  19156. */
  19157. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  19158. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  19159. /**
  19160. * Node material version of {@link SpriteMaterial}.
  19161. *
  19162. * @augments NodeMaterial
  19163. */
  19164. class SpriteNodeMaterial extends NodeMaterial {
  19165. static get type() {
  19166. return 'SpriteNodeMaterial';
  19167. }
  19168. /**
  19169. * Constructs a new sprite node material.
  19170. *
  19171. * @param {Object} [parameters] - The configuration parameter.
  19172. */
  19173. constructor( parameters ) {
  19174. super();
  19175. /**
  19176. * This flag can be used for type testing.
  19177. *
  19178. * @type {boolean}
  19179. * @readonly
  19180. * @default true
  19181. */
  19182. this.isSpriteNodeMaterial = true;
  19183. this._useSizeAttenuation = true;
  19184. /**
  19185. * This property makes it possible to define the position of the sprite with a
  19186. * node. That can be useful when the material is used with instanced rendering
  19187. * and node data are defined with an instanced attribute node:
  19188. * ```js
  19189. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  19190. * material.positionNode = instancedBufferAttribute( positionAttribute );
  19191. * ```
  19192. * Another possibility is to compute the instanced data with a compute shader:
  19193. * ```js
  19194. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  19195. * particleMaterial.positionNode = positionBuffer.toAttribute();
  19196. * ```
  19197. *
  19198. * @type {?Node<vec2>}
  19199. * @default null
  19200. */
  19201. this.positionNode = null;
  19202. /**
  19203. * The rotation of sprite materials is by default inferred from the `rotation`,
  19204. * property. This node property allows to overwrite the default and define
  19205. * the rotation with a node instead.
  19206. *
  19207. * If you don't want to overwrite the rotation but modify the existing
  19208. * value instead, use {@link materialRotation}.
  19209. *
  19210. * @type {?Node<float>}
  19211. * @default null
  19212. */
  19213. this.rotationNode = null;
  19214. /**
  19215. * This node property provides an additional way to scale sprites next to
  19216. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  19217. * is multiplied with the scale value of this node in the vertex shader.
  19218. *
  19219. * @type {?Node<vec2>}
  19220. * @default null
  19221. */
  19222. this.scaleNode = null;
  19223. /**
  19224. * In Sprites, the transparent property is enabled by default.
  19225. *
  19226. * @type {boolean}
  19227. * @default true
  19228. */
  19229. this.transparent = true;
  19230. this.setDefaultValues( _defaultValues$2 );
  19231. this.setValues( parameters );
  19232. }
  19233. /**
  19234. * Setups the position node in view space. This method implements
  19235. * the sprite specific vertex shader.
  19236. *
  19237. * @param {NodeBuilder} builder - The current node builder.
  19238. * @return {Node<vec3>} The position in view space.
  19239. */
  19240. setupPositionView( builder ) {
  19241. const { object, camera } = builder;
  19242. const { positionNode, rotationNode, scaleNode, sizeAttenuation } = this;
  19243. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  19244. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  19245. if ( scaleNode !== null ) {
  19246. scale = scale.mul( vec2( scaleNode ) );
  19247. }
  19248. if ( camera.isPerspectiveCamera && sizeAttenuation === false ) {
  19249. scale = scale.mul( mvPosition.z.negate() );
  19250. }
  19251. let alignedPosition = positionGeometry.xy;
  19252. if ( object.center && object.center.isVector2 === true ) {
  19253. const center = reference$1( 'center', 'vec2', object );
  19254. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  19255. }
  19256. alignedPosition = alignedPosition.mul( scale );
  19257. const rotation = float( rotationNode || materialRotation );
  19258. const rotatedPosition = rotate( alignedPosition, rotation );
  19259. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  19260. }
  19261. copy( source ) {
  19262. this.positionNode = source.positionNode;
  19263. this.rotationNode = source.rotationNode;
  19264. this.scaleNode = source.scaleNode;
  19265. return super.copy( source );
  19266. }
  19267. /**
  19268. * Whether to use size attenuation or not.
  19269. *
  19270. * @type {boolean}
  19271. * @default true
  19272. */
  19273. get sizeAttenuation() {
  19274. return this._useSizeAttenuation;
  19275. }
  19276. set sizeAttenuation( value ) {
  19277. if ( this._useSizeAttenuation !== value ) {
  19278. this._useSizeAttenuation = value;
  19279. this.needsUpdate = true;
  19280. }
  19281. }
  19282. }
  19283. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  19284. const _size$4 = /*@__PURE__*/ new Vector2();
  19285. /**
  19286. * Node material version of {@link PointsMaterial}.
  19287. *
  19288. * This material can be used in two ways:
  19289. *
  19290. * - By rendering point primitives with {@link Points}. Since WebGPU only supports point primitives
  19291. * with a pixel size of `1`, it's not possible to define a size.
  19292. *
  19293. * ```js
  19294. * const pointCloud = new THREE.Points( geometry, new THREE.PointsNodeMaterial() );
  19295. * ```
  19296. *
  19297. * - By rendering point primitives with {@link Sprites}. In this case, size is honored,
  19298. * see {@link PointsNodeMaterial#sizeNode}.
  19299. *
  19300. * ```js
  19301. * const instancedPoints = new THREE.Sprite( new THREE.PointsNodeMaterial( { positionNode: instancedBufferAttribute( positionAttribute ) } ) );
  19302. * ```
  19303. *
  19304. * @augments SpriteNodeMaterial
  19305. */
  19306. class PointsNodeMaterial extends SpriteNodeMaterial {
  19307. static get type() {
  19308. return 'PointsNodeMaterial';
  19309. }
  19310. /**
  19311. * Constructs a new points node material.
  19312. *
  19313. * @param {Object} [parameters] - The configuration parameter.
  19314. */
  19315. constructor( parameters ) {
  19316. super();
  19317. /**
  19318. * This node property provides an additional way to set the point size.
  19319. *
  19320. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  19321. * this node has no effect when the material is used with {@link Points} and a WebGPU
  19322. * backend. If an application wants to render points with a size larger than 1 pixel,
  19323. * the material should be used with {@link Sprite} and instancing.
  19324. *
  19325. * @type {?Node<vec2>}
  19326. * @default null
  19327. */
  19328. this.sizeNode = null;
  19329. /**
  19330. * This flag can be used for type testing.
  19331. *
  19332. * @type {boolean}
  19333. * @readonly
  19334. * @default true
  19335. */
  19336. this.isPointsNodeMaterial = true;
  19337. this.setDefaultValues( _defaultValues$1 );
  19338. this.setValues( parameters );
  19339. }
  19340. setupPositionView() {
  19341. const { positionNode } = this;
  19342. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  19343. }
  19344. setupVertexSprite( builder ) {
  19345. const { material, camera } = builder;
  19346. const { rotationNode, scaleNode, sizeNode, sizeAttenuation } = this;
  19347. let mvp = super.setupVertex( builder );
  19348. // skip further processing if the material is not a node material
  19349. if ( material.isNodeMaterial !== true ) {
  19350. return mvp;
  19351. }
  19352. // point size
  19353. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  19354. pointSize = pointSize.mul( screenDPR );
  19355. // size attenuation
  19356. if ( camera.isPerspectiveCamera && sizeAttenuation === true ) {
  19357. // follow WebGLRenderer's implementation, and scale by half the canvas height in logical units
  19358. pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
  19359. }
  19360. // scale
  19361. if ( scaleNode && scaleNode.isNode ) {
  19362. pointSize = pointSize.mul( vec2( scaleNode ) );
  19363. }
  19364. // compute offset
  19365. let offset = positionGeometry.xy;
  19366. // apply rotation
  19367. if ( rotationNode && rotationNode.isNode ) {
  19368. const rotation = float( rotationNode );
  19369. offset = rotate( offset, rotation );
  19370. }
  19371. // account for point size
  19372. offset = offset.mul( pointSize );
  19373. // scale by viewport size
  19374. offset = offset.div( viewportSize.div( 2 ) );
  19375. // compensate for the perspective divide
  19376. offset = offset.mul( mvp.w );
  19377. // add offset
  19378. mvp = mvp.add( vec4( offset, 0, 0 ) );
  19379. return mvp;
  19380. }
  19381. setupVertex( builder ) {
  19382. if ( builder.object.isPoints ) {
  19383. return super.setupVertex( builder );
  19384. } else {
  19385. return this.setupVertexSprite( builder );
  19386. }
  19387. }
  19388. /**
  19389. * Whether alpha to coverage should be used or not.
  19390. *
  19391. * @type {boolean}
  19392. * @default true
  19393. */
  19394. get alphaToCoverage() {
  19395. return this._useAlphaToCoverage;
  19396. }
  19397. set alphaToCoverage( value ) {
  19398. if ( this._useAlphaToCoverage !== value ) {
  19399. this._useAlphaToCoverage = value;
  19400. this.needsUpdate = true;
  19401. }
  19402. }
  19403. }
  19404. const scale = /*@__PURE__*/ uniform( 1 ).onFrameUpdate( function ( { renderer } ) {
  19405. const size = renderer.getSize( _size$4 ); // logical units
  19406. this.value = 0.5 * size.y;
  19407. } );
  19408. /**
  19409. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  19410. *
  19411. * @augments LightingModel
  19412. */
  19413. class ShadowMaskModel extends LightingModel {
  19414. /**
  19415. * Constructs a new shadow mask model.
  19416. */
  19417. constructor() {
  19418. super();
  19419. /**
  19420. * The shadow mask node.
  19421. *
  19422. * @type {Node}
  19423. */
  19424. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  19425. }
  19426. /**
  19427. * Only used to save the shadow mask.
  19428. *
  19429. * @param {Object} input - The input data.
  19430. */
  19431. direct( { lightNode } ) {
  19432. if ( lightNode.shadowNode !== null ) {
  19433. this.shadowNode.mulAssign( lightNode.shadowNode );
  19434. }
  19435. }
  19436. /**
  19437. * Uses the shadow mask to produce the final color.
  19438. *
  19439. * @param {NodeBuilder} builder - The current node builder.
  19440. */
  19441. finish( { context } ) {
  19442. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  19443. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  19444. }
  19445. }
  19446. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  19447. /**
  19448. * Node material version of {@link ShadowMaterial}.
  19449. *
  19450. * @augments NodeMaterial
  19451. */
  19452. class ShadowNodeMaterial extends NodeMaterial {
  19453. static get type() {
  19454. return 'ShadowNodeMaterial';
  19455. }
  19456. /**
  19457. * Constructs a new shadow node material.
  19458. *
  19459. * @param {Object} [parameters] - The configuration parameter.
  19460. */
  19461. constructor( parameters ) {
  19462. super();
  19463. /**
  19464. * This flag can be used for type testing.
  19465. *
  19466. * @type {boolean}
  19467. * @readonly
  19468. * @default true
  19469. */
  19470. this.isShadowNodeMaterial = true;
  19471. /**
  19472. * Set to `true` because so it's possible to implement
  19473. * the shadow mask effect.
  19474. *
  19475. * @type {boolean}
  19476. * @default true
  19477. */
  19478. this.lights = true;
  19479. /**
  19480. * Overwritten since shadow materials are transparent
  19481. * by default.
  19482. *
  19483. * @type {boolean}
  19484. * @default true
  19485. */
  19486. this.transparent = true;
  19487. this.setDefaultValues( _defaultValues );
  19488. this.setValues( parameters );
  19489. }
  19490. /**
  19491. * Setups the lighting model.
  19492. *
  19493. * @return {ShadowMaskModel} The lighting model.
  19494. */
  19495. setupLightingModel( /*builder*/ ) {
  19496. return new ShadowMaskModel();
  19497. }
  19498. }
  19499. const scatteringDensity = property( 'vec3' );
  19500. const linearDepthRay = property( 'vec3' );
  19501. const outgoingRayLight = property( 'vec3' );
  19502. /**
  19503. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  19504. * This model calculates the scattering and transmittance of light through a volumetric medium.
  19505. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  19506. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  19507. *
  19508. * @augments LightingModel
  19509. */
  19510. class VolumetricLightingModel extends LightingModel {
  19511. constructor() {
  19512. super();
  19513. }
  19514. start( builder ) {
  19515. const { material } = builder;
  19516. const startPos = property( 'vec3' );
  19517. const endPos = property( 'vec3' );
  19518. // This approach dynamically changes the direction of the ray,
  19519. // 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.
  19520. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  19521. startPos.assign( cameraPosition );
  19522. endPos.assign( positionWorld );
  19523. } ).Else( () => {
  19524. startPos.assign( positionWorld );
  19525. endPos.assign( cameraPosition );
  19526. } );
  19527. //
  19528. const viewVector = endPos.sub( startPos );
  19529. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  19530. const stepSize = viewVector.length().div( steps ).toVar();
  19531. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  19532. const distTravelled = float( 0.0 ).toVar();
  19533. const transmittance = vec3( 1 ).toVar();
  19534. if ( material.offsetNode ) {
  19535. // reduce banding
  19536. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  19537. }
  19538. Loop( steps, () => {
  19539. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  19540. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  19541. if ( material.depthNode !== null ) {
  19542. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  19543. builder.context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  19544. }
  19545. builder.context.positionWorld = positionRay;
  19546. builder.context.shadowPositionWorld = positionRay;
  19547. builder.context.positionView = positionViewRay;
  19548. scatteringDensity.assign( 0 );
  19549. let scatteringNode;
  19550. if ( material.scatteringNode ) {
  19551. scatteringNode = material.scatteringNode( {
  19552. positionRay
  19553. } );
  19554. }
  19555. super.start( builder );
  19556. if ( scatteringNode ) {
  19557. scatteringDensity.mulAssign( scatteringNode );
  19558. }
  19559. // beer's law
  19560. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  19561. transmittance.mulAssign( falloff );
  19562. // move along the ray
  19563. distTravelled.addAssign( stepSize );
  19564. } );
  19565. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  19566. }
  19567. scatteringLight( lightColor, builder ) {
  19568. const sceneDepthNode = builder.context.sceneDepthNode;
  19569. if ( sceneDepthNode ) {
  19570. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  19571. scatteringDensity.addAssign( lightColor );
  19572. } );
  19573. } else {
  19574. scatteringDensity.addAssign( lightColor );
  19575. }
  19576. }
  19577. direct( { lightNode, lightColor }, builder ) {
  19578. // Ignore lights with infinite distance
  19579. if ( lightNode.light.distance === undefined ) return;
  19580. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  19581. const directLight = lightColor.xyz.toVar();
  19582. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  19583. this.scatteringLight( directLight, builder );
  19584. }
  19585. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  19586. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  19587. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  19588. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  19589. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  19590. const P = builder.context.positionView;
  19591. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  19592. this.scatteringLight( directLight, builder );
  19593. }
  19594. finish( builder ) {
  19595. builder.context.outgoingLight.assign( outgoingRayLight );
  19596. }
  19597. }
  19598. /**
  19599. * Volume node material.
  19600. *
  19601. * @augments NodeMaterial
  19602. */
  19603. class VolumeNodeMaterial extends NodeMaterial {
  19604. static get type() {
  19605. return 'VolumeNodeMaterial';
  19606. }
  19607. /**
  19608. * Constructs a new volume node material.
  19609. *
  19610. * @param {Object} [parameters] - The configuration parameter.
  19611. */
  19612. constructor( parameters ) {
  19613. super();
  19614. /**
  19615. * This flag can be used for type testing.
  19616. *
  19617. * @type {boolean}
  19618. * @readonly
  19619. * @default true
  19620. */
  19621. this.isVolumeNodeMaterial = true;
  19622. /**
  19623. * Number of steps used for raymarching.
  19624. *
  19625. * @type {number}
  19626. * @default 25
  19627. */
  19628. this.steps = 25;
  19629. /**
  19630. * Offsets the distance a ray has been traveled through a volume.
  19631. * Can be used to implement dithering to reduce banding.
  19632. *
  19633. * @type {Node<float>}
  19634. * @default null
  19635. */
  19636. this.offsetNode = null;
  19637. /**
  19638. * Node used for scattering calculations.
  19639. *
  19640. * @type {Function|FunctionNode<vec4>}
  19641. * @default null
  19642. */
  19643. this.scatteringNode = null;
  19644. this.lights = true;
  19645. this.transparent = true;
  19646. this.side = BackSide;
  19647. this.depthTest = false;
  19648. this.depthWrite = false;
  19649. this.setValues( parameters );
  19650. }
  19651. setupLightingModel() {
  19652. return new VolumetricLightingModel();
  19653. }
  19654. }
  19655. /**
  19656. * This module manages the internal animation loop of the renderer.
  19657. *
  19658. * @private
  19659. */
  19660. class Animation {
  19661. /**
  19662. * Constructs a new animation loop management component.
  19663. *
  19664. * @param {Renderer} renderer - A reference to the main renderer.
  19665. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19666. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19667. */
  19668. constructor( renderer, nodes, info ) {
  19669. /**
  19670. * A reference to the main renderer.
  19671. *
  19672. * @type {Renderer}
  19673. */
  19674. this.renderer = renderer;
  19675. /**
  19676. * Renderer component for managing nodes related logic.
  19677. *
  19678. * @type {Nodes}
  19679. */
  19680. this.nodes = nodes;
  19681. /**
  19682. * Renderer component for managing metrics and monitoring data.
  19683. *
  19684. * @type {Info}
  19685. */
  19686. this.info = info;
  19687. /**
  19688. * A reference to the context from `requestAnimationFrame()` can
  19689. * be called (usually `window`).
  19690. *
  19691. * @type {?(Window|XRSession)}
  19692. */
  19693. this._context = typeof self !== 'undefined' ? self : null;
  19694. /**
  19695. * The user-defined animation loop.
  19696. *
  19697. * @type {?Function}
  19698. * @default null
  19699. */
  19700. this._animationLoop = null;
  19701. /**
  19702. * The requestId which is returned from the `requestAnimationFrame()` call.
  19703. * Can be used to cancel the stop the animation loop.
  19704. *
  19705. * @type {?number}
  19706. * @default null
  19707. */
  19708. this._requestId = null;
  19709. }
  19710. /**
  19711. * Starts the internal animation loop.
  19712. */
  19713. start() {
  19714. const update = ( time, xrFrame ) => {
  19715. this._requestId = this._context.requestAnimationFrame( update );
  19716. if ( this.info.autoReset === true ) this.info.reset();
  19717. this.nodes.nodeFrame.update();
  19718. this.info.frame = this.nodes.nodeFrame.frameId;
  19719. this.renderer._inspector.begin();
  19720. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  19721. this.renderer._inspector.finish();
  19722. };
  19723. update();
  19724. }
  19725. /**
  19726. * Stops the internal animation loop.
  19727. */
  19728. stop() {
  19729. this._context.cancelAnimationFrame( this._requestId );
  19730. this._requestId = null;
  19731. }
  19732. /**
  19733. * Returns the user-level animation loop.
  19734. *
  19735. * @return {?Function} The animation loop.
  19736. */
  19737. getAnimationLoop() {
  19738. return this._animationLoop;
  19739. }
  19740. /**
  19741. * Defines the user-level animation loop.
  19742. *
  19743. * @param {?Function} callback - The animation loop.
  19744. */
  19745. setAnimationLoop( callback ) {
  19746. this._animationLoop = callback;
  19747. }
  19748. /**
  19749. * Returns the animation context.
  19750. *
  19751. * @return {Window|XRSession} The animation context.
  19752. */
  19753. getContext() {
  19754. return this._context;
  19755. }
  19756. /**
  19757. * Defines the context in which `requestAnimationFrame()` is executed.
  19758. *
  19759. * @param {Window|XRSession} context - The context to set.
  19760. */
  19761. setContext( context ) {
  19762. this._context = context;
  19763. }
  19764. /**
  19765. * Frees all internal resources and stops the animation loop.
  19766. */
  19767. dispose() {
  19768. this.stop();
  19769. }
  19770. }
  19771. /**
  19772. * Data structure for the renderer. It allows defining values
  19773. * with chained, hierarchical keys. Keys are meant to be
  19774. * objects since the module internally works with Weak Maps
  19775. * for performance reasons.
  19776. *
  19777. * @private
  19778. */
  19779. class ChainMap {
  19780. /**
  19781. * Constructs a new Chain Map.
  19782. */
  19783. constructor() {
  19784. /**
  19785. * The root Weak Map.
  19786. *
  19787. * @type {WeakMap<Object, WeakMap>}
  19788. */
  19789. this.weakMap = new WeakMap();
  19790. }
  19791. /**
  19792. * Returns the value for the given array of keys.
  19793. *
  19794. * @param {Array<Object>} keys - List of keys.
  19795. * @return {any} The value. Returns `undefined` if no value was found.
  19796. */
  19797. get( keys ) {
  19798. let map = this.weakMap;
  19799. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19800. map = map.get( keys[ i ] );
  19801. if ( map === undefined ) return undefined;
  19802. }
  19803. return map.get( keys[ keys.length - 1 ] );
  19804. }
  19805. /**
  19806. * Sets the value for the given keys.
  19807. *
  19808. * @param {Array<Object>} keys - List of keys.
  19809. * @param {any} value - The value to set.
  19810. * @return {ChainMap} A reference to this Chain Map.
  19811. */
  19812. set( keys, value ) {
  19813. let map = this.weakMap;
  19814. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19815. const key = keys[ i ];
  19816. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  19817. map = map.get( key );
  19818. }
  19819. map.set( keys[ keys.length - 1 ], value );
  19820. return this;
  19821. }
  19822. /**
  19823. * Deletes a value for the given keys.
  19824. *
  19825. * @param {Array<Object>} keys - The keys.
  19826. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  19827. */
  19828. delete( keys ) {
  19829. let map = this.weakMap;
  19830. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19831. map = map.get( keys[ i ] );
  19832. if ( map === undefined ) return false;
  19833. }
  19834. return map.delete( keys[ keys.length - 1 ] );
  19835. }
  19836. }
  19837. let _id$a = 0;
  19838. function getKeys( obj ) {
  19839. const keys = Object.keys( obj );
  19840. let proto = Object.getPrototypeOf( obj );
  19841. while ( proto ) {
  19842. const descriptors = Object.getOwnPropertyDescriptors( proto );
  19843. for ( const key in descriptors ) {
  19844. if ( descriptors[ key ] !== undefined ) {
  19845. const descriptor = descriptors[ key ];
  19846. if ( descriptor && typeof descriptor.get === 'function' ) {
  19847. keys.push( key );
  19848. }
  19849. }
  19850. }
  19851. proto = Object.getPrototypeOf( proto );
  19852. }
  19853. return keys;
  19854. }
  19855. /**
  19856. * A render object is the renderer's representation of single entity that gets drawn
  19857. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  19858. * scene since render objects also depend from the used material, the current render context
  19859. * and the current scene's lighting.
  19860. *
  19861. * In general, the basic process of the renderer is:
  19862. *
  19863. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  19864. * - Process the render lists by calling one or more render commands for each render item.
  19865. * - For each render command, request a render object and perform the draw.
  19866. *
  19867. * The module provides an interface to get data required for the draw command like the actual
  19868. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  19869. * creating render objects should only be done when necessary.
  19870. *
  19871. * @private
  19872. */
  19873. class RenderObject {
  19874. /**
  19875. * Constructs a new render object.
  19876. *
  19877. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19878. * @param {Geometries} geometries - Renderer component for managing geometries.
  19879. * @param {Renderer} renderer - The renderer.
  19880. * @param {Object3D} object - The 3D object.
  19881. * @param {Material} material - The 3D object's material.
  19882. * @param {Scene} scene - The scene the 3D object belongs to.
  19883. * @param {Camera} camera - The camera the object should be rendered with.
  19884. * @param {LightsNode} lightsNode - The lights node.
  19885. * @param {RenderContext} renderContext - The render context.
  19886. * @param {ClippingContext} clippingContext - The clipping context.
  19887. */
  19888. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  19889. this.id = _id$a ++;
  19890. /**
  19891. * Renderer component for managing nodes related logic.
  19892. *
  19893. * @type {Nodes}
  19894. * @private
  19895. */
  19896. this._nodes = nodes;
  19897. /**
  19898. * Renderer component for managing geometries.
  19899. *
  19900. * @type {Geometries}
  19901. * @private
  19902. */
  19903. this._geometries = geometries;
  19904. /**
  19905. * The renderer.
  19906. *
  19907. * @type {Renderer}
  19908. */
  19909. this.renderer = renderer;
  19910. /**
  19911. * The 3D object.
  19912. *
  19913. * @type {Object3D}
  19914. */
  19915. this.object = object;
  19916. /**
  19917. * The 3D object's material.
  19918. *
  19919. * @type {Material}
  19920. */
  19921. this.material = material;
  19922. /**
  19923. * The scene the 3D object belongs to.
  19924. *
  19925. * @type {Scene}
  19926. */
  19927. this.scene = scene;
  19928. /**
  19929. * The camera the 3D object should be rendered with.
  19930. *
  19931. * @type {Camera}
  19932. */
  19933. this.camera = camera;
  19934. /**
  19935. * The lights node.
  19936. *
  19937. * @type {LightsNode}
  19938. */
  19939. this.lightsNode = lightsNode;
  19940. /**
  19941. * The render context.
  19942. *
  19943. * @type {RenderContext}
  19944. */
  19945. this.context = renderContext;
  19946. /**
  19947. * The 3D object's geometry.
  19948. *
  19949. * @type {BufferGeometry}
  19950. */
  19951. this.geometry = object.geometry;
  19952. /**
  19953. * The render object's version.
  19954. *
  19955. * @type {number}
  19956. */
  19957. this.version = material.version;
  19958. /**
  19959. * The draw range of the geometry.
  19960. *
  19961. * @type {?Object}
  19962. * @default null
  19963. */
  19964. this.drawRange = null;
  19965. /**
  19966. * An array holding the buffer attributes
  19967. * of the render object. This entails attribute
  19968. * definitions on geometry and node level.
  19969. *
  19970. * @type {?Array<BufferAttribute>}
  19971. * @default null
  19972. */
  19973. this.attributes = null;
  19974. /**
  19975. * An object holding the version of the
  19976. * attributes. The keys are the attribute names
  19977. * and the values are the attribute versions.
  19978. *
  19979. * @type {?Object<string, number>}
  19980. * @default null
  19981. */
  19982. this.attributesId = null;
  19983. /**
  19984. * A reference to a render pipeline the render
  19985. * object is processed with.
  19986. *
  19987. * @type {RenderPipeline}
  19988. * @default null
  19989. */
  19990. this.pipeline = null;
  19991. /**
  19992. * Only relevant for objects using
  19993. * multiple materials. This represents a group entry
  19994. * from the respective `BufferGeometry`.
  19995. *
  19996. * @type {?{start: number, count: number}}
  19997. * @default null
  19998. */
  19999. this.group = null;
  20000. /**
  20001. * An array holding the vertex buffers which can
  20002. * be buffer attributes but also interleaved buffers.
  20003. *
  20004. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  20005. * @default null
  20006. */
  20007. this.vertexBuffers = null;
  20008. /**
  20009. * The parameters for the draw command.
  20010. *
  20011. * @type {?Object}
  20012. * @default null
  20013. */
  20014. this.drawParams = null;
  20015. /**
  20016. * If this render object is used inside a render bundle,
  20017. * this property points to the respective bundle group.
  20018. *
  20019. * @type {?BundleGroup}
  20020. * @default null
  20021. */
  20022. this.bundle = null;
  20023. /**
  20024. * The clipping context.
  20025. *
  20026. * @type {ClippingContext}
  20027. */
  20028. this.clippingContext = clippingContext;
  20029. /**
  20030. * The clipping context's cache key.
  20031. *
  20032. * @type {string}
  20033. */
  20034. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  20035. /**
  20036. * The initial node cache key.
  20037. *
  20038. * @type {number}
  20039. */
  20040. this.initialNodesCacheKey = this.getDynamicCacheKey();
  20041. /**
  20042. * The initial cache key.
  20043. *
  20044. * @type {number}
  20045. */
  20046. this.initialCacheKey = this.getCacheKey();
  20047. /**
  20048. * The node builder state.
  20049. *
  20050. * @type {?NodeBuilderState}
  20051. * @private
  20052. * @default null
  20053. */
  20054. this._nodeBuilderState = null;
  20055. /**
  20056. * An array of bindings.
  20057. *
  20058. * @type {?Array<BindGroup>}
  20059. * @private
  20060. * @default null
  20061. */
  20062. this._bindings = null;
  20063. /**
  20064. * Reference to the node material observer.
  20065. *
  20066. * @type {?NodeMaterialObserver}
  20067. * @private
  20068. * @default null
  20069. */
  20070. this._monitor = null;
  20071. /**
  20072. * An event listener which is defined by `RenderObjects`. It performs
  20073. * clean up tasks when `dispose()` on this render object.
  20074. *
  20075. * @method
  20076. */
  20077. this.onDispose = null;
  20078. /**
  20079. * This flag can be used for type testing.
  20080. *
  20081. * @type {boolean}
  20082. * @readonly
  20083. * @default true
  20084. */
  20085. this.isRenderObject = true;
  20086. /**
  20087. * An event listener which is executed when `dispose()` is called on
  20088. * the material of this render object.
  20089. *
  20090. * @method
  20091. */
  20092. this.onMaterialDispose = () => {
  20093. this.dispose();
  20094. };
  20095. /**
  20096. * An event listener which is executed when `dispose()` is called on
  20097. * the geometry of this render object.
  20098. *
  20099. * @method
  20100. */
  20101. this.onGeometryDispose = () => {
  20102. // clear geometry cache attributes
  20103. this.attributes = null;
  20104. this.attributesId = null;
  20105. };
  20106. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  20107. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  20108. }
  20109. /**
  20110. * Updates the clipping context.
  20111. *
  20112. * @param {ClippingContext} context - The clipping context to set.
  20113. */
  20114. updateClipping( context ) {
  20115. this.clippingContext = context;
  20116. }
  20117. /**
  20118. * Whether the clipping requires an update or not.
  20119. *
  20120. * @type {boolean}
  20121. * @readonly
  20122. */
  20123. get clippingNeedsUpdate() {
  20124. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  20125. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  20126. return true;
  20127. }
  20128. /**
  20129. * The number of clipping planes defined in context of hardware clipping.
  20130. *
  20131. * @type {number}
  20132. * @readonly
  20133. */
  20134. get hardwareClippingPlanes() {
  20135. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  20136. }
  20137. /**
  20138. * Returns the node builder state of this render object.
  20139. *
  20140. * @return {NodeBuilderState} The node builder state.
  20141. */
  20142. getNodeBuilderState() {
  20143. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  20144. }
  20145. /**
  20146. * Returns the node material observer of this render object.
  20147. *
  20148. * @return {NodeMaterialObserver} The node material observer.
  20149. */
  20150. getMonitor() {
  20151. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  20152. }
  20153. /**
  20154. * Returns an array of bind groups of this render object.
  20155. *
  20156. * @return {Array<BindGroup>} The bindings.
  20157. */
  20158. getBindings() {
  20159. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  20160. }
  20161. /**
  20162. * Returns a binding group by group name of this render object.
  20163. *
  20164. * @param {string} name - The name of the binding group.
  20165. * @return {?BindGroup} The bindings.
  20166. */
  20167. getBindingGroup( name ) {
  20168. for ( const bindingGroup of this.getBindings() ) {
  20169. if ( bindingGroup.name === name ) {
  20170. return bindingGroup;
  20171. }
  20172. }
  20173. }
  20174. /**
  20175. * Returns the index of the render object's geometry.
  20176. *
  20177. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20178. */
  20179. getIndex() {
  20180. return this._geometries.getIndex( this );
  20181. }
  20182. /**
  20183. * Returns the indirect buffer attribute.
  20184. *
  20185. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20186. */
  20187. getIndirect() {
  20188. return this._geometries.getIndirect( this );
  20189. }
  20190. /**
  20191. * Returns an array that acts as a key for identifying the render object in a chain map.
  20192. *
  20193. * @return {Array<Object>} An array with object references.
  20194. */
  20195. getChainArray() {
  20196. return [ this.object, this.material, this.context, this.lightsNode ];
  20197. }
  20198. /**
  20199. * This method is used when the geometry of a 3D object has been exchanged and the
  20200. * respective render object now requires an update.
  20201. *
  20202. * @param {BufferGeometry} geometry - The geometry to set.
  20203. */
  20204. setGeometry( geometry ) {
  20205. this.geometry = geometry;
  20206. this.attributes = null;
  20207. this.attributesId = null;
  20208. }
  20209. /**
  20210. * Returns the buffer attributes of the render object. The returned array holds
  20211. * attribute definitions on geometry and node level.
  20212. *
  20213. * @return {Array<BufferAttribute>} An array with buffer attributes.
  20214. */
  20215. getAttributes() {
  20216. if ( this.attributes !== null ) return this.attributes;
  20217. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  20218. const geometry = this.geometry;
  20219. const attributes = [];
  20220. const vertexBuffers = new Set();
  20221. const attributesId = {};
  20222. for ( const nodeAttribute of nodeAttributes ) {
  20223. let attribute;
  20224. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  20225. // node attribute
  20226. attribute = nodeAttribute.node.attribute;
  20227. } else {
  20228. // geometry attribute
  20229. attribute = geometry.getAttribute( nodeAttribute.name );
  20230. attributesId[ nodeAttribute.name ] = attribute.version;
  20231. }
  20232. if ( attribute === undefined ) continue;
  20233. attributes.push( attribute );
  20234. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  20235. vertexBuffers.add( bufferAttribute );
  20236. }
  20237. this.attributes = attributes;
  20238. this.attributesId = attributesId;
  20239. this.vertexBuffers = Array.from( vertexBuffers.values() );
  20240. return attributes;
  20241. }
  20242. /**
  20243. * Returns the vertex buffers of the render object.
  20244. *
  20245. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  20246. */
  20247. getVertexBuffers() {
  20248. if ( this.vertexBuffers === null ) this.getAttributes();
  20249. return this.vertexBuffers;
  20250. }
  20251. /**
  20252. * Returns the draw parameters for the render object.
  20253. *
  20254. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  20255. */
  20256. getDrawParameters() {
  20257. const { object, material, geometry, group, drawRange } = this;
  20258. const drawParams = this.drawParams || ( this.drawParams = {
  20259. vertexCount: 0,
  20260. firstVertex: 0,
  20261. instanceCount: 0,
  20262. firstInstance: 0
  20263. } );
  20264. const index = this.getIndex();
  20265. const hasIndex = ( index !== null );
  20266. let instanceCount = 1;
  20267. if ( geometry.isInstancedBufferGeometry === true ) {
  20268. instanceCount = geometry.instanceCount;
  20269. } else if ( object.count !== undefined ) {
  20270. instanceCount = Math.max( 0, object.count );
  20271. }
  20272. if ( instanceCount === 0 ) return null;
  20273. drawParams.instanceCount = instanceCount;
  20274. if ( object.isBatchedMesh === true ) return drawParams;
  20275. let rangeFactor = 1;
  20276. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  20277. rangeFactor = 2;
  20278. }
  20279. let firstVertex = drawRange.start * rangeFactor;
  20280. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  20281. if ( group !== null ) {
  20282. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  20283. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  20284. }
  20285. const position = geometry.attributes.position;
  20286. let itemCount = Infinity;
  20287. if ( hasIndex ) {
  20288. itemCount = index.count;
  20289. } else if ( position !== undefined && position !== null ) {
  20290. itemCount = position.count;
  20291. }
  20292. firstVertex = Math.max( firstVertex, 0 );
  20293. lastVertex = Math.min( lastVertex, itemCount );
  20294. const count = lastVertex - firstVertex;
  20295. if ( count < 0 || count === Infinity ) return null;
  20296. drawParams.vertexCount = count;
  20297. drawParams.firstVertex = firstVertex;
  20298. return drawParams;
  20299. }
  20300. /**
  20301. * Returns the render object's geometry cache key.
  20302. *
  20303. * The geometry cache key is part of the material cache key.
  20304. *
  20305. * @return {string} The geometry cache key.
  20306. */
  20307. getGeometryCacheKey() {
  20308. const { geometry } = this;
  20309. let cacheKey = '';
  20310. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  20311. const attribute = geometry.attributes[ name ];
  20312. cacheKey += name + ',';
  20313. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  20314. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  20315. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  20316. if ( attribute.normalized ) cacheKey += 'n,';
  20317. }
  20318. // structural equality isn't sufficient for morph targets since the
  20319. // data are maintained in textures. only if the targets are all equal
  20320. // the texture and thus the instance of `MorphNode` can be shared.
  20321. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  20322. const targets = geometry.morphAttributes[ name ];
  20323. cacheKey += 'morph-' + name + ',';
  20324. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  20325. const attribute = targets[ i ];
  20326. cacheKey += attribute.id + ',';
  20327. }
  20328. }
  20329. if ( geometry.index ) {
  20330. cacheKey += 'index,';
  20331. }
  20332. return cacheKey;
  20333. }
  20334. /**
  20335. * Returns the render object's material cache key.
  20336. *
  20337. * The material cache key is part of the render object cache key.
  20338. *
  20339. * @return {number} The material cache key.
  20340. */
  20341. getMaterialCacheKey() {
  20342. const { object, material, renderer } = this;
  20343. let cacheKey = material.customProgramCacheKey();
  20344. for ( const property of getKeys( material ) ) {
  20345. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  20346. const value = material[ property ];
  20347. let valueKey;
  20348. if ( value !== null ) {
  20349. // some material values require a formatting
  20350. const type = typeof value;
  20351. if ( type === 'number' ) {
  20352. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  20353. } else if ( type === 'object' ) {
  20354. valueKey = '{';
  20355. if ( value.isTexture ) {
  20356. valueKey += value.mapping;
  20357. // WebGPU must honor the sampler data because they are part of the bindings
  20358. if ( renderer.backend.isWebGPUBackend === true ) {
  20359. valueKey += value.magFilter;
  20360. valueKey += value.minFilter;
  20361. valueKey += value.wrapS;
  20362. valueKey += value.wrapT;
  20363. valueKey += value.wrapR;
  20364. }
  20365. }
  20366. valueKey += '}';
  20367. } else {
  20368. valueKey = String( value );
  20369. }
  20370. } else {
  20371. valueKey = String( value );
  20372. }
  20373. cacheKey += /*property + ':' +*/ valueKey + ',';
  20374. }
  20375. cacheKey += this.clippingContextCacheKey + ',';
  20376. if ( object.geometry ) {
  20377. cacheKey += this.getGeometryCacheKey();
  20378. }
  20379. if ( object.skeleton ) {
  20380. cacheKey += object.skeleton.bones.length + ',';
  20381. }
  20382. if ( object.isBatchedMesh ) {
  20383. cacheKey += object._matricesTexture.uuid + ',';
  20384. if ( object._colorsTexture !== null ) {
  20385. cacheKey += object._colorsTexture.uuid + ',';
  20386. }
  20387. }
  20388. if ( object.isInstancedMesh || object.count > 1 || Array.isArray( object.morphTargetInfluences ) ) {
  20389. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  20390. cacheKey += object.uuid + ',';
  20391. }
  20392. cacheKey += object.receiveShadow + ',';
  20393. return hashString( cacheKey );
  20394. }
  20395. /**
  20396. * Whether the geometry requires an update or not.
  20397. *
  20398. * @type {boolean}
  20399. * @readonly
  20400. */
  20401. get needsGeometryUpdate() {
  20402. if ( this.geometry.id !== this.object.geometry.id ) return true;
  20403. if ( this.attributes !== null ) {
  20404. const attributesId = this.attributesId;
  20405. for ( const name in attributesId ) {
  20406. const attribute = this.geometry.getAttribute( name );
  20407. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  20408. return true;
  20409. }
  20410. }
  20411. }
  20412. return false;
  20413. }
  20414. /**
  20415. * Whether the render object requires an update or not.
  20416. *
  20417. * Note: There are two distinct places where render objects are checked for an update.
  20418. *
  20419. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  20420. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  20421. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  20422. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  20423. * a need for a refresh due to material, geometry or object related value changes.
  20424. *
  20425. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  20426. * that performs the 'needsUpdate' check.
  20427. *
  20428. * @type {boolean}
  20429. * @readonly
  20430. */
  20431. get needsUpdate() {
  20432. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  20433. }
  20434. /**
  20435. * Returns the dynamic cache key which represents a key that is computed per draw command.
  20436. *
  20437. * @return {number} The cache key.
  20438. */
  20439. getDynamicCacheKey() {
  20440. let cacheKey = 0;
  20441. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  20442. // the renderer is inside a shadow pass.
  20443. if ( this.material.isShadowPassMaterial !== true ) {
  20444. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  20445. }
  20446. if ( this.camera.isArrayCamera ) {
  20447. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  20448. }
  20449. if ( this.object.receiveShadow ) {
  20450. cacheKey = hash$1( cacheKey, 1 );
  20451. }
  20452. cacheKey = hash$1( cacheKey, this.camera.id );
  20453. return cacheKey;
  20454. }
  20455. /**
  20456. * Returns the render object's cache key.
  20457. *
  20458. * @return {number} The cache key.
  20459. */
  20460. getCacheKey() {
  20461. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  20462. }
  20463. /**
  20464. * Frees internal resources.
  20465. */
  20466. dispose() {
  20467. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  20468. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  20469. this.onDispose();
  20470. }
  20471. }
  20472. const _chainKeys$5 = [];
  20473. /**
  20474. * This module manages the render objects of the renderer.
  20475. *
  20476. * @private
  20477. */
  20478. class RenderObjects {
  20479. /**
  20480. * Constructs a new render object management component.
  20481. *
  20482. * @param {Renderer} renderer - The renderer.
  20483. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20484. * @param {Geometries} geometries - Renderer component for managing geometries.
  20485. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  20486. * @param {Bindings} bindings - Renderer component for managing bindings.
  20487. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20488. */
  20489. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  20490. /**
  20491. * The renderer.
  20492. *
  20493. * @type {Renderer}
  20494. */
  20495. this.renderer = renderer;
  20496. /**
  20497. * Renderer component for managing nodes related logic.
  20498. *
  20499. * @type {Nodes}
  20500. */
  20501. this.nodes = nodes;
  20502. /**
  20503. * Renderer component for managing geometries.
  20504. *
  20505. * @type {Geometries}
  20506. */
  20507. this.geometries = geometries;
  20508. /**
  20509. * Renderer component for managing pipelines.
  20510. *
  20511. * @type {Pipelines}
  20512. */
  20513. this.pipelines = pipelines;
  20514. /**
  20515. * Renderer component for managing bindings.
  20516. *
  20517. * @type {Bindings}
  20518. */
  20519. this.bindings = bindings;
  20520. /**
  20521. * Renderer component for managing metrics and monitoring data.
  20522. *
  20523. * @type {Info}
  20524. */
  20525. this.info = info;
  20526. /**
  20527. * A dictionary that manages render contexts in chain maps
  20528. * for each pass ID.
  20529. *
  20530. * @type {Object<string,ChainMap>}
  20531. */
  20532. this.chainMaps = {};
  20533. }
  20534. /**
  20535. * Returns a render object for the given object and state data.
  20536. *
  20537. * @param {Object3D} object - The 3D object.
  20538. * @param {Material} material - The 3D object's material.
  20539. * @param {Scene} scene - The scene the 3D object belongs to.
  20540. * @param {Camera} camera - The camera the 3D object should be rendered with.
  20541. * @param {LightsNode} lightsNode - The lights node.
  20542. * @param {RenderContext} renderContext - The render context.
  20543. * @param {ClippingContext} clippingContext - The clipping context.
  20544. * @param {string} [passId] - An optional ID for identifying the pass.
  20545. * @return {RenderObject} The render object.
  20546. */
  20547. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  20548. const chainMap = this.getChainMap( passId );
  20549. // reuse chainArray
  20550. _chainKeys$5[ 0 ] = object;
  20551. _chainKeys$5[ 1 ] = material;
  20552. _chainKeys$5[ 2 ] = renderContext;
  20553. _chainKeys$5[ 3 ] = lightsNode;
  20554. let renderObject = chainMap.get( _chainKeys$5 );
  20555. if ( renderObject === undefined ) {
  20556. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20557. chainMap.set( _chainKeys$5, renderObject );
  20558. } else {
  20559. renderObject.updateClipping( clippingContext );
  20560. if ( renderObject.needsGeometryUpdate ) {
  20561. renderObject.setGeometry( object.geometry );
  20562. }
  20563. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  20564. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  20565. renderObject.dispose();
  20566. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20567. } else {
  20568. renderObject.version = material.version;
  20569. }
  20570. }
  20571. }
  20572. _chainKeys$5.length = 0;
  20573. return renderObject;
  20574. }
  20575. /**
  20576. * Returns a chain map for the given pass ID.
  20577. *
  20578. * @param {string} [passId='default'] - The pass ID.
  20579. * @return {ChainMap} The chain map.
  20580. */
  20581. getChainMap( passId = 'default' ) {
  20582. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  20583. }
  20584. /**
  20585. * Frees internal resources.
  20586. */
  20587. dispose() {
  20588. this.chainMaps = {};
  20589. }
  20590. /**
  20591. * Factory method for creating render objects with the given list of parameters.
  20592. *
  20593. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20594. * @param {Geometries} geometries - Renderer component for managing geometries.
  20595. * @param {Renderer} renderer - The renderer.
  20596. * @param {Object3D} object - The 3D object.
  20597. * @param {Material} material - The object's material.
  20598. * @param {Scene} scene - The scene the 3D object belongs to.
  20599. * @param {Camera} camera - The camera the object should be rendered with.
  20600. * @param {LightsNode} lightsNode - The lights node.
  20601. * @param {RenderContext} renderContext - The render context.
  20602. * @param {ClippingContext} clippingContext - The clipping context.
  20603. * @param {string} [passId] - An optional ID for identifying the pass.
  20604. * @return {RenderObject} The render object.
  20605. */
  20606. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  20607. const chainMap = this.getChainMap( passId );
  20608. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  20609. renderObject.onDispose = () => {
  20610. this.pipelines.delete( renderObject );
  20611. this.bindings.deleteForRender( renderObject );
  20612. this.nodes.delete( renderObject );
  20613. chainMap.delete( renderObject.getChainArray() );
  20614. };
  20615. return renderObject;
  20616. }
  20617. }
  20618. /**
  20619. * Data structure for the renderer. It is intended to manage
  20620. * data of objects in dictionaries.
  20621. *
  20622. * @private
  20623. */
  20624. class DataMap {
  20625. /**
  20626. * Constructs a new data map.
  20627. */
  20628. constructor() {
  20629. /**
  20630. * `DataMap` internally uses a weak map
  20631. * to manage its data.
  20632. *
  20633. * @type {WeakMap<Object, Object>}
  20634. */
  20635. this.data = new WeakMap();
  20636. }
  20637. /**
  20638. * Returns the dictionary for the given object.
  20639. *
  20640. * @param {Object} object - The object.
  20641. * @return {Object} The dictionary.
  20642. */
  20643. get( object ) {
  20644. let map = this.data.get( object );
  20645. if ( map === undefined ) {
  20646. map = {};
  20647. this.data.set( object, map );
  20648. }
  20649. return map;
  20650. }
  20651. /**
  20652. * Deletes the dictionary for the given object.
  20653. *
  20654. * @param {Object} object - The object.
  20655. * @return {?Object} The deleted dictionary.
  20656. */
  20657. delete( object ) {
  20658. let map = null;
  20659. if ( this.data.has( object ) ) {
  20660. map = this.data.get( object );
  20661. this.data.delete( object );
  20662. }
  20663. return map;
  20664. }
  20665. /**
  20666. * Returns `true` if the given object has a dictionary defined.
  20667. *
  20668. * @param {Object} object - The object to test.
  20669. * @return {boolean} Whether a dictionary is defined or not.
  20670. */
  20671. has( object ) {
  20672. return this.data.has( object );
  20673. }
  20674. /**
  20675. * Frees internal resources.
  20676. */
  20677. dispose() {
  20678. this.data = new WeakMap();
  20679. }
  20680. }
  20681. const AttributeType = {
  20682. VERTEX: 1,
  20683. INDEX: 2,
  20684. STORAGE: 3,
  20685. INDIRECT: 4
  20686. };
  20687. // size of a chunk in bytes (STD140 layout)
  20688. const GPU_CHUNK_BYTES = 16;
  20689. // @TODO: Move to src/constants.js
  20690. const BlendColorFactor = 211;
  20691. const OneMinusBlendColorFactor = 212;
  20692. /**
  20693. * This renderer module manages geometry attributes.
  20694. *
  20695. * @private
  20696. * @augments DataMap
  20697. */
  20698. class Attributes extends DataMap {
  20699. /**
  20700. * Constructs a new attribute management component.
  20701. *
  20702. * @param {Backend} backend - The renderer's backend.
  20703. */
  20704. constructor( backend ) {
  20705. super();
  20706. /**
  20707. * The renderer's backend.
  20708. *
  20709. * @type {Backend}
  20710. */
  20711. this.backend = backend;
  20712. }
  20713. /**
  20714. * Deletes the data for the given attribute.
  20715. *
  20716. * @param {BufferAttribute} attribute - The attribute.
  20717. * @return {?Object} The deleted attribute data.
  20718. */
  20719. delete( attribute ) {
  20720. const attributeData = super.delete( attribute );
  20721. if ( attributeData !== null ) {
  20722. this.backend.destroyAttribute( attribute );
  20723. }
  20724. return attributeData;
  20725. }
  20726. /**
  20727. * Updates the given attribute. This method creates attribute buffers
  20728. * for new attributes and updates data for existing ones.
  20729. *
  20730. * @param {BufferAttribute} attribute - The attribute to update.
  20731. * @param {number} type - The attribute type.
  20732. */
  20733. update( attribute, type ) {
  20734. const data = this.get( attribute );
  20735. if ( data.version === undefined ) {
  20736. if ( type === AttributeType.VERTEX ) {
  20737. this.backend.createAttribute( attribute );
  20738. } else if ( type === AttributeType.INDEX ) {
  20739. this.backend.createIndexAttribute( attribute );
  20740. } else if ( type === AttributeType.STORAGE ) {
  20741. this.backend.createStorageAttribute( attribute );
  20742. } else if ( type === AttributeType.INDIRECT ) {
  20743. this.backend.createIndirectStorageAttribute( attribute );
  20744. }
  20745. data.version = this._getBufferAttribute( attribute ).version;
  20746. } else {
  20747. const bufferAttribute = this._getBufferAttribute( attribute );
  20748. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  20749. this.backend.updateAttribute( attribute );
  20750. data.version = bufferAttribute.version;
  20751. }
  20752. }
  20753. }
  20754. /**
  20755. * Utility method for handling interleaved buffer attributes correctly.
  20756. * To process them, their `InterleavedBuffer` is returned.
  20757. *
  20758. * @param {BufferAttribute} attribute - The attribute.
  20759. * @return {BufferAttribute|InterleavedBuffer}
  20760. */
  20761. _getBufferAttribute( attribute ) {
  20762. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  20763. return attribute;
  20764. }
  20765. }
  20766. /**
  20767. * Returns the wireframe version for the given geometry.
  20768. *
  20769. * @private
  20770. * @function
  20771. * @param {BufferGeometry} geometry - The geometry.
  20772. * @return {number} The version.
  20773. */
  20774. function getWireframeVersion( geometry ) {
  20775. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  20776. }
  20777. /**
  20778. * Returns a wireframe index attribute for the given geometry.
  20779. *
  20780. * @private
  20781. * @function
  20782. * @param {BufferGeometry} geometry - The geometry.
  20783. * @return {BufferAttribute} The wireframe index attribute.
  20784. */
  20785. function getWireframeIndex( geometry ) {
  20786. const indices = [];
  20787. const geometryIndex = geometry.index;
  20788. const geometryPosition = geometry.attributes.position;
  20789. if ( geometryIndex !== null ) {
  20790. const array = geometryIndex.array;
  20791. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  20792. const a = array[ i + 0 ];
  20793. const b = array[ i + 1 ];
  20794. const c = array[ i + 2 ];
  20795. indices.push( a, b, b, c, c, a );
  20796. }
  20797. } else {
  20798. const array = geometryPosition.array;
  20799. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  20800. const a = i + 0;
  20801. const b = i + 1;
  20802. const c = i + 2;
  20803. indices.push( a, b, b, c, c, a );
  20804. }
  20805. }
  20806. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  20807. attribute.version = getWireframeVersion( geometry );
  20808. return attribute;
  20809. }
  20810. /**
  20811. * This renderer module manages geometries.
  20812. *
  20813. * @private
  20814. * @augments DataMap
  20815. */
  20816. class Geometries extends DataMap {
  20817. /**
  20818. * Constructs a new geometry management component.
  20819. *
  20820. * @param {Attributes} attributes - Renderer component for managing attributes.
  20821. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20822. */
  20823. constructor( attributes, info ) {
  20824. super();
  20825. /**
  20826. * Renderer component for managing attributes.
  20827. *
  20828. * @type {Attributes}
  20829. */
  20830. this.attributes = attributes;
  20831. /**
  20832. * Renderer component for managing metrics and monitoring data.
  20833. *
  20834. * @type {Info}
  20835. */
  20836. this.info = info;
  20837. /**
  20838. * Weak Map for managing attributes for wireframe rendering.
  20839. *
  20840. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  20841. */
  20842. this.wireframes = new WeakMap();
  20843. /**
  20844. * This Weak Map is used to make sure buffer attributes are
  20845. * updated only once per render call.
  20846. *
  20847. * @type {WeakMap<BufferAttribute,number>}
  20848. */
  20849. this.attributeCall = new WeakMap();
  20850. /**
  20851. * Stores the event listeners attached to geometries.
  20852. *
  20853. * @private
  20854. * @type {Map<BufferGeometry,Function>}
  20855. */
  20856. this._geometryDisposeListeners = new Map();
  20857. }
  20858. /**
  20859. * Returns `true` if the given render object has an initialized geometry.
  20860. *
  20861. * @param {RenderObject} renderObject - The render object.
  20862. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  20863. */
  20864. has( renderObject ) {
  20865. const geometry = renderObject.geometry;
  20866. return super.has( geometry ) && this.get( geometry ).initialized === true;
  20867. }
  20868. /**
  20869. * Prepares the geometry of the given render object for rendering.
  20870. *
  20871. * @param {RenderObject} renderObject - The render object.
  20872. */
  20873. updateForRender( renderObject ) {
  20874. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  20875. this.updateAttributes( renderObject );
  20876. }
  20877. /**
  20878. * Initializes the geometry of the given render object.
  20879. *
  20880. * @param {RenderObject} renderObject - The render object.
  20881. */
  20882. initGeometry( renderObject ) {
  20883. const geometry = renderObject.geometry;
  20884. const geometryData = this.get( geometry );
  20885. geometryData.initialized = true;
  20886. this.info.memory.geometries ++;
  20887. const onDispose = () => {
  20888. this.info.memory.geometries --;
  20889. const index = geometry.index;
  20890. const geometryAttributes = renderObject.getAttributes();
  20891. if ( index !== null ) {
  20892. this.attributes.delete( index );
  20893. }
  20894. for ( const geometryAttribute of geometryAttributes ) {
  20895. this.attributes.delete( geometryAttribute );
  20896. }
  20897. const wireframeAttribute = this.wireframes.get( geometry );
  20898. if ( wireframeAttribute !== undefined ) {
  20899. this.attributes.delete( wireframeAttribute );
  20900. }
  20901. geometry.removeEventListener( 'dispose', onDispose );
  20902. this._geometryDisposeListeners.delete( geometry );
  20903. };
  20904. geometry.addEventListener( 'dispose', onDispose );
  20905. // see #31798 why tracking separate remove listeners is required right now
  20906. // TODO: Re-evaluate how onDispose() is managed in this component
  20907. this._geometryDisposeListeners.set( geometry, onDispose );
  20908. }
  20909. /**
  20910. * Updates the geometry attributes of the given render object.
  20911. *
  20912. * @param {RenderObject} renderObject - The render object.
  20913. */
  20914. updateAttributes( renderObject ) {
  20915. // attributes
  20916. const attributes = renderObject.getAttributes();
  20917. for ( const attribute of attributes ) {
  20918. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  20919. this.updateAttribute( attribute, AttributeType.STORAGE );
  20920. } else {
  20921. this.updateAttribute( attribute, AttributeType.VERTEX );
  20922. }
  20923. }
  20924. // indexes
  20925. const index = this.getIndex( renderObject );
  20926. if ( index !== null ) {
  20927. this.updateAttribute( index, AttributeType.INDEX );
  20928. }
  20929. // indirect
  20930. const indirect = renderObject.geometry.indirect;
  20931. if ( indirect !== null ) {
  20932. this.updateAttribute( indirect, AttributeType.INDIRECT );
  20933. }
  20934. }
  20935. /**
  20936. * Updates the given attribute.
  20937. *
  20938. * @param {BufferAttribute} attribute - The attribute to update.
  20939. * @param {number} type - The attribute type.
  20940. */
  20941. updateAttribute( attribute, type ) {
  20942. const callId = this.info.render.calls;
  20943. if ( ! attribute.isInterleavedBufferAttribute ) {
  20944. if ( this.attributeCall.get( attribute ) !== callId ) {
  20945. this.attributes.update( attribute, type );
  20946. this.attributeCall.set( attribute, callId );
  20947. }
  20948. } else {
  20949. if ( this.attributeCall.get( attribute ) === undefined ) {
  20950. this.attributes.update( attribute, type );
  20951. this.attributeCall.set( attribute, callId );
  20952. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  20953. this.attributes.update( attribute, type );
  20954. this.attributeCall.set( attribute.data, callId );
  20955. this.attributeCall.set( attribute, callId );
  20956. }
  20957. }
  20958. }
  20959. /**
  20960. * Returns the indirect buffer attribute of the given render object.
  20961. *
  20962. * @param {RenderObject} renderObject - The render object.
  20963. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20964. */
  20965. getIndirect( renderObject ) {
  20966. return renderObject.geometry.indirect;
  20967. }
  20968. /**
  20969. * Returns the index of the given render object's geometry. This is implemented
  20970. * in a method to return a wireframe index if necessary.
  20971. *
  20972. * @param {RenderObject} renderObject - The render object.
  20973. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20974. */
  20975. getIndex( renderObject ) {
  20976. const { geometry, material } = renderObject;
  20977. let index = geometry.index;
  20978. if ( material.wireframe === true ) {
  20979. const wireframes = this.wireframes;
  20980. let wireframeAttribute = wireframes.get( geometry );
  20981. if ( wireframeAttribute === undefined ) {
  20982. wireframeAttribute = getWireframeIndex( geometry );
  20983. wireframes.set( geometry, wireframeAttribute );
  20984. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  20985. this.attributes.delete( wireframeAttribute );
  20986. wireframeAttribute = getWireframeIndex( geometry );
  20987. wireframes.set( geometry, wireframeAttribute );
  20988. }
  20989. index = wireframeAttribute;
  20990. }
  20991. return index;
  20992. }
  20993. dispose() {
  20994. for ( const [ geometry, onDispose ] of this._geometryDisposeListeners.entries() ) {
  20995. geometry.removeEventListener( 'dispose', onDispose );
  20996. }
  20997. this._geometryDisposeListeners.clear();
  20998. }
  20999. }
  21000. /**
  21001. * This renderer module provides a series of statistical information
  21002. * about the GPU memory and the rendering process. Useful for debugging
  21003. * and monitoring.
  21004. */
  21005. class Info {
  21006. /**
  21007. * Constructs a new info component.
  21008. */
  21009. constructor() {
  21010. /**
  21011. * Whether frame related metrics should automatically
  21012. * be resetted or not. This property should be set to `false`
  21013. * by apps which manage their own animation loop. They must
  21014. * then call `renderer.info.reset()` once per frame manually.
  21015. *
  21016. * @type {boolean}
  21017. * @default true
  21018. */
  21019. this.autoReset = true;
  21020. /**
  21021. * The current frame ID. This ID is managed
  21022. * by `NodeFrame`.
  21023. *
  21024. * @type {number}
  21025. * @readonly
  21026. * @default 0
  21027. */
  21028. this.frame = 0;
  21029. /**
  21030. * The number of render calls since the
  21031. * app has been started.
  21032. *
  21033. * @type {number}
  21034. * @readonly
  21035. * @default 0
  21036. */
  21037. this.calls = 0;
  21038. /**
  21039. * Render related metrics.
  21040. *
  21041. * @type {Object}
  21042. * @readonly
  21043. * @property {number} calls - The number of render calls since the app has been started.
  21044. * @property {number} frameCalls - The number of render calls of the current frame.
  21045. * @property {number} drawCalls - The number of draw calls of the current frame.
  21046. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  21047. * @property {number} points - The number of rendered point primitives of the current frame.
  21048. * @property {number} lines - The number of rendered line primitives of the current frame.
  21049. * @property {number} timestamp - The timestamp of the frame.
  21050. */
  21051. this.render = {
  21052. calls: 0,
  21053. frameCalls: 0,
  21054. drawCalls: 0,
  21055. triangles: 0,
  21056. points: 0,
  21057. lines: 0,
  21058. timestamp: 0,
  21059. };
  21060. /**
  21061. * Compute related metrics.
  21062. *
  21063. * @type {Object}
  21064. * @readonly
  21065. * @property {number} calls - The number of compute calls since the app has been started.
  21066. * @property {number} frameCalls - The number of compute calls of the current frame.
  21067. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  21068. */
  21069. this.compute = {
  21070. calls: 0,
  21071. frameCalls: 0,
  21072. timestamp: 0
  21073. };
  21074. /**
  21075. * Memory related metrics.
  21076. *
  21077. * @type {Object}
  21078. * @readonly
  21079. * @property {number} geometries - The number of active geometries.
  21080. * @property {number} frameCalls - The number of active textures.
  21081. */
  21082. this.memory = {
  21083. geometries: 0,
  21084. textures: 0
  21085. };
  21086. }
  21087. /**
  21088. * This method should be executed per draw call and updates the corresponding metrics.
  21089. *
  21090. * @param {Object3D} object - The 3D object that is going to be rendered.
  21091. * @param {number} count - The vertex or index count.
  21092. * @param {number} instanceCount - The instance count.
  21093. */
  21094. update( object, count, instanceCount ) {
  21095. this.render.drawCalls ++;
  21096. if ( object.isMesh || object.isSprite ) {
  21097. this.render.triangles += instanceCount * ( count / 3 );
  21098. } else if ( object.isPoints ) {
  21099. this.render.points += instanceCount * count;
  21100. } else if ( object.isLineSegments ) {
  21101. this.render.lines += instanceCount * ( count / 2 );
  21102. } else if ( object.isLine ) {
  21103. this.render.lines += instanceCount * ( count - 1 );
  21104. } else {
  21105. error( 'WebGPUInfo: Unknown object type.' );
  21106. }
  21107. }
  21108. /**
  21109. * Resets frame related metrics.
  21110. */
  21111. reset() {
  21112. this.render.drawCalls = 0;
  21113. this.render.frameCalls = 0;
  21114. this.compute.frameCalls = 0;
  21115. this.render.triangles = 0;
  21116. this.render.points = 0;
  21117. this.render.lines = 0;
  21118. }
  21119. /**
  21120. * Performs a complete reset of the object.
  21121. */
  21122. dispose() {
  21123. this.reset();
  21124. this.calls = 0;
  21125. this.render.calls = 0;
  21126. this.compute.calls = 0;
  21127. this.render.timestamp = 0;
  21128. this.compute.timestamp = 0;
  21129. this.memory.geometries = 0;
  21130. this.memory.textures = 0;
  21131. }
  21132. }
  21133. /**
  21134. * Abstract class for representing pipelines.
  21135. *
  21136. * @private
  21137. * @abstract
  21138. */
  21139. class Pipeline {
  21140. /**
  21141. * Constructs a new pipeline.
  21142. *
  21143. * @param {string} cacheKey - The pipeline's cache key.
  21144. */
  21145. constructor( cacheKey ) {
  21146. /**
  21147. * The pipeline's cache key.
  21148. *
  21149. * @type {string}
  21150. */
  21151. this.cacheKey = cacheKey;
  21152. /**
  21153. * How often the pipeline is currently in use.
  21154. *
  21155. * @type {number}
  21156. * @default 0
  21157. */
  21158. this.usedTimes = 0;
  21159. }
  21160. }
  21161. /**
  21162. * Class for representing render pipelines.
  21163. *
  21164. * @private
  21165. * @augments Pipeline
  21166. */
  21167. class RenderPipeline extends Pipeline {
  21168. /**
  21169. * Constructs a new render pipeline.
  21170. *
  21171. * @param {string} cacheKey - The pipeline's cache key.
  21172. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  21173. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  21174. */
  21175. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  21176. super( cacheKey );
  21177. /**
  21178. * The pipeline's vertex shader.
  21179. *
  21180. * @type {ProgrammableStage}
  21181. */
  21182. this.vertexProgram = vertexProgram;
  21183. /**
  21184. * The pipeline's fragment shader.
  21185. *
  21186. * @type {ProgrammableStage}
  21187. */
  21188. this.fragmentProgram = fragmentProgram;
  21189. }
  21190. }
  21191. /**
  21192. * Class for representing compute pipelines.
  21193. *
  21194. * @private
  21195. * @augments Pipeline
  21196. */
  21197. class ComputePipeline extends Pipeline {
  21198. /**
  21199. * Constructs a new render pipeline.
  21200. *
  21201. * @param {string} cacheKey - The pipeline's cache key.
  21202. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  21203. */
  21204. constructor( cacheKey, computeProgram ) {
  21205. super( cacheKey );
  21206. /**
  21207. * The pipeline's compute shader.
  21208. *
  21209. * @type {ProgrammableStage}
  21210. */
  21211. this.computeProgram = computeProgram;
  21212. /**
  21213. * This flag can be used for type testing.
  21214. *
  21215. * @type {boolean}
  21216. * @readonly
  21217. * @default true
  21218. */
  21219. this.isComputePipeline = true;
  21220. }
  21221. }
  21222. let _id$9 = 0;
  21223. /**
  21224. * Class for representing programmable stages which are vertex,
  21225. * fragment or compute shaders. Unlike fixed-function states (like blending),
  21226. * they represent the programmable part of a pipeline.
  21227. *
  21228. * @private
  21229. */
  21230. class ProgrammableStage {
  21231. /**
  21232. * Constructs a new programmable stage.
  21233. *
  21234. * @param {string} code - The shader code.
  21235. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  21236. * @param {string} name - The name of the shader.
  21237. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21238. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21239. */
  21240. constructor( code, stage, name, transforms = null, attributes = null ) {
  21241. /**
  21242. * The id of the programmable stage.
  21243. *
  21244. * @type {number}
  21245. */
  21246. this.id = _id$9 ++;
  21247. /**
  21248. * The shader code.
  21249. *
  21250. * @type {string}
  21251. */
  21252. this.code = code;
  21253. /**
  21254. * The type of stage.
  21255. *
  21256. * @type {string}
  21257. */
  21258. this.stage = stage;
  21259. /**
  21260. * The name of the stage.
  21261. * This is used for debugging purposes.
  21262. *
  21263. * @type {string}
  21264. */
  21265. this.name = name;
  21266. /**
  21267. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21268. *
  21269. * @type {?Array<Object>}
  21270. */
  21271. this.transforms = transforms;
  21272. /**
  21273. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21274. *
  21275. * @type {?Array<Object>}
  21276. */
  21277. this.attributes = attributes;
  21278. /**
  21279. * How often the programmable stage is currently in use.
  21280. *
  21281. * @type {number}
  21282. * @default 0
  21283. */
  21284. this.usedTimes = 0;
  21285. }
  21286. }
  21287. /**
  21288. * This renderer module manages the pipelines of the renderer.
  21289. *
  21290. * @private
  21291. * @augments DataMap
  21292. */
  21293. class Pipelines extends DataMap {
  21294. /**
  21295. * Constructs a new pipeline management component.
  21296. *
  21297. * @param {Backend} backend - The renderer's backend.
  21298. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21299. */
  21300. constructor( backend, nodes ) {
  21301. super();
  21302. /**
  21303. * The renderer's backend.
  21304. *
  21305. * @type {Backend}
  21306. */
  21307. this.backend = backend;
  21308. /**
  21309. * Renderer component for managing nodes related logic.
  21310. *
  21311. * @type {Nodes}
  21312. */
  21313. this.nodes = nodes;
  21314. /**
  21315. * A references to the bindings management component.
  21316. * This reference will be set inside the `Bindings`
  21317. * constructor.
  21318. *
  21319. * @type {?Bindings}
  21320. * @default null
  21321. */
  21322. this.bindings = null;
  21323. /**
  21324. * Internal cache for maintaining pipelines.
  21325. * The key of the map is a cache key, the value the pipeline.
  21326. *
  21327. * @type {Map<string,Pipeline>}
  21328. */
  21329. this.caches = new Map();
  21330. /**
  21331. * This dictionary maintains for each shader stage type (vertex,
  21332. * fragment and compute) the programmable stage objects which
  21333. * represent the actual shader code.
  21334. *
  21335. * @type {Object<string,Map<string, ProgrammableStage>>}
  21336. */
  21337. this.programs = {
  21338. vertex: new Map(),
  21339. fragment: new Map(),
  21340. compute: new Map()
  21341. };
  21342. }
  21343. /**
  21344. * Returns a compute pipeline for the given compute node.
  21345. *
  21346. * @param {Node} computeNode - The compute node.
  21347. * @param {Array<BindGroup>} bindings - The bindings.
  21348. * @return {ComputePipeline} The compute pipeline.
  21349. */
  21350. getForCompute( computeNode, bindings ) {
  21351. const { backend } = this;
  21352. const data = this.get( computeNode );
  21353. if ( this._needsComputeUpdate( computeNode ) ) {
  21354. const previousPipeline = data.pipeline;
  21355. if ( previousPipeline ) {
  21356. previousPipeline.usedTimes --;
  21357. previousPipeline.computeProgram.usedTimes --;
  21358. }
  21359. // get shader
  21360. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  21361. // programmable stage
  21362. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  21363. if ( stageCompute === undefined ) {
  21364. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  21365. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  21366. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  21367. backend.createProgram( stageCompute );
  21368. }
  21369. // determine compute pipeline
  21370. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  21371. let pipeline = this.caches.get( cacheKey );
  21372. if ( pipeline === undefined ) {
  21373. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21374. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  21375. }
  21376. // keep track of all used times
  21377. pipeline.usedTimes ++;
  21378. stageCompute.usedTimes ++;
  21379. //
  21380. data.version = computeNode.version;
  21381. data.pipeline = pipeline;
  21382. }
  21383. return data.pipeline;
  21384. }
  21385. /**
  21386. * Returns a render pipeline for the given render object.
  21387. *
  21388. * @param {RenderObject} renderObject - The render object.
  21389. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21390. * @return {RenderPipeline} The render pipeline.
  21391. */
  21392. getForRender( renderObject, promises = null ) {
  21393. const { backend } = this;
  21394. const data = this.get( renderObject );
  21395. if ( this._needsRenderUpdate( renderObject ) ) {
  21396. const previousPipeline = data.pipeline;
  21397. if ( previousPipeline ) {
  21398. previousPipeline.usedTimes --;
  21399. previousPipeline.vertexProgram.usedTimes --;
  21400. previousPipeline.fragmentProgram.usedTimes --;
  21401. }
  21402. // get shader
  21403. const nodeBuilderState = renderObject.getNodeBuilderState();
  21404. const name = renderObject.material ? renderObject.material.name : '';
  21405. // programmable stages
  21406. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  21407. if ( stageVertex === undefined ) {
  21408. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  21409. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  21410. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  21411. backend.createProgram( stageVertex );
  21412. }
  21413. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  21414. if ( stageFragment === undefined ) {
  21415. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  21416. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  21417. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  21418. backend.createProgram( stageFragment );
  21419. }
  21420. // determine render pipeline
  21421. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21422. let pipeline = this.caches.get( cacheKey );
  21423. if ( pipeline === undefined ) {
  21424. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21425. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  21426. } else {
  21427. renderObject.pipeline = pipeline;
  21428. }
  21429. // keep track of all used times
  21430. pipeline.usedTimes ++;
  21431. stageVertex.usedTimes ++;
  21432. stageFragment.usedTimes ++;
  21433. //
  21434. data.pipeline = pipeline;
  21435. }
  21436. return data.pipeline;
  21437. }
  21438. /**
  21439. * Deletes the pipeline for the given render object.
  21440. *
  21441. * @param {RenderObject} object - The render object.
  21442. * @return {?Object} The deleted dictionary.
  21443. */
  21444. delete( object ) {
  21445. const pipeline = this.get( object ).pipeline;
  21446. if ( pipeline ) {
  21447. // pipeline
  21448. pipeline.usedTimes --;
  21449. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  21450. // programs
  21451. if ( pipeline.isComputePipeline ) {
  21452. pipeline.computeProgram.usedTimes --;
  21453. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  21454. } else {
  21455. pipeline.fragmentProgram.usedTimes --;
  21456. pipeline.vertexProgram.usedTimes --;
  21457. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  21458. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  21459. }
  21460. }
  21461. return super.delete( object );
  21462. }
  21463. /**
  21464. * Frees internal resources.
  21465. */
  21466. dispose() {
  21467. super.dispose();
  21468. this.caches = new Map();
  21469. this.programs = {
  21470. vertex: new Map(),
  21471. fragment: new Map(),
  21472. compute: new Map()
  21473. };
  21474. }
  21475. /**
  21476. * Updates the pipeline for the given render object.
  21477. *
  21478. * @param {RenderObject} renderObject - The render object.
  21479. */
  21480. updateForRender( renderObject ) {
  21481. this.getForRender( renderObject );
  21482. }
  21483. /**
  21484. * Returns a compute pipeline for the given parameters.
  21485. *
  21486. * @private
  21487. * @param {Node} computeNode - The compute node.
  21488. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21489. * @param {string} cacheKey - The cache key.
  21490. * @param {Array<BindGroup>} bindings - The bindings.
  21491. * @return {ComputePipeline} The compute pipeline.
  21492. */
  21493. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  21494. // check for existing pipeline
  21495. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  21496. let pipeline = this.caches.get( cacheKey );
  21497. if ( pipeline === undefined ) {
  21498. pipeline = new ComputePipeline( cacheKey, stageCompute );
  21499. this.caches.set( cacheKey, pipeline );
  21500. this.backend.createComputePipeline( pipeline, bindings );
  21501. }
  21502. return pipeline;
  21503. }
  21504. /**
  21505. * Returns a render pipeline for the given parameters.
  21506. *
  21507. * @private
  21508. * @param {RenderObject} renderObject - The render object.
  21509. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21510. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21511. * @param {string} cacheKey - The cache key.
  21512. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21513. * @return {ComputePipeline} The compute pipeline.
  21514. */
  21515. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  21516. // check for existing pipeline
  21517. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21518. let pipeline = this.caches.get( cacheKey );
  21519. if ( pipeline === undefined ) {
  21520. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  21521. this.caches.set( cacheKey, pipeline );
  21522. renderObject.pipeline = pipeline;
  21523. // The `promises` array is `null` by default and only set to an empty array when
  21524. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  21525. // pending promises that resolve when the render pipelines are ready for rendering.
  21526. this.backend.createRenderPipeline( renderObject, promises );
  21527. }
  21528. return pipeline;
  21529. }
  21530. /**
  21531. * Computes a cache key representing a compute pipeline.
  21532. *
  21533. * @private
  21534. * @param {Node} computeNode - The compute node.
  21535. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21536. * @return {string} The cache key.
  21537. */
  21538. _getComputeCacheKey( computeNode, stageCompute ) {
  21539. return computeNode.id + ',' + stageCompute.id;
  21540. }
  21541. /**
  21542. * Computes a cache key representing a render pipeline.
  21543. *
  21544. * @private
  21545. * @param {RenderObject} renderObject - The render object.
  21546. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21547. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21548. * @return {string} The cache key.
  21549. */
  21550. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  21551. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  21552. }
  21553. /**
  21554. * Releases the given pipeline.
  21555. *
  21556. * @private
  21557. * @param {Pipeline} pipeline - The pipeline to release.
  21558. */
  21559. _releasePipeline( pipeline ) {
  21560. this.caches.delete( pipeline.cacheKey );
  21561. }
  21562. /**
  21563. * Releases the shader program.
  21564. *
  21565. * @private
  21566. * @param {Object} program - The shader program to release.
  21567. */
  21568. _releaseProgram( program ) {
  21569. const code = program.code;
  21570. const stage = program.stage;
  21571. this.programs[ stage ].delete( code );
  21572. }
  21573. /**
  21574. * Returns `true` if the compute pipeline for the given compute node requires an update.
  21575. *
  21576. * @private
  21577. * @param {Node} computeNode - The compute node.
  21578. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  21579. */
  21580. _needsComputeUpdate( computeNode ) {
  21581. const data = this.get( computeNode );
  21582. return data.pipeline === undefined || data.version !== computeNode.version;
  21583. }
  21584. /**
  21585. * Returns `true` if the render pipeline for the given render object requires an update.
  21586. *
  21587. * @private
  21588. * @param {RenderObject} renderObject - The render object.
  21589. * @return {boolean} Whether the render object for the given render object requires an update or not.
  21590. */
  21591. _needsRenderUpdate( renderObject ) {
  21592. const data = this.get( renderObject );
  21593. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  21594. }
  21595. }
  21596. /**
  21597. * This renderer module manages the bindings of the renderer.
  21598. *
  21599. * @private
  21600. * @augments DataMap
  21601. */
  21602. class Bindings extends DataMap {
  21603. /**
  21604. * Constructs a new bindings management component.
  21605. *
  21606. * @param {Backend} backend - The renderer's backend.
  21607. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21608. * @param {Textures} textures - Renderer component for managing textures.
  21609. * @param {Attributes} attributes - Renderer component for managing attributes.
  21610. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  21611. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21612. */
  21613. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  21614. super();
  21615. /**
  21616. * The renderer's backend.
  21617. *
  21618. * @type {Backend}
  21619. */
  21620. this.backend = backend;
  21621. /**
  21622. * Renderer component for managing textures.
  21623. *
  21624. * @type {Textures}
  21625. */
  21626. this.textures = textures;
  21627. /**
  21628. * Renderer component for managing pipelines.
  21629. *
  21630. * @type {Pipelines}
  21631. */
  21632. this.pipelines = pipelines;
  21633. /**
  21634. * Renderer component for managing attributes.
  21635. *
  21636. * @type {Attributes}
  21637. */
  21638. this.attributes = attributes;
  21639. /**
  21640. * Renderer component for managing nodes related logic.
  21641. *
  21642. * @type {Nodes}
  21643. */
  21644. this.nodes = nodes;
  21645. /**
  21646. * Renderer component for managing metrics and monitoring data.
  21647. *
  21648. * @type {Info}
  21649. */
  21650. this.info = info;
  21651. this.pipelines.bindings = this; // assign bindings to pipelines
  21652. }
  21653. /**
  21654. * Returns the bind groups for the given render object.
  21655. *
  21656. * @param {RenderObject} renderObject - The render object.
  21657. * @return {Array<BindGroup>} The bind groups.
  21658. */
  21659. getForRender( renderObject ) {
  21660. const bindings = renderObject.getBindings();
  21661. for ( const bindGroup of bindings ) {
  21662. const groupData = this.get( bindGroup );
  21663. if ( groupData.bindGroup === undefined ) {
  21664. // each object defines an array of bindings (ubos, textures, samplers etc.)
  21665. this._init( bindGroup );
  21666. this.backend.createBindings( bindGroup, bindings, 0 );
  21667. groupData.bindGroup = bindGroup;
  21668. }
  21669. }
  21670. return bindings;
  21671. }
  21672. /**
  21673. * Returns the bind groups for the given compute node.
  21674. *
  21675. * @param {Node} computeNode - The compute node.
  21676. * @return {Array<BindGroup>} The bind groups.
  21677. */
  21678. getForCompute( computeNode ) {
  21679. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  21680. for ( const bindGroup of bindings ) {
  21681. const groupData = this.get( bindGroup );
  21682. if ( groupData.bindGroup === undefined ) {
  21683. this._init( bindGroup );
  21684. this.backend.createBindings( bindGroup, bindings, 0 );
  21685. groupData.bindGroup = bindGroup;
  21686. }
  21687. }
  21688. return bindings;
  21689. }
  21690. /**
  21691. * Updates the bindings for the given compute node.
  21692. *
  21693. * @param {Node} computeNode - The compute node.
  21694. */
  21695. updateForCompute( computeNode ) {
  21696. this._updateBindings( this.getForCompute( computeNode ) );
  21697. }
  21698. /**
  21699. * Updates the bindings for the given render object.
  21700. *
  21701. * @param {RenderObject} renderObject - The render object.
  21702. */
  21703. updateForRender( renderObject ) {
  21704. this._updateBindings( this.getForRender( renderObject ) );
  21705. }
  21706. /**
  21707. * Deletes the bindings for the given compute node.
  21708. *
  21709. * @param {Node} computeNode - The compute node.
  21710. */
  21711. deleteForCompute( computeNode ) {
  21712. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  21713. for ( const bindGroup of bindings ) {
  21714. this.delete( bindGroup );
  21715. }
  21716. }
  21717. /**
  21718. * Deletes the bindings for the given renderObject node.
  21719. *
  21720. * @param {RenderObject} renderObject - The renderObject.
  21721. */
  21722. deleteForRender( renderObject ) {
  21723. const bindings = renderObject.getBindings();
  21724. for ( const bindGroup of bindings ) {
  21725. this.delete( bindGroup );
  21726. }
  21727. }
  21728. /**
  21729. * Updates the given array of bindings.
  21730. *
  21731. * @param {Array<BindGroup>} bindings - The bind groups.
  21732. */
  21733. _updateBindings( bindings ) {
  21734. for ( const bindGroup of bindings ) {
  21735. this._update( bindGroup, bindings );
  21736. }
  21737. }
  21738. /**
  21739. * Initializes the given bind group.
  21740. *
  21741. * @param {BindGroup} bindGroup - The bind group to initialize.
  21742. */
  21743. _init( bindGroup ) {
  21744. for ( const binding of bindGroup.bindings ) {
  21745. if ( binding.isSampledTexture ) {
  21746. this.textures.updateTexture( binding.texture );
  21747. } else if ( binding.isSampler ) {
  21748. this.textures.updateSampler( binding.texture );
  21749. } else if ( binding.isStorageBuffer ) {
  21750. const attribute = binding.attribute;
  21751. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  21752. this.attributes.update( attribute, attributeType );
  21753. }
  21754. }
  21755. }
  21756. /**
  21757. * Updates the given bind group.
  21758. *
  21759. * @param {BindGroup} bindGroup - The bind group to update.
  21760. * @param {Array<BindGroup>} bindings - The bind groups.
  21761. */
  21762. _update( bindGroup, bindings ) {
  21763. const { backend } = this;
  21764. let needsBindingsUpdate = false;
  21765. let cacheBindings = true;
  21766. let cacheIndex = 0;
  21767. let version = 0;
  21768. // iterate over all bindings and check if buffer updates or a new binding group is required
  21769. for ( const binding of bindGroup.bindings ) {
  21770. if ( binding.isNodeUniformsGroup ) {
  21771. const updated = this.nodes.updateGroup( binding );
  21772. // every uniforms group is a uniform buffer. So if no update is required,
  21773. // we move one with the next binding. Otherwise the next if block will update the group.
  21774. if ( updated === false ) continue;
  21775. }
  21776. if ( binding.isStorageBuffer ) {
  21777. const attribute = binding.attribute;
  21778. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  21779. this.attributes.update( attribute, attributeType );
  21780. }
  21781. if ( binding.isUniformBuffer ) {
  21782. const updated = binding.update();
  21783. if ( updated ) {
  21784. backend.updateBinding( binding );
  21785. }
  21786. } else if ( binding.isSampledTexture ) {
  21787. const updated = binding.update();
  21788. // get the texture data after the update, to sync the texture reference from node
  21789. const texture = binding.texture;
  21790. const texturesTextureData = this.textures.get( texture );
  21791. if ( updated ) {
  21792. // version: update the texture data or create a new one
  21793. this.textures.updateTexture( texture );
  21794. // generation: update the bindings if a new texture has been created
  21795. if ( binding.generation !== texturesTextureData.generation ) {
  21796. binding.generation = texturesTextureData.generation;
  21797. needsBindingsUpdate = true;
  21798. cacheBindings = false;
  21799. }
  21800. }
  21801. const textureData = backend.get( texture );
  21802. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  21803. cacheBindings = false;
  21804. } else {
  21805. cacheIndex = cacheIndex * 10 + texture.id;
  21806. version += texture.version;
  21807. }
  21808. if ( texture.isStorageTexture === true && texture.mipmapsAutoUpdate === true ) {
  21809. const textureData = this.get( texture );
  21810. if ( binding.store === true ) {
  21811. textureData.needsMipmap = true;
  21812. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  21813. this.backend.generateMipmaps( texture );
  21814. textureData.needsMipmap = false;
  21815. }
  21816. }
  21817. } else if ( binding.isSampler ) {
  21818. const updated = binding.update();
  21819. if ( updated ) {
  21820. const samplerKey = this.textures.updateSampler( binding.texture );
  21821. if ( binding.samplerKey !== samplerKey ) {
  21822. binding.samplerKey = samplerKey;
  21823. needsBindingsUpdate = true;
  21824. cacheBindings = false;
  21825. }
  21826. }
  21827. }
  21828. }
  21829. if ( needsBindingsUpdate === true ) {
  21830. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  21831. }
  21832. }
  21833. }
  21834. /**
  21835. * Default sorting function for opaque render items.
  21836. *
  21837. * @private
  21838. * @function
  21839. * @param {Object} a - The first render item.
  21840. * @param {Object} b - The second render item.
  21841. * @return {number} A numeric value which defines the sort order.
  21842. */
  21843. function painterSortStable( a, b ) {
  21844. if ( a.groupOrder !== b.groupOrder ) {
  21845. return a.groupOrder - b.groupOrder;
  21846. } else if ( a.renderOrder !== b.renderOrder ) {
  21847. return a.renderOrder - b.renderOrder;
  21848. } else if ( a.z !== b.z ) {
  21849. return a.z - b.z;
  21850. } else {
  21851. return a.id - b.id;
  21852. }
  21853. }
  21854. /**
  21855. * Default sorting function for transparent render items.
  21856. *
  21857. * @private
  21858. * @function
  21859. * @param {Object} a - The first render item.
  21860. * @param {Object} b - The second render item.
  21861. * @return {number} A numeric value which defines the sort order.
  21862. */
  21863. function reversePainterSortStable( a, b ) {
  21864. if ( a.groupOrder !== b.groupOrder ) {
  21865. return a.groupOrder - b.groupOrder;
  21866. } else if ( a.renderOrder !== b.renderOrder ) {
  21867. return a.renderOrder - b.renderOrder;
  21868. } else if ( a.z !== b.z ) {
  21869. return b.z - a.z;
  21870. } else {
  21871. return a.id - b.id;
  21872. }
  21873. }
  21874. /**
  21875. * Returns `true` if the given transparent material requires a double pass.
  21876. *
  21877. * @private
  21878. * @function
  21879. * @param {Material} material - The transparent material.
  21880. * @return {boolean} Whether the given material requires a double pass or not.
  21881. */
  21882. function needsDoublePass( material ) {
  21883. const hasTransmission = material.transmission > 0 || ( material.transmissionNode && material.transmissionNode.isNode );
  21884. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  21885. }
  21886. /**
  21887. * When the renderer analyzes the scene at the beginning of a render call,
  21888. * it stores 3D object for further processing in render lists. Depending on the
  21889. * properties of a 3D objects (like their transformation or material state), the
  21890. * objects are maintained in ordered lists for the actual rendering.
  21891. *
  21892. * Render lists are unique per scene and camera combination.
  21893. *
  21894. * @private
  21895. * @augments Pipeline
  21896. */
  21897. class RenderList {
  21898. /**
  21899. * Constructs a render list.
  21900. *
  21901. * @param {Lighting} lighting - The lighting management component.
  21902. * @param {Scene} scene - The scene.
  21903. * @param {Camera} camera - The camera the scene is rendered with.
  21904. */
  21905. constructor( lighting, scene, camera ) {
  21906. /**
  21907. * 3D objects are transformed into render items and stored in this array.
  21908. *
  21909. * @type {Array<Object>}
  21910. */
  21911. this.renderItems = [];
  21912. /**
  21913. * The current render items index.
  21914. *
  21915. * @type {number}
  21916. * @default 0
  21917. */
  21918. this.renderItemsIndex = 0;
  21919. /**
  21920. * A list with opaque render items.
  21921. *
  21922. * @type {Array<Object>}
  21923. */
  21924. this.opaque = [];
  21925. /**
  21926. * A list with transparent render items which require
  21927. * double pass rendering (e.g. transmissive objects).
  21928. *
  21929. * @type {Array<Object>}
  21930. */
  21931. this.transparentDoublePass = [];
  21932. /**
  21933. * A list with transparent render items.
  21934. *
  21935. * @type {Array<Object>}
  21936. */
  21937. this.transparent = [];
  21938. /**
  21939. * A list with transparent render bundle data.
  21940. *
  21941. * @type {Array<Object>}
  21942. */
  21943. this.bundles = [];
  21944. /**
  21945. * The render list's lights node. This node is later
  21946. * relevant for the actual analytical light nodes which
  21947. * compute the scene's lighting in the shader.
  21948. *
  21949. * @type {LightsNode}
  21950. */
  21951. this.lightsNode = lighting.getNode( scene, camera );
  21952. /**
  21953. * The scene's lights stored in an array. This array
  21954. * is used to setup the lights node.
  21955. *
  21956. * @type {Array<Light>}
  21957. */
  21958. this.lightsArray = [];
  21959. /**
  21960. * The scene.
  21961. *
  21962. * @type {Scene}
  21963. */
  21964. this.scene = scene;
  21965. /**
  21966. * The camera the scene is rendered with.
  21967. *
  21968. * @type {Camera}
  21969. */
  21970. this.camera = camera;
  21971. /**
  21972. * How many objects perform occlusion query tests.
  21973. *
  21974. * @type {number}
  21975. * @default 0
  21976. */
  21977. this.occlusionQueryCount = 0;
  21978. }
  21979. /**
  21980. * This method is called right at the beginning of a render call
  21981. * before the scene is analyzed. It prepares the internal data
  21982. * structures for the upcoming render lists generation.
  21983. *
  21984. * @return {RenderList} A reference to this render list.
  21985. */
  21986. begin() {
  21987. this.renderItemsIndex = 0;
  21988. this.opaque.length = 0;
  21989. this.transparentDoublePass.length = 0;
  21990. this.transparent.length = 0;
  21991. this.bundles.length = 0;
  21992. this.lightsArray.length = 0;
  21993. this.occlusionQueryCount = 0;
  21994. return this;
  21995. }
  21996. /**
  21997. * Returns a render item for the giving render item state. The state is defined
  21998. * by a series of object-related parameters.
  21999. *
  22000. * The method avoids object creation by holding render items and reusing them in
  22001. * subsequent render calls (just with different property values).
  22002. *
  22003. * @param {Object3D} object - The 3D object.
  22004. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22005. * @param {Material} material - The 3D object's material.
  22006. * @param {number} groupOrder - The current group order.
  22007. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22008. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22009. * @param {ClippingContext} clippingContext - The current clipping context.
  22010. * @return {Object} The render item.
  22011. */
  22012. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22013. let renderItem = this.renderItems[ this.renderItemsIndex ];
  22014. if ( renderItem === undefined ) {
  22015. renderItem = {
  22016. id: object.id,
  22017. object: object,
  22018. geometry: geometry,
  22019. material: material,
  22020. groupOrder: groupOrder,
  22021. renderOrder: object.renderOrder,
  22022. z: z,
  22023. group: group,
  22024. clippingContext: clippingContext
  22025. };
  22026. this.renderItems[ this.renderItemsIndex ] = renderItem;
  22027. } else {
  22028. renderItem.id = object.id;
  22029. renderItem.object = object;
  22030. renderItem.geometry = geometry;
  22031. renderItem.material = material;
  22032. renderItem.groupOrder = groupOrder;
  22033. renderItem.renderOrder = object.renderOrder;
  22034. renderItem.z = z;
  22035. renderItem.group = group;
  22036. renderItem.clippingContext = clippingContext;
  22037. }
  22038. this.renderItemsIndex ++;
  22039. return renderItem;
  22040. }
  22041. /**
  22042. * Pushes the given object as a render item to the internal render lists.
  22043. * The selected lists depend on the object properties.
  22044. *
  22045. * @param {Object3D} object - The 3D object.
  22046. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22047. * @param {Material} material - The 3D object's material.
  22048. * @param {number} groupOrder - The current group order.
  22049. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22050. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22051. * @param {ClippingContext} clippingContext - The current clipping context.
  22052. */
  22053. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22054. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  22055. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  22056. if ( material.transparent === true || material.transmission > 0 ||
  22057. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  22058. ( material.backdropNode && material.backdropNode.isNode ) ) {
  22059. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  22060. this.transparent.push( renderItem );
  22061. } else {
  22062. this.opaque.push( renderItem );
  22063. }
  22064. }
  22065. /**
  22066. * Inserts the given object as a render item at the start of the internal render lists.
  22067. * The selected lists depend on the object properties.
  22068. *
  22069. * @param {Object3D} object - The 3D object.
  22070. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22071. * @param {Material} material - The 3D object's material.
  22072. * @param {number} groupOrder - The current group order.
  22073. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22074. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22075. * @param {ClippingContext} clippingContext - The current clipping context.
  22076. */
  22077. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22078. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  22079. if ( material.transparent === true || material.transmission > 0 ||
  22080. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  22081. ( material.backdropNode && material.backdropNode.isNode ) ) {
  22082. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  22083. this.transparent.unshift( renderItem );
  22084. } else {
  22085. this.opaque.unshift( renderItem );
  22086. }
  22087. }
  22088. /**
  22089. * Pushes render bundle group data into the render list.
  22090. *
  22091. * @param {Object} group - Bundle group data.
  22092. */
  22093. pushBundle( group ) {
  22094. this.bundles.push( group );
  22095. }
  22096. /**
  22097. * Pushes a light into the render list.
  22098. *
  22099. * @param {Light} light - The light.
  22100. */
  22101. pushLight( light ) {
  22102. this.lightsArray.push( light );
  22103. }
  22104. /**
  22105. * Sorts the internal render lists.
  22106. *
  22107. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  22108. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  22109. */
  22110. sort( customOpaqueSort, customTransparentSort ) {
  22111. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  22112. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  22113. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  22114. }
  22115. /**
  22116. * This method performs finalizing tasks right after the render lists
  22117. * have been generated.
  22118. */
  22119. finish() {
  22120. // update lights
  22121. this.lightsNode.setLights( this.lightsArray );
  22122. // Clear references from inactive renderItems in the list
  22123. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  22124. const renderItem = this.renderItems[ i ];
  22125. if ( renderItem.id === null ) break;
  22126. renderItem.id = null;
  22127. renderItem.object = null;
  22128. renderItem.geometry = null;
  22129. renderItem.material = null;
  22130. renderItem.groupOrder = null;
  22131. renderItem.renderOrder = null;
  22132. renderItem.z = null;
  22133. renderItem.group = null;
  22134. renderItem.clippingContext = null;
  22135. }
  22136. }
  22137. }
  22138. const _chainKeys$4 = [];
  22139. /**
  22140. * This renderer module manages the render lists which are unique
  22141. * per scene and camera combination.
  22142. *
  22143. * @private
  22144. */
  22145. class RenderLists {
  22146. /**
  22147. * Constructs a render lists management component.
  22148. *
  22149. * @param {Lighting} lighting - The lighting management component.
  22150. */
  22151. constructor( lighting ) {
  22152. /**
  22153. * The lighting management component.
  22154. *
  22155. * @type {Lighting}
  22156. */
  22157. this.lighting = lighting;
  22158. /**
  22159. * The internal chain map which holds the render lists.
  22160. *
  22161. * @type {ChainMap}
  22162. */
  22163. this.lists = new ChainMap();
  22164. }
  22165. /**
  22166. * Returns a render list for the given scene and camera.
  22167. *
  22168. * @param {Scene} scene - The scene.
  22169. * @param {Camera} camera - The camera.
  22170. * @return {RenderList} The render list.
  22171. */
  22172. get( scene, camera ) {
  22173. const lists = this.lists;
  22174. _chainKeys$4[ 0 ] = scene;
  22175. _chainKeys$4[ 1 ] = camera;
  22176. let list = lists.get( _chainKeys$4 );
  22177. if ( list === undefined ) {
  22178. list = new RenderList( this.lighting, scene, camera );
  22179. lists.set( _chainKeys$4, list );
  22180. }
  22181. _chainKeys$4.length = 0;
  22182. return list;
  22183. }
  22184. /**
  22185. * Frees all internal resources.
  22186. */
  22187. dispose() {
  22188. this.lists = new ChainMap();
  22189. }
  22190. }
  22191. let _id$8 = 0;
  22192. /**
  22193. * Any render or compute command is executed in a specific context that defines
  22194. * the state of the renderer and its backend. Typical examples for such context
  22195. * data are the current clear values or data from the active framebuffer. This
  22196. * module is used to represent these contexts as objects.
  22197. *
  22198. * @private
  22199. */
  22200. class RenderContext {
  22201. /**
  22202. * Constructs a new render context.
  22203. */
  22204. constructor() {
  22205. /**
  22206. * The context's ID.
  22207. *
  22208. * @type {number}
  22209. */
  22210. this.id = _id$8 ++;
  22211. /**
  22212. * Whether the current active framebuffer has a color attachment.
  22213. *
  22214. * @type {boolean}
  22215. * @default true
  22216. */
  22217. this.color = true;
  22218. /**
  22219. * Whether the color attachment should be cleared or not.
  22220. *
  22221. * @type {boolean}
  22222. * @default true
  22223. */
  22224. this.clearColor = true;
  22225. /**
  22226. * The clear color value.
  22227. *
  22228. * @type {Object}
  22229. * @default true
  22230. */
  22231. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  22232. /**
  22233. * Whether the current active framebuffer has a depth attachment.
  22234. *
  22235. * @type {boolean}
  22236. * @default true
  22237. */
  22238. this.depth = true;
  22239. /**
  22240. * Whether the depth attachment should be cleared or not.
  22241. *
  22242. * @type {boolean}
  22243. * @default true
  22244. */
  22245. this.clearDepth = true;
  22246. /**
  22247. * The clear depth value.
  22248. *
  22249. * @type {number}
  22250. * @default 1
  22251. */
  22252. this.clearDepthValue = 1;
  22253. /**
  22254. * Whether the current active framebuffer has a stencil attachment.
  22255. *
  22256. * @type {boolean}
  22257. * @default false
  22258. */
  22259. this.stencil = false;
  22260. /**
  22261. * Whether the stencil attachment should be cleared or not.
  22262. *
  22263. * @type {boolean}
  22264. * @default true
  22265. */
  22266. this.clearStencil = true;
  22267. /**
  22268. * The clear stencil value.
  22269. *
  22270. * @type {number}
  22271. * @default 1
  22272. */
  22273. this.clearStencilValue = 1;
  22274. /**
  22275. * By default the viewport encloses the entire framebuffer If a smaller
  22276. * viewport is manually defined, this property is to `true` by the renderer.
  22277. *
  22278. * @type {boolean}
  22279. * @default false
  22280. */
  22281. this.viewport = false;
  22282. /**
  22283. * The viewport value. This value is in physical pixels meaning it incorporates
  22284. * the renderer's pixel ratio. The viewport property of render targets or
  22285. * the renderer is in logical pixels.
  22286. *
  22287. * @type {Vector4}
  22288. */
  22289. this.viewportValue = new Vector4();
  22290. /**
  22291. * When the scissor test is active and scissor rectangle smaller than the
  22292. * framebuffers dimensions, this property is to `true` by the renderer.
  22293. *
  22294. * @type {boolean}
  22295. * @default false
  22296. */
  22297. this.scissor = false;
  22298. /**
  22299. * The scissor rectangle.
  22300. *
  22301. * @type {Vector4}
  22302. */
  22303. this.scissorValue = new Vector4();
  22304. /**
  22305. * The active render target.
  22306. *
  22307. * @type {?RenderTarget}
  22308. * @default null
  22309. */
  22310. this.renderTarget = null;
  22311. /**
  22312. * The textures of the active render target.
  22313. * `null` when no render target is set.
  22314. *
  22315. * @type {?Array<Texture>}
  22316. * @default null
  22317. */
  22318. this.textures = null;
  22319. /**
  22320. * The depth texture of the active render target.
  22321. * `null` when no render target is set.
  22322. *
  22323. * @type {?DepthTexture}
  22324. * @default null
  22325. */
  22326. this.depthTexture = null;
  22327. /**
  22328. * The active cube face.
  22329. *
  22330. * @type {number}
  22331. * @default 0
  22332. */
  22333. this.activeCubeFace = 0;
  22334. /**
  22335. * The active mipmap level.
  22336. *
  22337. * @type {number}
  22338. * @default 0
  22339. */
  22340. this.activeMipmapLevel = 0;
  22341. /**
  22342. * The number of MSAA samples. This value is always `1` when
  22343. * MSAA isn't used.
  22344. *
  22345. * @type {number}
  22346. * @default 1
  22347. */
  22348. this.sampleCount = 1;
  22349. /**
  22350. * The active render target's width in physical pixels.
  22351. *
  22352. * @type {number}
  22353. * @default 0
  22354. */
  22355. this.width = 0;
  22356. /**
  22357. * The active render target's height in physical pixels.
  22358. *
  22359. * @type {number}
  22360. * @default 0
  22361. */
  22362. this.height = 0;
  22363. /**
  22364. * The occlusion query count.
  22365. *
  22366. * @type {number}
  22367. * @default 0
  22368. */
  22369. this.occlusionQueryCount = 0;
  22370. /**
  22371. * The current clipping context.
  22372. *
  22373. * @type {?ClippingContext}
  22374. * @default null
  22375. */
  22376. this.clippingContext = null;
  22377. /**
  22378. * This flag can be used for type testing.
  22379. *
  22380. * @type {boolean}
  22381. * @readonly
  22382. * @default true
  22383. */
  22384. this.isRenderContext = true;
  22385. }
  22386. /**
  22387. * Returns the cache key of this render context.
  22388. *
  22389. * @return {number} The cache key.
  22390. */
  22391. getCacheKey() {
  22392. return getCacheKey( this );
  22393. }
  22394. }
  22395. /**
  22396. * Computes a cache key for the given render context. This key
  22397. * should identify the render target state so it is possible to
  22398. * configure the correct attachments in the respective backend.
  22399. *
  22400. * @param {RenderContext} renderContext - The render context.
  22401. * @return {number} The cache key.
  22402. */
  22403. function getCacheKey( renderContext ) {
  22404. const { textures, activeCubeFace, activeMipmapLevel } = renderContext;
  22405. const values = [ activeCubeFace, activeMipmapLevel ];
  22406. for ( const texture of textures ) {
  22407. values.push( texture.id );
  22408. }
  22409. return hashArray( values );
  22410. }
  22411. const _chainKeys$3 = [];
  22412. const _defaultScene = /*@__PURE__*/ new Scene();
  22413. const _defaultCamera = /*@__PURE__*/ new Camera();
  22414. /**
  22415. * This module manages the render contexts of the renderer.
  22416. *
  22417. * @private
  22418. */
  22419. class RenderContexts {
  22420. /**
  22421. * Constructs a new render context management component.
  22422. */
  22423. constructor() {
  22424. /**
  22425. * A dictionary that manages render contexts in chain maps
  22426. * for each attachment state.
  22427. *
  22428. * @type {Object<string,ChainMap>}
  22429. */
  22430. this.chainMaps = {};
  22431. }
  22432. /**
  22433. * Returns a render context for the given scene, camera and render target.
  22434. *
  22435. * @param {Scene} scene - The scene.
  22436. * @param {Camera} camera - The camera that is used to render the scene.
  22437. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22438. * @return {RenderContext} The render context.
  22439. */
  22440. get( scene, camera, renderTarget = null ) {
  22441. _chainKeys$3[ 0 ] = scene;
  22442. _chainKeys$3[ 1 ] = camera;
  22443. let attachmentState;
  22444. if ( renderTarget === null ) {
  22445. attachmentState = 'default';
  22446. } else {
  22447. const format = renderTarget.texture.format;
  22448. const count = renderTarget.textures.length;
  22449. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  22450. }
  22451. const chainMap = this._getChainMap( attachmentState );
  22452. let renderState = chainMap.get( _chainKeys$3 );
  22453. if ( renderState === undefined ) {
  22454. renderState = new RenderContext();
  22455. chainMap.set( _chainKeys$3, renderState );
  22456. }
  22457. _chainKeys$3.length = 0;
  22458. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22459. return renderState;
  22460. }
  22461. /**
  22462. * Returns a render context intended for clear operations.
  22463. *
  22464. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22465. * @return {RenderContext} The render context.
  22466. */
  22467. getForClear( renderTarget = null ) {
  22468. return this.get( _defaultScene, _defaultCamera, renderTarget );
  22469. }
  22470. /**
  22471. * Returns a chain map for the given attachment state.
  22472. *
  22473. * @private
  22474. * @param {string} attachmentState - The attachment state.
  22475. * @return {ChainMap} The chain map.
  22476. */
  22477. _getChainMap( attachmentState ) {
  22478. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  22479. }
  22480. /**
  22481. * Frees internal resources.
  22482. */
  22483. dispose() {
  22484. this.chainMaps = {};
  22485. }
  22486. }
  22487. const _size$3 = /*@__PURE__*/ new Vector3();
  22488. /**
  22489. * This module manages the textures of the renderer.
  22490. *
  22491. * @private
  22492. * @augments DataMap
  22493. */
  22494. class Textures extends DataMap {
  22495. /**
  22496. * Constructs a new texture management component.
  22497. *
  22498. * @param {Renderer} renderer - The renderer.
  22499. * @param {Backend} backend - The renderer's backend.
  22500. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22501. */
  22502. constructor( renderer, backend, info ) {
  22503. super();
  22504. /**
  22505. * The renderer.
  22506. *
  22507. * @type {Renderer}
  22508. */
  22509. this.renderer = renderer;
  22510. /**
  22511. * The backend.
  22512. *
  22513. * @type {Backend}
  22514. */
  22515. this.backend = backend;
  22516. /**
  22517. * Renderer component for managing metrics and monitoring data.
  22518. *
  22519. * @type {Info}
  22520. */
  22521. this.info = info;
  22522. }
  22523. /**
  22524. * Updates the given render target. Based on the given render target configuration,
  22525. * it updates the texture states representing the attachments of the framebuffer.
  22526. *
  22527. * @param {RenderTarget} renderTarget - The render target to update.
  22528. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  22529. */
  22530. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  22531. const renderTargetData = this.get( renderTarget );
  22532. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22533. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  22534. const textures = renderTarget.textures;
  22535. const size = this.getSize( textures[ 0 ] );
  22536. const mipWidth = size.width >> activeMipmapLevel;
  22537. const mipHeight = size.height >> activeMipmapLevel;
  22538. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  22539. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  22540. let textureNeedsUpdate = false;
  22541. if ( depthTexture === undefined && useDepthTexture ) {
  22542. depthTexture = new DepthTexture();
  22543. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  22544. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  22545. depthTexture.image.width = mipWidth;
  22546. depthTexture.image.height = mipHeight;
  22547. depthTexture.image.depth = size.depth;
  22548. depthTexture.renderTarget = renderTarget;
  22549. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  22550. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  22551. }
  22552. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  22553. textureNeedsUpdate = true;
  22554. if ( depthTexture ) {
  22555. depthTexture.needsUpdate = true;
  22556. depthTexture.image.width = mipWidth;
  22557. depthTexture.image.height = mipHeight;
  22558. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  22559. }
  22560. }
  22561. renderTargetData.width = size.width;
  22562. renderTargetData.height = size.height;
  22563. renderTargetData.textures = textures;
  22564. renderTargetData.depthTexture = depthTexture || null;
  22565. renderTargetData.depth = renderTarget.depthBuffer;
  22566. renderTargetData.stencil = renderTarget.stencilBuffer;
  22567. renderTargetData.renderTarget = renderTarget;
  22568. if ( renderTargetData.sampleCount !== sampleCount ) {
  22569. textureNeedsUpdate = true;
  22570. if ( depthTexture ) {
  22571. depthTexture.needsUpdate = true;
  22572. }
  22573. renderTargetData.sampleCount = sampleCount;
  22574. }
  22575. //
  22576. const options = { sampleCount };
  22577. // XR render targets require no texture updates
  22578. if ( renderTarget.isXRRenderTarget !== true ) {
  22579. for ( let i = 0; i < textures.length; i ++ ) {
  22580. const texture = textures[ i ];
  22581. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  22582. this.updateTexture( texture, options );
  22583. }
  22584. if ( depthTexture ) {
  22585. this.updateTexture( depthTexture, options );
  22586. }
  22587. }
  22588. // dispose handler
  22589. if ( renderTargetData.initialized !== true ) {
  22590. renderTargetData.initialized = true;
  22591. // dispose
  22592. renderTargetData.onDispose = () => {
  22593. this._destroyRenderTarget( renderTarget );
  22594. };
  22595. renderTarget.addEventListener( 'dispose', renderTargetData.onDispose );
  22596. }
  22597. }
  22598. /**
  22599. * Updates the given texture. Depending on the texture state, this method
  22600. * triggers the upload of texture data to the GPU memory. If the texture data are
  22601. * not yet ready for the upload, it uses default texture data for as a placeholder.
  22602. *
  22603. * @param {Texture} texture - The texture to update.
  22604. * @param {Object} [options={}] - The options.
  22605. */
  22606. updateTexture( texture, options = {} ) {
  22607. const textureData = this.get( texture );
  22608. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  22609. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  22610. const backend = this.backend;
  22611. if ( isRenderTarget && textureData.initialized === true ) {
  22612. // it's an update
  22613. backend.destroyTexture( texture );
  22614. }
  22615. //
  22616. if ( texture.isFramebufferTexture ) {
  22617. const renderTarget = this.renderer.getRenderTarget();
  22618. if ( renderTarget ) {
  22619. texture.type = renderTarget.texture.type;
  22620. } else {
  22621. texture.type = UnsignedByteType;
  22622. }
  22623. }
  22624. //
  22625. const { width, height, depth } = this.getSize( texture );
  22626. options.width = width;
  22627. options.height = height;
  22628. options.depth = depth;
  22629. options.needsMipmaps = this.needsMipmaps( texture );
  22630. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  22631. // TODO: Uniformly handle mipmap definitions
  22632. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  22633. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  22634. if ( texture.isCubeTexture && texture.mipmaps.length > 0 ) options.levels ++;
  22635. //
  22636. if ( isRenderTarget || texture.isStorageTexture === true || texture.isExternalTexture === true ) {
  22637. backend.createTexture( texture, options );
  22638. textureData.generation = texture.version;
  22639. } else {
  22640. if ( texture.version > 0 ) {
  22641. const image = texture.image;
  22642. if ( image === undefined ) {
  22643. warn( 'Renderer: Texture marked for update but image is undefined.' );
  22644. } else if ( image.complete === false ) {
  22645. warn( 'Renderer: Texture marked for update but image is incomplete.' );
  22646. } else {
  22647. if ( texture.images ) {
  22648. const images = [];
  22649. for ( const image of texture.images ) {
  22650. images.push( image );
  22651. }
  22652. options.images = images;
  22653. } else {
  22654. options.image = image;
  22655. }
  22656. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  22657. backend.createTexture( texture, options );
  22658. textureData.isDefaultTexture = false;
  22659. textureData.generation = texture.version;
  22660. }
  22661. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  22662. const skipAutoGeneration = texture.isStorageTexture === true && texture.mipmapsAutoUpdate === false;
  22663. if ( options.needsMipmaps && texture.mipmaps.length === 0 && ! skipAutoGeneration ) {
  22664. backend.generateMipmaps( texture );
  22665. }
  22666. if ( texture.onUpdate ) texture.onUpdate( texture );
  22667. }
  22668. } else {
  22669. // async update
  22670. backend.createDefaultTexture( texture );
  22671. textureData.isDefaultTexture = true;
  22672. textureData.generation = texture.version;
  22673. }
  22674. }
  22675. // dispose handler
  22676. if ( textureData.initialized !== true ) {
  22677. textureData.initialized = true;
  22678. textureData.generation = texture.version;
  22679. //
  22680. this.info.memory.textures ++;
  22681. //
  22682. if ( texture.isVideoTexture && ColorManagement.getTransfer( texture.colorSpace ) !== SRGBTransfer ) {
  22683. warn( 'WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.' );
  22684. }
  22685. // dispose
  22686. textureData.onDispose = () => {
  22687. this._destroyTexture( texture );
  22688. };
  22689. texture.addEventListener( 'dispose', textureData.onDispose );
  22690. }
  22691. //
  22692. textureData.version = texture.version;
  22693. }
  22694. /**
  22695. * Updates the sampler for the given texture. This method has no effect
  22696. * for the WebGL backend since it has no concept of samplers. Texture
  22697. * parameters are configured with the `texParameter()` command for each
  22698. * texture.
  22699. *
  22700. * In WebGPU, samplers are objects like textures and it's possible to share
  22701. * them when the texture parameters match.
  22702. *
  22703. * @param {Texture} texture - The texture to update the sampler for.
  22704. * @return {string} The current sampler key.
  22705. */
  22706. updateSampler( texture ) {
  22707. return this.backend.updateSampler( texture );
  22708. }
  22709. /**
  22710. * Computes the size of the given texture and writes the result
  22711. * into the target vector. This vector is also returned by the
  22712. * method.
  22713. *
  22714. * If no texture data are available for the compute yet, the method
  22715. * returns default size values.
  22716. *
  22717. * @param {Texture} texture - The texture to compute the size for.
  22718. * @param {Vector3} target - The target vector.
  22719. * @return {Vector3} The target vector.
  22720. */
  22721. getSize( texture, target = _size$3 ) {
  22722. let image = texture.images ? texture.images[ 0 ] : texture.image;
  22723. if ( image ) {
  22724. if ( image.image !== undefined ) image = image.image;
  22725. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( image instanceof HTMLVideoElement ) ) {
  22726. target.width = image.videoWidth || 1;
  22727. target.height = image.videoHeight || 1;
  22728. target.depth = 1;
  22729. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( image instanceof VideoFrame ) ) {
  22730. target.width = image.displayWidth || 1;
  22731. target.height = image.displayHeight || 1;
  22732. target.depth = 1;
  22733. } else {
  22734. target.width = image.width || 1;
  22735. target.height = image.height || 1;
  22736. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  22737. }
  22738. } else {
  22739. target.width = target.height = target.depth = 1;
  22740. }
  22741. return target;
  22742. }
  22743. /**
  22744. * Computes the number of mipmap levels for the given texture.
  22745. *
  22746. * @param {Texture} texture - The texture.
  22747. * @param {number} width - The texture's width.
  22748. * @param {number} height - The texture's height.
  22749. * @return {number} The number of mipmap levels.
  22750. */
  22751. getMipLevels( texture, width, height ) {
  22752. let mipLevelCount;
  22753. if ( texture.mipmaps.length > 0 ) {
  22754. mipLevelCount = texture.mipmaps.length;
  22755. } else {
  22756. if ( texture.isCompressedTexture === true ) {
  22757. // it is not possible to compute mipmaps for compressed textures. So
  22758. // when no mipmaps are defined in "texture.mipmaps", force a texture
  22759. // level of 1
  22760. mipLevelCount = 1;
  22761. } else {
  22762. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  22763. }
  22764. }
  22765. return mipLevelCount;
  22766. }
  22767. /**
  22768. * Returns `true` if the given texture makes use of mipmapping.
  22769. *
  22770. * @param {Texture} texture - The texture.
  22771. * @return {boolean} Whether mipmaps are required or not.
  22772. */
  22773. needsMipmaps( texture ) {
  22774. return texture.generateMipmaps === true || texture.mipmaps.length > 0;
  22775. }
  22776. /**
  22777. * Frees internal resources when the given render target isn't
  22778. * required anymore.
  22779. *
  22780. * @param {RenderTarget} renderTarget - The render target to destroy.
  22781. */
  22782. _destroyRenderTarget( renderTarget ) {
  22783. if ( this.has( renderTarget ) === true ) {
  22784. const renderTargetData = this.get( renderTarget );
  22785. const textures = renderTargetData.textures;
  22786. const depthTexture = renderTargetData.depthTexture;
  22787. //
  22788. renderTarget.removeEventListener( 'dispose', renderTargetData.onDispose );
  22789. //
  22790. for ( let i = 0; i < textures.length; i ++ ) {
  22791. this._destroyTexture( textures[ i ] );
  22792. }
  22793. if ( depthTexture ) {
  22794. this._destroyTexture( depthTexture );
  22795. }
  22796. this.delete( renderTarget );
  22797. this.backend.delete( renderTarget );
  22798. }
  22799. }
  22800. /**
  22801. * Frees internal resource when the given texture isn't
  22802. * required anymore.
  22803. *
  22804. * @param {Texture} texture - The texture to destroy.
  22805. */
  22806. _destroyTexture( texture ) {
  22807. if ( this.has( texture ) === true ) {
  22808. const textureData = this.get( texture );
  22809. //
  22810. texture.removeEventListener( 'dispose', textureData.onDispose );
  22811. // if a texture is not ready for use, it falls back to a default texture so it's possible
  22812. // to use it for rendering. If a texture in this state is disposed, it's important to
  22813. // not destroy/delete the underlying GPU texture object since it is cached and shared with
  22814. // other textures.
  22815. const isDefaultTexture = textureData.isDefaultTexture;
  22816. this.backend.destroyTexture( texture, isDefaultTexture );
  22817. this.delete( texture );
  22818. this.info.memory.textures --;
  22819. }
  22820. }
  22821. }
  22822. /**
  22823. * A four-component version of {@link Color} which is internally
  22824. * used by the renderer to represents clear color with alpha as
  22825. * one object.
  22826. *
  22827. * @private
  22828. * @augments Color
  22829. */
  22830. class Color4 extends Color {
  22831. /**
  22832. * Constructs a new four-component color.
  22833. * You can also pass a single THREE.Color, hex or
  22834. * string argument to this constructor.
  22835. *
  22836. * @param {number|string} [r=1] - The red value.
  22837. * @param {number} [g=1] - The green value.
  22838. * @param {number} [b=1] - The blue value.
  22839. * @param {number} [a=1] - The alpha value.
  22840. */
  22841. constructor( r, g, b, a = 1 ) {
  22842. super( r, g, b );
  22843. this.a = a;
  22844. }
  22845. /**
  22846. * Overwrites the default to honor alpha.
  22847. * You can also pass a single THREE.Color, hex or
  22848. * string argument to this method.
  22849. *
  22850. * @param {number|string|Color} r - The red value.
  22851. * @param {number} [g] - The green value.
  22852. * @param {number} [b] - The blue value.
  22853. * @param {number} [a=1] - The alpha value.
  22854. * @return {Color4} A reference to this object.
  22855. */
  22856. set( r, g, b, a = 1 ) {
  22857. this.a = a;
  22858. return super.set( r, g, b );
  22859. }
  22860. /**
  22861. * Overwrites the default to honor alpha.
  22862. *
  22863. * @param {Color4} color - The color to copy.
  22864. * @return {Color4} A reference to this object.
  22865. */
  22866. copy( color ) {
  22867. if ( color.a !== undefined ) this.a = color.a;
  22868. return super.copy( color );
  22869. }
  22870. /**
  22871. * Overwrites the default to honor alpha.
  22872. *
  22873. * @return {Color4} The cloned color.
  22874. */
  22875. clone() {
  22876. return new this.constructor( this.r, this.g, this.b, this.a );
  22877. }
  22878. }
  22879. /**
  22880. * Special version of {@link PropertyNode} which is used for parameters.
  22881. *
  22882. * @augments PropertyNode
  22883. */
  22884. class ParameterNode extends PropertyNode {
  22885. static get type() {
  22886. return 'ParameterNode';
  22887. }
  22888. /**
  22889. * Constructs a new parameter node.
  22890. *
  22891. * @param {string} nodeType - The type of the node.
  22892. * @param {?string} [name=null] - The name of the parameter in the shader.
  22893. */
  22894. constructor( nodeType, name = null ) {
  22895. super( nodeType, name );
  22896. /**
  22897. * This flag can be used for type testing.
  22898. *
  22899. * @type {boolean}
  22900. * @readonly
  22901. * @default true
  22902. */
  22903. this.isParameterNode = true;
  22904. }
  22905. /**
  22906. * Gets the type of a member variable in the parameter node.
  22907. *
  22908. * @param {NodeBuilder} builder - The node builder.
  22909. * @param {string} name - The name of the member variable.
  22910. * @returns {string}
  22911. */
  22912. getMemberType( builder, name ) {
  22913. const type = this.getNodeType( builder );
  22914. const struct = builder.getStructTypeNode( type );
  22915. let memberType;
  22916. if ( struct !== null ) {
  22917. memberType = struct.getMemberType( builder, name );
  22918. } else {
  22919. error( `TSL: Member "${ name }" not found in struct "${ type }".` );
  22920. memberType = 'float';
  22921. }
  22922. return memberType;
  22923. }
  22924. getHash() {
  22925. return this.uuid;
  22926. }
  22927. generate() {
  22928. return this.name;
  22929. }
  22930. }
  22931. /**
  22932. * TSL function for creating a parameter node.
  22933. *
  22934. * @tsl
  22935. * @function
  22936. * @param {string} type - The type of the node.
  22937. * @param {?string} name - The name of the parameter in the shader.
  22938. * @returns {ParameterNode}
  22939. */
  22940. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  22941. /**
  22942. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  22943. * They are usually needed in cases like `If`, `Else`.
  22944. *
  22945. * @augments Node
  22946. */
  22947. class StackNode extends Node {
  22948. static get type() {
  22949. return 'StackNode';
  22950. }
  22951. /**
  22952. * Constructs a new stack node.
  22953. *
  22954. * @param {?StackNode} [parent=null] - The parent stack node.
  22955. */
  22956. constructor( parent = null ) {
  22957. super();
  22958. /**
  22959. * List of nodes.
  22960. *
  22961. * @type {Array<Node>}
  22962. */
  22963. this.nodes = [];
  22964. /**
  22965. * The output node.
  22966. *
  22967. * @type {?Node}
  22968. * @default null
  22969. */
  22970. this.outputNode = null;
  22971. /**
  22972. * The parent stack node.
  22973. *
  22974. * @type {?StackNode}
  22975. * @default null
  22976. */
  22977. this.parent = parent;
  22978. /**
  22979. * The current conditional node.
  22980. *
  22981. * @private
  22982. * @type {ConditionalNode}
  22983. * @default null
  22984. */
  22985. this._currentCond = null;
  22986. /**
  22987. * The expression node. Only
  22988. * relevant for Switch/Case.
  22989. *
  22990. * @private
  22991. * @type {Node}
  22992. * @default null
  22993. */
  22994. this._expressionNode = null;
  22995. /**
  22996. * This flag can be used for type testing.
  22997. *
  22998. * @type {boolean}
  22999. * @readonly
  23000. * @default true
  23001. */
  23002. this.isStackNode = true;
  23003. }
  23004. getNodeType( builder ) {
  23005. return this.hasOutput ? this.outputNode.getNodeType( builder ) : 'void';
  23006. }
  23007. getMemberType( builder, name ) {
  23008. return this.hasOutput ? this.outputNode.getMemberType( builder, name ) : 'void';
  23009. }
  23010. /**
  23011. * Adds a node to this stack.
  23012. *
  23013. * @param {Node} node - The node to add.
  23014. * @return {StackNode} A reference to this stack node.
  23015. */
  23016. addToStack( node ) {
  23017. if ( node.isNode !== true ) {
  23018. error( 'TSL: Invalid node added to stack.' );
  23019. return this;
  23020. }
  23021. this.nodes.push( node );
  23022. return this;
  23023. }
  23024. /**
  23025. * Represent an `if` statement in TSL.
  23026. *
  23027. * @param {Node} boolNode - Represents the condition.
  23028. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23029. * @return {StackNode} A reference to this stack node.
  23030. */
  23031. If( boolNode, method ) {
  23032. const methodNode = new ShaderNode( method );
  23033. this._currentCond = select( boolNode, methodNode );
  23034. return this.addToStack( this._currentCond );
  23035. }
  23036. /**
  23037. * Represent an `elseif` statement in TSL.
  23038. *
  23039. * @param {Node} boolNode - Represents the condition.
  23040. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23041. * @return {StackNode} A reference to this stack node.
  23042. */
  23043. ElseIf( boolNode, method ) {
  23044. const methodNode = new ShaderNode( method );
  23045. const ifNode = select( boolNode, methodNode );
  23046. this._currentCond.elseNode = ifNode;
  23047. this._currentCond = ifNode;
  23048. return this;
  23049. }
  23050. /**
  23051. * Represent an `else` statement in TSL.
  23052. *
  23053. * @param {Function} method - TSL code which is executed in the `else` case.
  23054. * @return {StackNode} A reference to this stack node.
  23055. */
  23056. Else( method ) {
  23057. this._currentCond.elseNode = new ShaderNode( method );
  23058. return this;
  23059. }
  23060. /**
  23061. * Represents a `switch` statement in TSL.
  23062. *
  23063. * @param {any} expression - Represents the expression.
  23064. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23065. * @return {StackNode} A reference to this stack node.
  23066. */
  23067. Switch( expression ) {
  23068. this._expressionNode = nodeObject( expression );
  23069. return this;
  23070. }
  23071. /**
  23072. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  23073. * The last parameter must be the callback method that should be executed in the `true` case.
  23074. *
  23075. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  23076. * @return {StackNode} A reference to this stack node.
  23077. */
  23078. Case( ...params ) {
  23079. const caseNodes = [];
  23080. // extract case nodes from the parameter list
  23081. if ( params.length >= 2 ) {
  23082. for ( let i = 0; i < params.length - 1; i ++ ) {
  23083. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  23084. }
  23085. } else {
  23086. error( 'TSL: Invalid parameter length. Case() requires at least two parameters.' );
  23087. }
  23088. // extract method
  23089. const method = params[ params.length - 1 ];
  23090. const methodNode = new ShaderNode( method );
  23091. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  23092. let caseNode = caseNodes[ 0 ];
  23093. for ( let i = 1; i < caseNodes.length; i ++ ) {
  23094. caseNode = caseNode.or( caseNodes[ i ] );
  23095. }
  23096. // build condition
  23097. const condNode = select( caseNode, methodNode );
  23098. if ( this._currentCond === null ) {
  23099. this._currentCond = condNode;
  23100. return this.addToStack( this._currentCond );
  23101. } else {
  23102. this._currentCond.elseNode = condNode;
  23103. this._currentCond = condNode;
  23104. return this;
  23105. }
  23106. }
  23107. /**
  23108. * Represents the default code block of a Switch/Case statement.
  23109. *
  23110. * @param {Function} method - TSL code which is executed in the `else` case.
  23111. * @return {StackNode} A reference to this stack node.
  23112. */
  23113. Default( method ) {
  23114. this.Else( method );
  23115. return this;
  23116. }
  23117. setup( builder ) {
  23118. const nodeProperties = builder.getNodeProperties( this );
  23119. let index = 0;
  23120. for ( const childNode of this.getChildren() ) {
  23121. if ( childNode.isVarNode && childNode.intent === true ) {
  23122. if ( childNode.isAssign( builder ) !== true ) {
  23123. continue;
  23124. }
  23125. }
  23126. nodeProperties[ 'node' + index ++ ] = childNode;
  23127. }
  23128. // return a outputNode if exists or null
  23129. return nodeProperties.outputNode || null;
  23130. }
  23131. get hasOutput() {
  23132. return this.outputNode && this.outputNode.isNode;
  23133. }
  23134. build( builder, ...params ) {
  23135. const previousStack = getCurrentStack();
  23136. setCurrentStack( this );
  23137. builder.setActiveStack( this );
  23138. const buildStage = builder.buildStage;
  23139. for ( const node of this.nodes ) {
  23140. if ( node.isVarNode && node.intent === true ) {
  23141. if ( node.isAssign( builder ) !== true ) {
  23142. continue;
  23143. }
  23144. }
  23145. if ( buildStage === 'setup' ) {
  23146. node.build( builder );
  23147. } else if ( buildStage === 'analyze' ) {
  23148. node.build( builder, this );
  23149. } else if ( buildStage === 'generate' ) {
  23150. const stages = builder.getDataFromNode( node, 'any' ).stages;
  23151. const parents = stages && stages[ builder.shaderStage ];
  23152. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  23153. continue; // skip var nodes that are only used in .toVarying()
  23154. }
  23155. node.build( builder, 'void' );
  23156. }
  23157. }
  23158. //
  23159. let result;
  23160. if ( this.hasOutput ) {
  23161. result = this.outputNode.build( builder, ...params );
  23162. } else {
  23163. result = super.build( builder, ...params );
  23164. }
  23165. setCurrentStack( previousStack );
  23166. builder.removeActiveStack( this );
  23167. return result;
  23168. }
  23169. }
  23170. /**
  23171. * TSL function for creating a stack node.
  23172. *
  23173. * @tsl
  23174. * @function
  23175. * @param {?StackNode} [parent=null] - The parent stack node.
  23176. * @returns {StackNode}
  23177. */
  23178. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  23179. /**
  23180. * Generates a layout for struct members.
  23181. * This function takes an object representing struct members and returns an array of member layouts.
  23182. * Each member layout includes the member's name, type, and whether it is atomic.
  23183. *
  23184. * @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.
  23185. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  23186. */
  23187. function getMembersLayout( members ) {
  23188. return Object.entries( members ).map( ( [ name, value ] ) => {
  23189. if ( typeof value === 'string' ) {
  23190. return { name, type: value, atomic: false };
  23191. }
  23192. return { name, type: value.type, atomic: value.atomic || false };
  23193. } );
  23194. }
  23195. /**
  23196. * Represents a struct type node in the node-based system.
  23197. * This class is used to define and manage the layout and types of struct members.
  23198. * It extends the base Node class and provides methods to get the length of the struct,
  23199. * retrieve member types, and generate the struct type for a builder.
  23200. *
  23201. * @augments Node
  23202. */
  23203. class StructTypeNode extends Node {
  23204. static get type() {
  23205. return 'StructTypeNode';
  23206. }
  23207. /**
  23208. * Creates an instance of StructTypeNode.
  23209. *
  23210. * @param {Object} membersLayout - The layout of the members for the struct.
  23211. * @param {?string} [name=null] - The optional name of the struct.
  23212. */
  23213. constructor( membersLayout, name = null ) {
  23214. super( 'struct' );
  23215. /**
  23216. * The layout of the members for the struct
  23217. *
  23218. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  23219. */
  23220. this.membersLayout = getMembersLayout( membersLayout );
  23221. /**
  23222. * The name of the struct.
  23223. *
  23224. * @type {?string}
  23225. * @default null
  23226. */
  23227. this.name = name;
  23228. /**
  23229. * This flag can be used for type testing.
  23230. *
  23231. * @type {boolean}
  23232. * @readonly
  23233. * @default true
  23234. */
  23235. this.isStructLayoutNode = true;
  23236. }
  23237. /**
  23238. * Returns the length of the struct.
  23239. * The length is calculated by summing the lengths of the struct's members.
  23240. *
  23241. * @returns {number} The length of the struct.
  23242. */
  23243. getLength() {
  23244. const GPU_CHUNK_BYTES = 8;
  23245. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  23246. let offset = 0; // global buffer offset in bytes
  23247. for ( const member of this.membersLayout ) {
  23248. const type = member.type;
  23249. const itemSize = getMemoryLengthFromType( type ) * BYTES_PER_ELEMENT;
  23250. const boundary = getByteBoundaryFromType( type );
  23251. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  23252. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  23253. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  23254. offset += chunkPadding;
  23255. // Check for chunk overflow
  23256. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  23257. // Add padding to the end of the chunk
  23258. offset += ( GPU_CHUNK_BYTES - chunkStart );
  23259. }
  23260. offset += itemSize;
  23261. }
  23262. return ( Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES ) / BYTES_PER_ELEMENT;
  23263. }
  23264. getMemberType( builder, name ) {
  23265. const member = this.membersLayout.find( m => m.name === name );
  23266. return member ? member.type : 'void';
  23267. }
  23268. getNodeType( builder ) {
  23269. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23270. return structType.name;
  23271. }
  23272. setup( builder ) {
  23273. builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23274. builder.addInclude( this );
  23275. }
  23276. generate( builder ) {
  23277. return this.getNodeType( builder );
  23278. }
  23279. }
  23280. /**
  23281. * StructNode allows to create custom structures with multiple members.
  23282. * This can also be used to define structures in attribute and uniform data.
  23283. *
  23284. * ```js
  23285. * // Define a custom struct
  23286. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  23287. *
  23288. * // Create a new instance of the struct
  23289. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  23290. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  23291. *
  23292. * // Access the struct members
  23293. * const min = bb.get( 'min' );
  23294. *
  23295. * // Assign a new value to a member
  23296. * min.assign( vec3() );
  23297. * ```
  23298. * @augments Node
  23299. */
  23300. class StructNode extends Node {
  23301. static get type() {
  23302. return 'StructNode';
  23303. }
  23304. constructor( structTypeNode, values ) {
  23305. super( 'vec3' );
  23306. this.structTypeNode = structTypeNode;
  23307. this.values = values;
  23308. this.isStructNode = true;
  23309. }
  23310. getNodeType( builder ) {
  23311. return this.structTypeNode.getNodeType( builder );
  23312. }
  23313. getMemberType( builder, name ) {
  23314. return this.structTypeNode.getMemberType( builder, name );
  23315. }
  23316. generate( builder ) {
  23317. const nodeVar = builder.getVarFromNode( this );
  23318. const structType = nodeVar.type;
  23319. const propertyName = builder.getPropertyName( nodeVar );
  23320. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structTypeNode.membersLayout, this.values ) }`, this );
  23321. return nodeVar.name;
  23322. }
  23323. }
  23324. /**
  23325. * TSL function for creating a struct node.
  23326. *
  23327. * @tsl
  23328. * @function
  23329. * @param {Object} membersLayout - The layout of the struct members.
  23330. * @param {?string} [name=null] - The name of the struct.
  23331. * @returns {Function} The struct function.
  23332. */
  23333. const struct = ( membersLayout, name = null ) => {
  23334. const structLayout = new StructTypeNode( membersLayout, name );
  23335. const struct = ( ...params ) => {
  23336. let values = null;
  23337. if ( params.length > 0 ) {
  23338. if ( params[ 0 ].isNode ) {
  23339. values = {};
  23340. const names = Object.keys( membersLayout );
  23341. for ( let i = 0; i < params.length; i ++ ) {
  23342. values[ names[ i ] ] = params[ i ];
  23343. }
  23344. } else {
  23345. values = params[ 0 ];
  23346. }
  23347. }
  23348. return nodeObject( new StructNode( structLayout, values ) );
  23349. };
  23350. struct.layout = structLayout;
  23351. struct.isStruct = true;
  23352. return struct;
  23353. };
  23354. /**
  23355. * This node can be used to define multiple outputs in a shader programs.
  23356. *
  23357. * @augments Node
  23358. */
  23359. class OutputStructNode extends Node {
  23360. static get type() {
  23361. return 'OutputStructNode';
  23362. }
  23363. /**
  23364. * Constructs a new output struct node. The constructor can be invoked with an
  23365. * arbitrary number of nodes representing the members.
  23366. *
  23367. * @param {...Node} members - A parameter list of nodes.
  23368. */
  23369. constructor( ...members ) {
  23370. super();
  23371. /**
  23372. * An array of nodes which defines the output.
  23373. *
  23374. * @type {Array<Node>}
  23375. */
  23376. this.members = members;
  23377. /**
  23378. * This flag can be used for type testing.
  23379. *
  23380. * @type {boolean}
  23381. * @readonly
  23382. * @default true
  23383. */
  23384. this.isOutputStructNode = true;
  23385. }
  23386. getNodeType( builder ) {
  23387. const properties = builder.getNodeProperties( this );
  23388. if ( properties.membersLayout === undefined ) {
  23389. const members = this.members;
  23390. const membersLayout = [];
  23391. for ( let i = 0; i < members.length; i ++ ) {
  23392. const name = 'm' + i;
  23393. const type = members[ i ].getNodeType( builder );
  23394. membersLayout.push( { name, type, index: i } );
  23395. }
  23396. properties.membersLayout = membersLayout;
  23397. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  23398. }
  23399. return properties.structType.name;
  23400. }
  23401. generate( builder ) {
  23402. const propertyName = builder.getOutputStructName();
  23403. const members = this.members;
  23404. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  23405. for ( let i = 0; i < members.length; i ++ ) {
  23406. const snippet = members[ i ].build( builder );
  23407. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  23408. }
  23409. return propertyName;
  23410. }
  23411. }
  23412. /**
  23413. * TSL function for creating an output struct node.
  23414. *
  23415. * @tsl
  23416. * @function
  23417. * @param {...Node} members - A parameter list of nodes.
  23418. * @returns {OutputStructNode}
  23419. */
  23420. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  23421. /**
  23422. * Returns the MRT texture index for the given name.
  23423. *
  23424. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  23425. * @param {string} name - The name of the MRT texture which index is requested.
  23426. * @return {number} The texture index.
  23427. */
  23428. function getTextureIndex( textures, name ) {
  23429. for ( let i = 0; i < textures.length; i ++ ) {
  23430. if ( textures[ i ].name === name ) {
  23431. return i;
  23432. }
  23433. }
  23434. return -1;
  23435. }
  23436. /**
  23437. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  23438. * post-processing is shown below:
  23439. * ```js
  23440. * const mrtNode = mrt( {
  23441. * output: output,
  23442. * normal: normalView
  23443. * } ) );
  23444. * ```
  23445. * The MRT output is defined as a dictionary.
  23446. *
  23447. * @augments OutputStructNode
  23448. */
  23449. class MRTNode extends OutputStructNode {
  23450. static get type() {
  23451. return 'MRTNode';
  23452. }
  23453. /**
  23454. * Constructs a new output struct node.
  23455. *
  23456. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  23457. */
  23458. constructor( outputNodes ) {
  23459. super();
  23460. /**
  23461. * A dictionary representing the MRT outputs. The key
  23462. * is the name of the output, the value the node which produces
  23463. * the output result.
  23464. *
  23465. * @type {Object<string, Node>}
  23466. */
  23467. this.outputNodes = outputNodes;
  23468. /**
  23469. * This flag can be used for type testing.
  23470. *
  23471. * @type {boolean}
  23472. * @readonly
  23473. * @default true
  23474. */
  23475. this.isMRTNode = true;
  23476. }
  23477. /**
  23478. * Returns `true` if the MRT node has an output with the given name.
  23479. *
  23480. * @param {string} name - The name of the output.
  23481. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  23482. */
  23483. has( name ) {
  23484. return this.outputNodes[ name ] !== undefined;
  23485. }
  23486. /**
  23487. * Returns the output node for the given name.
  23488. *
  23489. * @param {string} name - The name of the output.
  23490. * @return {Node} The output node.
  23491. */
  23492. get( name ) {
  23493. return this.outputNodes[ name ];
  23494. }
  23495. /**
  23496. * Merges the outputs of the given MRT node with the outputs of this node.
  23497. *
  23498. * @param {MRTNode} mrtNode - The MRT to merge.
  23499. * @return {MRTNode} A new MRT node with merged outputs..
  23500. */
  23501. merge( mrtNode ) {
  23502. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  23503. return mrt( outputs );
  23504. }
  23505. setup( builder ) {
  23506. const outputNodes = this.outputNodes;
  23507. const mrt = builder.renderer.getRenderTarget();
  23508. const members = [];
  23509. const textures = mrt.textures;
  23510. for ( const name in outputNodes ) {
  23511. const index = getTextureIndex( textures, name );
  23512. members[ index ] = vec4( outputNodes[ name ] );
  23513. }
  23514. this.members = members;
  23515. return super.setup( builder );
  23516. }
  23517. }
  23518. /**
  23519. * TSL function for creating a MRT node.
  23520. *
  23521. * @tsl
  23522. * @function
  23523. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  23524. * @returns {MRTNode}
  23525. */
  23526. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  23527. /**
  23528. * This node represents an operation that reinterprets the bit representation of a value
  23529. * in one type as a value in another type.
  23530. *
  23531. * @augments TempNode
  23532. */
  23533. class BitcastNode extends TempNode {
  23534. static get type() {
  23535. return 'BitcastNode';
  23536. }
  23537. /**
  23538. * Constructs a new bitcast node.
  23539. *
  23540. * @param {Node} valueNode - The value to convert.
  23541. * @param {string} conversionType - The type to convert to.
  23542. * @param {?string} [inputType = null] - The expected input data type of the bitcast operation.
  23543. */
  23544. constructor( valueNode, conversionType, inputType = null ) {
  23545. super();
  23546. /**
  23547. * The data to bitcast to a new type.
  23548. *
  23549. * @type {Node}
  23550. */
  23551. this.valueNode = valueNode;
  23552. /**
  23553. * The type the value will be converted to.
  23554. *
  23555. * @type {string}
  23556. */
  23557. this.conversionType = conversionType;
  23558. /**
  23559. * The expected input data type of the bitcast operation.
  23560. *
  23561. *
  23562. * @type {string}
  23563. * @default null
  23564. */
  23565. this.inputType = inputType;
  23566. /**
  23567. * This flag can be used for type testing.
  23568. *
  23569. * @type {boolean}
  23570. * @readonly
  23571. * @default true
  23572. */
  23573. this.isBitcastNode = true;
  23574. }
  23575. getNodeType( builder ) {
  23576. // GLSL aliasing
  23577. if ( this.inputType !== null ) {
  23578. const valueType = this.valueNode.getNodeType( builder );
  23579. const valueLength = builder.getTypeLength( valueType );
  23580. return builder.getTypeFromLength( valueLength, this.conversionType );
  23581. }
  23582. return this.conversionType;
  23583. }
  23584. generate( builder ) {
  23585. const type = this.getNodeType( builder );
  23586. let inputType = '';
  23587. if ( this.inputType !== null ) {
  23588. const valueType = this.valueNode.getNodeType( builder );
  23589. const valueTypeLength = builder.getTypeLength( valueType );
  23590. inputType = valueTypeLength === 1 ? this.inputType : builder.changeComponentType( valueType, this.inputType );
  23591. } else {
  23592. inputType = this.valueNode.getNodeType( builder );
  23593. }
  23594. return `${ builder.getBitcastMethod( type, inputType ) }( ${ this.valueNode.build( builder, inputType ) } )`;
  23595. }
  23596. }
  23597. /**
  23598. * Reinterpret the bit representation of a value in one type as a value in another type.
  23599. *
  23600. * @tsl
  23601. * @function
  23602. * @param {Node | number} x - The parameter.
  23603. * @param {string} y - The new type.
  23604. * @returns {Node}
  23605. */
  23606. const bitcast = /*@__PURE__*/ nodeProxyIntent( BitcastNode ).setParameterLength( 2 );
  23607. /**
  23608. * Bitcasts a float or a vector of floats to a corresponding integer type with the same element size.
  23609. *
  23610. * @tsl
  23611. * @function
  23612. * @param {Node<float>} value - The float or vector of floats to bitcast.
  23613. * @returns {BitcastNode}
  23614. */
  23615. const floatBitsToInt = ( value ) => new BitcastNode( value, 'int', 'float' );
  23616. /**
  23617. * Bitcasts a float or a vector of floats to a corresponding unsigned integer type with the same element size.
  23618. *
  23619. * @tsl
  23620. * @function
  23621. * @param {Node<float>} value - The float or vector of floats to bitcast.
  23622. * @returns {BitcastNode}
  23623. */
  23624. const floatBitsToUint = ( value ) => new BitcastNode( value, 'uint', 'float' );
  23625. /**
  23626. * Bitcasts an integer or a vector of integers to a corresponding float type with the same element size.
  23627. *
  23628. * @tsl
  23629. * @function
  23630. * @param {Node<int>} value - The integer or vector of integers to bitcast.
  23631. * @returns {BitcastNode}
  23632. */
  23633. const intBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'int' );
  23634. /**
  23635. * Bitcast an unsigned integer or a vector of unsigned integers to a corresponding float type with the same element size.
  23636. *
  23637. * @tsl
  23638. * @function
  23639. * @param {Node<uint>} value - The unsigned integer or vector of unsigned integers to bitcast.
  23640. * @returns {BitcastNode}
  23641. */
  23642. const uintBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'uint' );
  23643. /**
  23644. * Generates a hash value in the range `[0, 1]` from the given seed.
  23645. *
  23646. * @tsl
  23647. * @function
  23648. * @param {Node<float>} seed - The seed.
  23649. * @return {Node<float>} The hash value.
  23650. */
  23651. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  23652. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  23653. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  23654. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  23655. const result = word.shiftRight( 22 ).bitXor( word );
  23656. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  23657. } );
  23658. /**
  23659. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23660. * The corners are mapped to `0` and the center to `1`.
  23661. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23662. *
  23663. * @tsl
  23664. * @function
  23665. * @param {Node<float>} x - The value to remap.
  23666. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  23667. * @return {Node<float>} The remapped value.
  23668. */
  23669. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  23670. /**
  23671. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23672. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  23673. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23674. *
  23675. * @tsl
  23676. * @function
  23677. * @param {Node<float>} x - The value to remap.
  23678. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  23679. * @return {Node<float>} The remapped value.
  23680. */
  23681. 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 ) );
  23682. /**
  23683. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23684. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  23685. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23686. *
  23687. * @tsl
  23688. * @function
  23689. * @param {Node<float>} x - The value to remap.
  23690. * @param {Node<float>} a - First control parameter.
  23691. * @param {Node<float>} b - Second control parameter.
  23692. * @return {Node<float>} The remapped value.
  23693. */
  23694. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  23695. /**
  23696. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  23697. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23698. *
  23699. * @tsl
  23700. * @function
  23701. * @param {Node<float>} x - The value to compute the sin for.
  23702. * @param {Node<float>} k - Controls the amount of bounces.
  23703. * @return {Node<float>} The result value.
  23704. */
  23705. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  23706. // https://github.com/cabbibo/glsl-tri-noise-3d
  23707. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  23708. return x.fract().sub( .5 ).abs();
  23709. } ).setLayout( {
  23710. name: 'tri',
  23711. type: 'float',
  23712. inputs: [
  23713. { name: 'x', type: 'float' }
  23714. ]
  23715. } );
  23716. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  23717. 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. ) ) ) ) );
  23718. } ).setLayout( {
  23719. name: 'tri3',
  23720. type: 'vec3',
  23721. inputs: [
  23722. { name: 'p', type: 'vec3' }
  23723. ]
  23724. } );
  23725. /**
  23726. * Generates a noise value from the given position, speed and time parameters.
  23727. *
  23728. * @tsl
  23729. * @function
  23730. * @param {Node<vec3>} position - The position.
  23731. * @param {Node<float>} speed - The speed.
  23732. * @param {Node<float>} time - The time.
  23733. * @return {Node<float>} The generated noise.
  23734. */
  23735. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  23736. const p = vec3( position ).toVar();
  23737. const z = float( 1.4 ).toVar();
  23738. const rz = float( 0.0 ).toVar();
  23739. const bp = vec3( p ).toVar();
  23740. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  23741. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  23742. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  23743. bp.mulAssign( 1.8 );
  23744. z.mulAssign( 1.5 );
  23745. p.mulAssign( 1.2 );
  23746. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  23747. rz.addAssign( t.div( z ) );
  23748. bp.addAssign( 0.14 );
  23749. } );
  23750. return rz;
  23751. } ).setLayout( {
  23752. name: 'triNoise3D',
  23753. type: 'float',
  23754. inputs: [
  23755. { name: 'position', type: 'vec3' },
  23756. { name: 'speed', type: 'float' },
  23757. { name: 'time', type: 'float' }
  23758. ]
  23759. } );
  23760. /**
  23761. * This class allows to define multiple overloaded versions
  23762. * of the same function. Depending on the parameters of the function
  23763. * call, the node picks the best-fit overloaded version.
  23764. *
  23765. * @augments Node
  23766. */
  23767. class FunctionOverloadingNode extends Node {
  23768. static get type() {
  23769. return 'FunctionOverloadingNode';
  23770. }
  23771. /**
  23772. * Constructs a new function overloading node.
  23773. *
  23774. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  23775. * @param {...Node} parametersNodes - A list of parameter nodes.
  23776. */
  23777. constructor( functionNodes = [], ...parametersNodes ) {
  23778. super();
  23779. /**
  23780. * Array of `Fn` function definitions.
  23781. *
  23782. * @type {Array<Function>}
  23783. */
  23784. this.functionNodes = functionNodes;
  23785. /**
  23786. * A list of parameter nodes.
  23787. *
  23788. * @type {Array<Node>}
  23789. */
  23790. this.parametersNodes = parametersNodes;
  23791. /**
  23792. * The selected overloaded function call.
  23793. *
  23794. * @private
  23795. * @type {ShaderCallNodeInternal}
  23796. */
  23797. this._candidateFn = null;
  23798. /**
  23799. * This node is marked as global.
  23800. *
  23801. * @type {boolean}
  23802. * @default true
  23803. */
  23804. this.global = true;
  23805. }
  23806. /**
  23807. * This method is overwritten since the node type is inferred from
  23808. * the function's return type.
  23809. *
  23810. * @param {NodeBuilder} builder - The current node builder.
  23811. * @return {string} The node type.
  23812. */
  23813. getNodeType( builder ) {
  23814. const candidateFn = this.getCandidateFn( builder );
  23815. return candidateFn.shaderNode.layout.type;
  23816. }
  23817. /**
  23818. * Returns the candidate function for the current parameters.
  23819. *
  23820. * @param {NodeBuilder} builder - The current node builder.
  23821. * @return {FunctionNode} The candidate function.
  23822. */
  23823. getCandidateFn( builder ) {
  23824. const params = this.parametersNodes;
  23825. let candidateFn = this._candidateFn;
  23826. if ( candidateFn === null ) {
  23827. let bestCandidateFn = null;
  23828. let bestScore = -1;
  23829. for ( const functionNode of this.functionNodes ) {
  23830. const shaderNode = functionNode.shaderNode;
  23831. const layout = shaderNode.layout;
  23832. if ( layout === null ) {
  23833. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  23834. }
  23835. const inputs = layout.inputs;
  23836. if ( params.length === inputs.length ) {
  23837. let currentScore = 0;
  23838. for ( let i = 0; i < params.length; i ++ ) {
  23839. const param = params[ i ];
  23840. const input = inputs[ i ];
  23841. if ( param.getNodeType( builder ) === input.type ) {
  23842. currentScore ++;
  23843. }
  23844. }
  23845. if ( currentScore > bestScore ) {
  23846. bestCandidateFn = functionNode;
  23847. bestScore = currentScore;
  23848. }
  23849. }
  23850. }
  23851. this._candidateFn = candidateFn = bestCandidateFn;
  23852. }
  23853. return candidateFn;
  23854. }
  23855. /**
  23856. * Sets up the node for the current parameters.
  23857. *
  23858. * @param {NodeBuilder} builder - The current node builder.
  23859. * @return {Node} The setup node.
  23860. */
  23861. setup( builder ) {
  23862. const candidateFn = this.getCandidateFn( builder );
  23863. return candidateFn( ...this.parametersNodes );
  23864. }
  23865. }
  23866. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  23867. /**
  23868. * TSL function for creating a function overloading node.
  23869. *
  23870. * @tsl
  23871. * @function
  23872. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  23873. * @returns {FunctionOverloadingNode}
  23874. */
  23875. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  23876. /**
  23877. * Represents the elapsed time in seconds.
  23878. *
  23879. * @tsl
  23880. * @type {UniformNode<float>}
  23881. */
  23882. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  23883. /**
  23884. * Represents the delta time in seconds.
  23885. *
  23886. * @tsl
  23887. * @type {UniformNode<float>}
  23888. */
  23889. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  23890. /**
  23891. * Represents the current frame ID.
  23892. *
  23893. * @tsl
  23894. * @type {UniformNode<uint>}
  23895. */
  23896. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  23897. /**
  23898. * Generates a sine wave oscillation based on a timer.
  23899. *
  23900. * @tsl
  23901. * @function
  23902. * @param {Node<float>} t - The timer to generate the oscillation with.
  23903. * @return {Node<float>} The oscillation node.
  23904. */
  23905. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  23906. /**
  23907. * Generates a square wave oscillation based on a timer.
  23908. *
  23909. * @tsl
  23910. * @function
  23911. * @param {Node<float>} t - The timer to generate the oscillation with.
  23912. * @return {Node<float>} The oscillation node.
  23913. */
  23914. const oscSquare = ( t = time ) => t.fract().round();
  23915. /**
  23916. * Generates a triangle wave oscillation based on a timer.
  23917. *
  23918. * @tsl
  23919. * @function
  23920. * @param {Node<float>} t - The timer to generate the oscillation with.
  23921. * @return {Node<float>} The oscillation node.
  23922. */
  23923. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  23924. /**
  23925. * Generates a sawtooth wave oscillation based on a timer.
  23926. *
  23927. * @tsl
  23928. * @function
  23929. * @param {Node<float>} t - The timer to generate the oscillation with.
  23930. * @return {Node<float>} The oscillation node.
  23931. */
  23932. const oscSawtooth = ( t = time ) => t.fract();
  23933. /**
  23934. * Rotates the given uv coordinates around a center point
  23935. *
  23936. * @tsl
  23937. * @function
  23938. * @param {Node<vec2>} uv - The uv coordinates.
  23939. * @param {Node<float>} rotation - The rotation defined in radians.
  23940. * @param {Node<vec2>} center - The center of rotation
  23941. * @return {Node<vec2>} The rotated uv coordinates.
  23942. */
  23943. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  23944. return rotate( uv.sub( center ), rotation ).add( center );
  23945. } );
  23946. /**
  23947. * Applies a spherical warping effect to the given uv coordinates.
  23948. *
  23949. * @tsl
  23950. * @function
  23951. * @param {Node<vec2>} uv - The uv coordinates.
  23952. * @param {Node<float>} strength - The strength of the effect.
  23953. * @param {Node<vec2>} center - The center point
  23954. * @return {Node<vec2>} The updated uv coordinates.
  23955. */
  23956. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  23957. const delta = uv.sub( center );
  23958. const delta2 = delta.dot( delta );
  23959. const delta4 = delta2.mul( delta2 );
  23960. const deltaOffset = delta4.mul( strength );
  23961. return uv.add( delta.mul( deltaOffset ) );
  23962. } );
  23963. /**
  23964. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  23965. * oriented always towards the camera.
  23966. *
  23967. * ```js
  23968. * material.vertexNode = billboarding();
  23969. * ```
  23970. *
  23971. * @tsl
  23972. * @function
  23973. * @param {Object} config - The configuration object.
  23974. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  23975. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  23976. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  23977. * @return {Node<vec3>} The updated vertex position in clip space.
  23978. */
  23979. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  23980. let worldMatrix;
  23981. if ( position !== null ) {
  23982. worldMatrix = modelWorldMatrix.toVar();
  23983. worldMatrix[ 3 ][ 0 ] = position.x;
  23984. worldMatrix[ 3 ][ 1 ] = position.y;
  23985. worldMatrix[ 3 ][ 2 ] = position.z;
  23986. } else {
  23987. worldMatrix = modelWorldMatrix;
  23988. }
  23989. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  23990. if ( defined( horizontal ) ) {
  23991. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  23992. modelViewMatrix[ 0 ][ 1 ] = 0;
  23993. modelViewMatrix[ 0 ][ 2 ] = 0;
  23994. }
  23995. if ( defined( vertical ) ) {
  23996. modelViewMatrix[ 1 ][ 0 ] = 0;
  23997. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  23998. modelViewMatrix[ 1 ][ 2 ] = 0;
  23999. }
  24000. modelViewMatrix[ 2 ][ 0 ] = 0;
  24001. modelViewMatrix[ 2 ][ 1 ] = 0;
  24002. modelViewMatrix[ 2 ][ 2 ] = 1;
  24003. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  24004. } );
  24005. /**
  24006. * A special version of a screen uv function that involves a depth comparison
  24007. * when computing the final uvs. The function mitigates visual errors when
  24008. * using viewport texture nodes for refraction purposes. Without this function
  24009. * objects in front of a refractive surface might appear on the refractive surface
  24010. * which is incorrect.
  24011. *
  24012. * @tsl
  24013. * @function
  24014. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  24015. * @return {Node<vec2>} The update uv coordinates.
  24016. */
  24017. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  24018. const depth = linearDepth();
  24019. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  24020. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  24021. return finalUV;
  24022. } );
  24023. /**
  24024. * Can be used to compute texture coordinates for animated sprite sheets.
  24025. *
  24026. * ```js
  24027. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  24028. *
  24029. * material.colorNode = texture( spriteSheet, uvNode );
  24030. * ```
  24031. *
  24032. * @augments Node
  24033. */
  24034. class SpriteSheetUVNode extends Node {
  24035. static get type() {
  24036. return 'SpriteSheetUVNode';
  24037. }
  24038. /**
  24039. * Constructs a new sprite sheet uv node.
  24040. *
  24041. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  24042. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  24043. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  24044. */
  24045. constructor( countNode, uvNode = uv$1(), frameNode = float( 0 ) ) {
  24046. super( 'vec2' );
  24047. /**
  24048. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  24049. *
  24050. * @type {Node<vec2>}
  24051. */
  24052. this.countNode = countNode;
  24053. /**
  24054. * The uv node.
  24055. *
  24056. * @type {Node<vec2>}
  24057. */
  24058. this.uvNode = uvNode;
  24059. /**
  24060. * The node that defines the current frame/sprite.
  24061. *
  24062. * @type {Node<float>}
  24063. */
  24064. this.frameNode = frameNode;
  24065. }
  24066. setup() {
  24067. const { frameNode, uvNode, countNode } = this;
  24068. const { width, height } = countNode;
  24069. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  24070. const column = frameNum.mod( width );
  24071. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  24072. const scale = countNode.reciprocal();
  24073. const uvFrameOffset = vec2( column, row );
  24074. return uvNode.add( uvFrameOffset ).mul( scale );
  24075. }
  24076. }
  24077. /**
  24078. * TSL function for creating a sprite sheet uv node.
  24079. *
  24080. * @tsl
  24081. * @function
  24082. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  24083. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  24084. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  24085. * @returns {SpriteSheetUVNode}
  24086. */
  24087. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  24088. /**
  24089. * TSL function for creating a triplanar textures node.
  24090. *
  24091. * Can be used for triplanar texture mapping.
  24092. *
  24093. * ```js
  24094. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  24095. * ```
  24096. *
  24097. * @tsl
  24098. * @function
  24099. * @param {Node} textureXNode - First texture node.
  24100. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  24101. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  24102. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  24103. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  24104. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  24105. * @returns {Node<vec4>}
  24106. */
  24107. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  24108. // Reference: https://github.com/keijiro/StandardTriplanar
  24109. // Blending factor of triplanar mapping
  24110. let bf = normalNode.abs().normalize();
  24111. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  24112. // Triplanar mapping
  24113. const tx = positionNode.yz.mul( scaleNode );
  24114. const ty = positionNode.zx.mul( scaleNode );
  24115. const tz = positionNode.xy.mul( scaleNode );
  24116. // Base color
  24117. const textureX = textureXNode.value;
  24118. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  24119. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  24120. const cx = texture( textureX, tx ).mul( bf.x );
  24121. const cy = texture( textureY, ty ).mul( bf.y );
  24122. const cz = texture( textureZ, tz ).mul( bf.z );
  24123. return add( cx, cy, cz );
  24124. } );
  24125. /**
  24126. * TSL function for creating a triplanar textures node.
  24127. *
  24128. * @tsl
  24129. * @function
  24130. * @param {Node} textureXNode - First texture node.
  24131. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  24132. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  24133. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  24134. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  24135. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  24136. * @returns {Node<vec4>}
  24137. */
  24138. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  24139. const _reflectorPlane = new Plane();
  24140. const _normal = new Vector3();
  24141. const _reflectorWorldPosition = new Vector3();
  24142. const _cameraWorldPosition = new Vector3();
  24143. const _rotationMatrix = new Matrix4();
  24144. const _lookAtPosition = new Vector3( 0, 0, -1 );
  24145. const clipPlane = new Vector4();
  24146. const _view = new Vector3();
  24147. const _target = new Vector3();
  24148. const _q = new Vector4();
  24149. const _size$2 = new Vector2();
  24150. const _defaultRT = new RenderTarget();
  24151. const _defaultUV = screenUV.flipX();
  24152. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  24153. let _inReflector = false;
  24154. /**
  24155. * This node can be used to implement mirror-like flat reflective surfaces.
  24156. *
  24157. * ```js
  24158. * const groundReflector = reflector();
  24159. * material.colorNode = groundReflector;
  24160. *
  24161. * const plane = new Mesh( geometry, material );
  24162. * plane.add( groundReflector.target );
  24163. * ```
  24164. *
  24165. * @augments TextureNode
  24166. */
  24167. class ReflectorNode extends TextureNode {
  24168. static get type() {
  24169. return 'ReflectorNode';
  24170. }
  24171. /**
  24172. * Constructs a new reflector node.
  24173. *
  24174. * @param {Object} [parameters={}] - An object holding configuration parameters.
  24175. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  24176. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  24177. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  24178. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  24179. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  24180. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  24181. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  24182. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  24183. */
  24184. constructor( parameters = {} ) {
  24185. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  24186. /**
  24187. * A reference to the internal reflector base node which holds the actual implementation.
  24188. *
  24189. * @private
  24190. * @type {ReflectorBaseNode}
  24191. * @default ReflectorBaseNode
  24192. */
  24193. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  24194. /**
  24195. * A reference to the internal depth node.
  24196. *
  24197. * @private
  24198. * @type {?Node}
  24199. * @default null
  24200. */
  24201. this._depthNode = null;
  24202. this.setUpdateMatrix( false );
  24203. }
  24204. /**
  24205. * A reference to the internal reflector node.
  24206. *
  24207. * @type {ReflectorBaseNode}
  24208. */
  24209. get reflector() {
  24210. return this._reflectorBaseNode;
  24211. }
  24212. /**
  24213. * A reference to 3D object the reflector is linked to.
  24214. *
  24215. * @type {Object3D}
  24216. */
  24217. get target() {
  24218. return this._reflectorBaseNode.target;
  24219. }
  24220. /**
  24221. * Returns a node representing the mirror's depth. That can be used
  24222. * to implement more advanced reflection effects like distance attenuation.
  24223. *
  24224. * @return {Node} The depth node.
  24225. */
  24226. getDepthNode() {
  24227. if ( this._depthNode === null ) {
  24228. if ( this._reflectorBaseNode.depth !== true ) {
  24229. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  24230. }
  24231. this._depthNode = nodeObject( new ReflectorNode( {
  24232. defaultTexture: _defaultRT.depthTexture,
  24233. reflector: this._reflectorBaseNode
  24234. } ) );
  24235. }
  24236. return this._depthNode;
  24237. }
  24238. setup( builder ) {
  24239. // ignore if used in post-processing
  24240. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  24241. return super.setup( builder );
  24242. }
  24243. clone() {
  24244. const newNode = new this.constructor( this.reflectorNode );
  24245. newNode.uvNode = this.uvNode;
  24246. newNode.levelNode = this.levelNode;
  24247. newNode.biasNode = this.biasNode;
  24248. newNode.sampler = this.sampler;
  24249. newNode.depthNode = this.depthNode;
  24250. newNode.compareNode = this.compareNode;
  24251. newNode.gradNode = this.gradNode;
  24252. newNode.offsetNode = this.offsetNode;
  24253. newNode._reflectorBaseNode = this._reflectorBaseNode;
  24254. return newNode;
  24255. }
  24256. /**
  24257. * Frees internal resources. Should be called when the node is no longer in use.
  24258. */
  24259. dispose() {
  24260. super.dispose();
  24261. this._reflectorBaseNode.dispose();
  24262. }
  24263. }
  24264. /**
  24265. * Holds the actual implementation of the reflector.
  24266. *
  24267. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  24268. * in `ReflectorNode`, see #29619.
  24269. *
  24270. * @private
  24271. * @augments Node
  24272. */
  24273. class ReflectorBaseNode extends Node {
  24274. static get type() {
  24275. return 'ReflectorBaseNode';
  24276. }
  24277. /**
  24278. * Constructs a new reflector base node.
  24279. *
  24280. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  24281. * @param {Object} [parameters={}] - An object holding configuration parameters.
  24282. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  24283. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  24284. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  24285. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  24286. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  24287. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  24288. */
  24289. constructor( textureNode, parameters = {} ) {
  24290. super();
  24291. const {
  24292. target = new Object3D(),
  24293. resolutionScale = 1,
  24294. generateMipmaps = false,
  24295. bounces = true,
  24296. depth = false,
  24297. samples = 0
  24298. } = parameters;
  24299. /**
  24300. * Represents the rendered reflections as a texture node.
  24301. *
  24302. * @type {TextureNode}
  24303. */
  24304. this.textureNode = textureNode;
  24305. /**
  24306. * The 3D object the reflector is linked to.
  24307. *
  24308. * @type {Object3D}
  24309. * @default {new Object3D()}
  24310. */
  24311. this.target = target;
  24312. /**
  24313. * The resolution scale.
  24314. *
  24315. * @type {number}
  24316. * @default {1}
  24317. */
  24318. this.resolutionScale = resolutionScale;
  24319. if ( parameters.resolution !== undefined ) {
  24320. warnOnce( 'ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".' ); // @deprecated r180
  24321. this.resolutionScale = parameters.resolution;
  24322. }
  24323. /**
  24324. * Whether mipmaps should be generated or not.
  24325. *
  24326. * @type {boolean}
  24327. * @default {false}
  24328. */
  24329. this.generateMipmaps = generateMipmaps;
  24330. /**
  24331. * Whether reflectors can render other reflector nodes or not.
  24332. *
  24333. * @type {boolean}
  24334. * @default {true}
  24335. */
  24336. this.bounces = bounces;
  24337. /**
  24338. * Whether depth data should be generated or not.
  24339. *
  24340. * @type {boolean}
  24341. * @default {false}
  24342. */
  24343. this.depth = depth;
  24344. /**
  24345. * The number of anti-aliasing samples for the render-target
  24346. *
  24347. * @type {number}
  24348. * @default {0}
  24349. */
  24350. this.samples = samples;
  24351. /**
  24352. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  24353. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  24354. *
  24355. * @type {string}
  24356. * @default 'render'
  24357. */
  24358. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  24359. /**
  24360. * Weak map for managing virtual cameras.
  24361. *
  24362. * @type {WeakMap<Camera, Camera>}
  24363. */
  24364. this.virtualCameras = new WeakMap();
  24365. /**
  24366. * Weak map for managing render targets.
  24367. *
  24368. * @type {Map<Camera, RenderTarget>}
  24369. */
  24370. this.renderTargets = new Map();
  24371. /**
  24372. * Force render even if reflector is facing away from camera.
  24373. *
  24374. * @type {boolean}
  24375. * @default {false}
  24376. */
  24377. this.forceUpdate = false;
  24378. /**
  24379. * Whether the reflector has been rendered or not.
  24380. *
  24381. * When the reflector is facing away from the camera,
  24382. * this flag is set to `false` and the texture will be empty(black).
  24383. *
  24384. * @type {boolean}
  24385. * @default {false}
  24386. */
  24387. this.hasOutput = false;
  24388. }
  24389. /**
  24390. * Updates the resolution of the internal render target.
  24391. *
  24392. * @private
  24393. * @param {RenderTarget} renderTarget - The render target to resize.
  24394. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  24395. */
  24396. _updateResolution( renderTarget, renderer ) {
  24397. const resolution = this.resolutionScale;
  24398. renderer.getDrawingBufferSize( _size$2 );
  24399. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  24400. }
  24401. setup( builder ) {
  24402. this._updateResolution( _defaultRT, builder.renderer );
  24403. return super.setup( builder );
  24404. }
  24405. /**
  24406. * Frees internal resources. Should be called when the node is no longer in use.
  24407. */
  24408. dispose() {
  24409. super.dispose();
  24410. for ( const renderTarget of this.renderTargets.values() ) {
  24411. renderTarget.dispose();
  24412. }
  24413. }
  24414. /**
  24415. * Returns a virtual camera for the given camera. The virtual camera is used to
  24416. * render the scene from the reflector's view so correct reflections can be produced.
  24417. *
  24418. * @param {Camera} camera - The scene's camera.
  24419. * @return {Camera} The corresponding virtual camera.
  24420. */
  24421. getVirtualCamera( camera ) {
  24422. let virtualCamera = this.virtualCameras.get( camera );
  24423. if ( virtualCamera === undefined ) {
  24424. virtualCamera = camera.clone();
  24425. this.virtualCameras.set( camera, virtualCamera );
  24426. }
  24427. return virtualCamera;
  24428. }
  24429. /**
  24430. * Returns a render target for the given camera. The reflections are rendered
  24431. * into this render target.
  24432. *
  24433. * @param {Camera} camera - The scene's camera.
  24434. * @return {RenderTarget} The render target.
  24435. */
  24436. getRenderTarget( camera ) {
  24437. let renderTarget = this.renderTargets.get( camera );
  24438. if ( renderTarget === undefined ) {
  24439. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  24440. if ( this.generateMipmaps === true ) {
  24441. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  24442. renderTarget.texture.generateMipmaps = true;
  24443. }
  24444. if ( this.depth === true ) {
  24445. renderTarget.depthTexture = new DepthTexture();
  24446. }
  24447. this.renderTargets.set( camera, renderTarget );
  24448. }
  24449. return renderTarget;
  24450. }
  24451. updateBefore( frame ) {
  24452. if ( this.bounces === false && _inReflector ) return false;
  24453. _inReflector = true;
  24454. const { scene, camera, renderer, material } = frame;
  24455. const { target } = this;
  24456. const virtualCamera = this.getVirtualCamera( camera );
  24457. const renderTarget = this.getRenderTarget( virtualCamera );
  24458. renderer.getDrawingBufferSize( _size$2 );
  24459. this._updateResolution( renderTarget, renderer );
  24460. //
  24461. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  24462. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  24463. _rotationMatrix.extractRotation( target.matrixWorld );
  24464. _normal.set( 0, 0, 1 );
  24465. _normal.applyMatrix4( _rotationMatrix );
  24466. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  24467. // Avoid rendering when reflector is facing away unless forcing an update
  24468. const isFacingAway = _view.dot( _normal ) > 0;
  24469. let needsClear = false;
  24470. if ( isFacingAway === true && this.forceUpdate === false ) {
  24471. if ( this.hasOutput === false ) {
  24472. _inReflector = false;
  24473. return;
  24474. }
  24475. needsClear = true;
  24476. }
  24477. _view.reflect( _normal ).negate();
  24478. _view.add( _reflectorWorldPosition );
  24479. _rotationMatrix.extractRotation( camera.matrixWorld );
  24480. _lookAtPosition.set( 0, 0, -1 );
  24481. _lookAtPosition.applyMatrix4( _rotationMatrix );
  24482. _lookAtPosition.add( _cameraWorldPosition );
  24483. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  24484. _target.reflect( _normal ).negate();
  24485. _target.add( _reflectorWorldPosition );
  24486. //
  24487. virtualCamera.coordinateSystem = camera.coordinateSystem;
  24488. virtualCamera.position.copy( _view );
  24489. virtualCamera.up.set( 0, 1, 0 );
  24490. virtualCamera.up.applyMatrix4( _rotationMatrix );
  24491. virtualCamera.up.reflect( _normal );
  24492. virtualCamera.lookAt( _target );
  24493. virtualCamera.near = camera.near;
  24494. virtualCamera.far = camera.far;
  24495. virtualCamera.updateMatrixWorld();
  24496. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  24497. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  24498. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  24499. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  24500. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  24501. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  24502. const projectionMatrix = virtualCamera.projectionMatrix;
  24503. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  24504. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  24505. _q.z = -1;
  24506. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  24507. // Calculate the scaled plane vector
  24508. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  24509. const clipBias = 0;
  24510. // Replacing the third row of the projection matrix
  24511. projectionMatrix.elements[ 2 ] = clipPlane.x;
  24512. projectionMatrix.elements[ 6 ] = clipPlane.y;
  24513. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  24514. projectionMatrix.elements[ 14 ] = clipPlane.w;
  24515. //
  24516. this.textureNode.value = renderTarget.texture;
  24517. if ( this.depth === true ) {
  24518. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  24519. }
  24520. material.visible = false;
  24521. const currentRenderTarget = renderer.getRenderTarget();
  24522. const currentMRT = renderer.getMRT();
  24523. const currentAutoClear = renderer.autoClear;
  24524. renderer.setMRT( null );
  24525. renderer.setRenderTarget( renderTarget );
  24526. renderer.autoClear = true;
  24527. const previousName = scene.name;
  24528. scene.name = ( scene.name || 'Scene' ) + ' [ Reflector ]'; // TODO: Add bounce index
  24529. if ( needsClear ) {
  24530. renderer.clear();
  24531. this.hasOutput = false;
  24532. } else {
  24533. renderer.render( scene, virtualCamera );
  24534. this.hasOutput = true;
  24535. }
  24536. scene.name = previousName;
  24537. renderer.setMRT( currentMRT );
  24538. renderer.setRenderTarget( currentRenderTarget );
  24539. renderer.autoClear = currentAutoClear;
  24540. material.visible = true;
  24541. _inReflector = false;
  24542. this.forceUpdate = false;
  24543. }
  24544. /**
  24545. * The resolution scale.
  24546. *
  24547. * @deprecated
  24548. * @type {number}
  24549. * @default {1}
  24550. */
  24551. get resolution() {
  24552. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  24553. return this.resolutionScale;
  24554. }
  24555. set resolution( value ) {
  24556. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  24557. this.resolutionScale = value;
  24558. }
  24559. }
  24560. /**
  24561. * TSL function for creating a reflector node.
  24562. *
  24563. * @tsl
  24564. * @function
  24565. * @param {Object} [parameters={}] - An object holding configuration parameters.
  24566. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  24567. * @param {number} [parameters.resolution=1] - The resolution scale.
  24568. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  24569. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  24570. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  24571. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  24572. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  24573. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  24574. * @returns {ReflectorNode}
  24575. */
  24576. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  24577. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  24578. /**
  24579. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  24580. *
  24581. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  24582. *
  24583. * @private
  24584. * @augments BufferGeometry
  24585. */
  24586. class QuadGeometry extends BufferGeometry {
  24587. /**
  24588. * Constructs a new quad geometry.
  24589. *
  24590. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  24591. */
  24592. constructor( flipY = false ) {
  24593. super();
  24594. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  24595. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  24596. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  24597. }
  24598. }
  24599. const _geometry = /*@__PURE__*/ new QuadGeometry();
  24600. /**
  24601. * This module is a helper for passes which need to render a full
  24602. * screen effect which is quite common in context of post processing.
  24603. *
  24604. * The intended usage is to reuse a single quad mesh for rendering
  24605. * subsequent passes by just reassigning the `material` reference.
  24606. *
  24607. * Note: This module can only be used with `WebGPURenderer`.
  24608. *
  24609. * @augments Mesh
  24610. */
  24611. class QuadMesh extends Mesh {
  24612. /**
  24613. * Constructs a new quad mesh.
  24614. *
  24615. * @param {?Material} [material=null] - The material to render the quad mesh with.
  24616. */
  24617. constructor( material = null ) {
  24618. super( _geometry, material );
  24619. /**
  24620. * The camera to render the quad mesh with.
  24621. *
  24622. * @type {OrthographicCamera}
  24623. * @readonly
  24624. */
  24625. this.camera = _camera;
  24626. /**
  24627. * This flag can be used for type testing.
  24628. *
  24629. * @type {boolean}
  24630. * @readonly
  24631. * @default true
  24632. */
  24633. this.isQuadMesh = true;
  24634. }
  24635. /**
  24636. * Async version of `render()`.
  24637. *
  24638. * @async
  24639. * @deprecated
  24640. * @param {Renderer} renderer - The renderer.
  24641. * @return {Promise} A Promise that resolves when the render has been finished.
  24642. */
  24643. async renderAsync( renderer ) {
  24644. warnOnce( 'QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  24645. await renderer.init();
  24646. renderer.render( this, _camera );
  24647. }
  24648. /**
  24649. * Renders the quad mesh
  24650. *
  24651. * @param {Renderer} renderer - The renderer.
  24652. */
  24653. render( renderer ) {
  24654. renderer.render( this, _camera );
  24655. }
  24656. }
  24657. const _size$1 = /*@__PURE__*/ new Vector2();
  24658. /**
  24659. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  24660. * This module is especially relevant in context of post processing where certain nodes require
  24661. * texture input for their effects. With the helper function `convertToTexture()` which is based
  24662. * on this module, the node system can automatically ensure texture input if required.
  24663. *
  24664. * @augments TextureNode
  24665. */
  24666. class RTTNode extends TextureNode {
  24667. static get type() {
  24668. return 'RTTNode';
  24669. }
  24670. /**
  24671. * Constructs a new RTT node.
  24672. *
  24673. * @param {Node} node - The node to render a texture with.
  24674. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24675. * @param {?number} [height=null] - The height of the internal render target.
  24676. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24677. */
  24678. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  24679. const renderTarget = new RenderTarget( width, height, options );
  24680. super( renderTarget.texture, uv$1() );
  24681. /**
  24682. * This flag can be used for type testing.
  24683. *
  24684. * @type {boolean}
  24685. * @readonly
  24686. * @default true
  24687. */
  24688. this.isRTTNode = true;
  24689. /**
  24690. * The node to render a texture with.
  24691. *
  24692. * @type {Node}
  24693. */
  24694. this.node = node;
  24695. /**
  24696. * The width of the internal render target.
  24697. * If not width is applied, the render target is automatically resized.
  24698. *
  24699. * @type {?number}
  24700. * @default null
  24701. */
  24702. this.width = width;
  24703. /**
  24704. * The height of the internal render target.
  24705. *
  24706. * @type {?number}
  24707. * @default null
  24708. */
  24709. this.height = height;
  24710. /**
  24711. * The pixel ratio
  24712. *
  24713. * @type {number}
  24714. * @default 1
  24715. */
  24716. this.pixelRatio = 1;
  24717. /**
  24718. * The render target
  24719. *
  24720. * @type {RenderTarget}
  24721. */
  24722. this.renderTarget = renderTarget;
  24723. /**
  24724. * Whether the texture requires an update or not.
  24725. *
  24726. * @type {boolean}
  24727. * @default true
  24728. */
  24729. this.textureNeedsUpdate = true;
  24730. /**
  24731. * Whether the texture should automatically be updated or not.
  24732. *
  24733. * @type {boolean}
  24734. * @default true
  24735. */
  24736. this.autoUpdate = true;
  24737. /**
  24738. * The node which is used with the quad mesh for RTT.
  24739. *
  24740. * @private
  24741. * @type {Node}
  24742. * @default null
  24743. */
  24744. this._rttNode = null;
  24745. /**
  24746. * The internal quad mesh for RTT.
  24747. *
  24748. * @private
  24749. * @type {QuadMesh}
  24750. */
  24751. this._quadMesh = new QuadMesh( new NodeMaterial() );
  24752. /**
  24753. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  24754. * the texture once per render in its {@link RTTNode#updateBefore} method.
  24755. *
  24756. * @type {string}
  24757. * @default 'render'
  24758. */
  24759. this.updateBeforeType = NodeUpdateType.RENDER;
  24760. }
  24761. /**
  24762. * Whether the internal render target should automatically be resized or not.
  24763. *
  24764. * @type {boolean}
  24765. * @readonly
  24766. * @default true
  24767. */
  24768. get autoResize() {
  24769. return this.width === null;
  24770. }
  24771. setup( builder ) {
  24772. this._rttNode = this.node.context( builder.getSharedContext() );
  24773. this._quadMesh.material.name = 'RTT';
  24774. this._quadMesh.material.needsUpdate = true;
  24775. return super.setup( builder );
  24776. }
  24777. /**
  24778. * Sets the size of the internal render target
  24779. *
  24780. * @param {number} width - The width to set.
  24781. * @param {number} height - The width to set.
  24782. */
  24783. setSize( width, height ) {
  24784. this.width = width;
  24785. this.height = height;
  24786. const effectiveWidth = width * this.pixelRatio;
  24787. const effectiveHeight = height * this.pixelRatio;
  24788. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  24789. this.textureNeedsUpdate = true;
  24790. }
  24791. /**
  24792. * Sets the pixel ratio. This will also resize the render target.
  24793. *
  24794. * @param {number} pixelRatio - The pixel ratio to set.
  24795. */
  24796. setPixelRatio( pixelRatio ) {
  24797. this.pixelRatio = pixelRatio;
  24798. this.setSize( this.width, this.height );
  24799. }
  24800. updateBefore( { renderer } ) {
  24801. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  24802. this.textureNeedsUpdate = false;
  24803. //
  24804. if ( this.autoResize === true ) {
  24805. const pixelRatio = renderer.getPixelRatio();
  24806. const size = renderer.getSize( _size$1 );
  24807. const effectiveWidth = Math.floor( size.width * pixelRatio );
  24808. const effectiveHeight = Math.floor( size.height * pixelRatio );
  24809. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  24810. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  24811. this.textureNeedsUpdate = true;
  24812. }
  24813. }
  24814. //
  24815. let name = 'RTT';
  24816. if ( this.node.name ) {
  24817. name = this.node.name + ' [ ' + name + ' ]';
  24818. }
  24819. this._quadMesh.material.fragmentNode = this._rttNode;
  24820. this._quadMesh.name = name;
  24821. //
  24822. const currentRenderTarget = renderer.getRenderTarget();
  24823. renderer.setRenderTarget( this.renderTarget );
  24824. this._quadMesh.render( renderer );
  24825. renderer.setRenderTarget( currentRenderTarget );
  24826. }
  24827. clone() {
  24828. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  24829. newNode.sampler = this.sampler;
  24830. newNode.referenceNode = this;
  24831. return newNode;
  24832. }
  24833. }
  24834. /**
  24835. * TSL function for creating a RTT node.
  24836. *
  24837. * @tsl
  24838. * @function
  24839. * @param {Node} node - The node to render a texture with.
  24840. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24841. * @param {?number} [height=null] - The height of the internal render target.
  24842. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24843. * @returns {RTTNode}
  24844. */
  24845. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  24846. /**
  24847. * TSL function for converting nodes to textures nodes.
  24848. *
  24849. * @tsl
  24850. * @function
  24851. * @param {Node} node - The node to render a texture with.
  24852. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24853. * @param {?number} [height=null] - The height of the internal render target.
  24854. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24855. * @returns {RTTNode}
  24856. */
  24857. const convertToTexture = ( node, ...params ) => {
  24858. if ( node.isSampleNode || node.isTextureNode ) return node;
  24859. if ( node.isPassNode ) return node.getTextureNode();
  24860. return rtt( node, ...params );
  24861. };
  24862. /**
  24863. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  24864. * depth value and the camera's inverse projection matrix.
  24865. *
  24866. * @tsl
  24867. * @function
  24868. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  24869. * @param {Node<float>} depth - The fragment's depth value.
  24870. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  24871. * @return {Node<vec3>} The fragments position in view space.
  24872. */
  24873. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  24874. let clipSpacePosition;
  24875. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  24876. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  24877. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  24878. } else {
  24879. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  24880. }
  24881. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  24882. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  24883. } );
  24884. /**
  24885. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  24886. * and the camera's projection matrix
  24887. *
  24888. * @tsl
  24889. * @function
  24890. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  24891. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  24892. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  24893. */
  24894. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  24895. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  24896. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  24897. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  24898. } );
  24899. /**
  24900. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  24901. * target is available or if flat surface normals are required.
  24902. *
  24903. * @tsl
  24904. * @function
  24905. * @param {Node<vec2>} uv - The texture coordinate.
  24906. * @param {DepthTexture} depthTexture - The depth texture.
  24907. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  24908. * @return {Node<vec3>} The computed normal vector.
  24909. */
  24910. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  24911. const size = textureSize( textureLoad( depthTexture ) );
  24912. const p = ivec2( uv.mul( size ) ).toVar();
  24913. const c0 = textureLoad( depthTexture, p ).toVar();
  24914. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  24915. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  24916. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  24917. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  24918. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  24919. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  24920. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  24921. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  24922. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  24923. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  24924. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  24925. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  24926. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  24927. 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 ) ) );
  24928. 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 ) ) );
  24929. return normalize( cross( dpdx, dpdy ) );
  24930. } );
  24931. /**
  24932. * Interleaved Gradient Noise (IGN) from Jimenez 2014.
  24933. *
  24934. * IGN has "low discrepancy" resulting in evenly distributed samples. It's superior compared to
  24935. * default white noise, blue noise or Bayer.
  24936. *
  24937. * References:
  24938. * - {@link https://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare/}
  24939. * - {@link https://blog.demofox.org/2022/01/01/interleaved-gradient-noise-a-different-kind-of-low-discrepancy-sequence/}
  24940. *
  24941. * @tsl
  24942. * @function
  24943. * @param {Node<vec2>} position - The input position, usually screen coordinates.
  24944. * @return {Node<float>} The noise value.
  24945. */
  24946. const interleavedGradientNoise = Fn( ( [ position ] ) => {
  24947. return fract( float( 52.9829189 ).mul( fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ) );
  24948. } ).setLayout( {
  24949. name: 'interleavedGradientNoise',
  24950. type: 'float',
  24951. inputs: [
  24952. { name: 'position', type: 'vec2' }
  24953. ]
  24954. } );
  24955. /**
  24956. * Class representing a node that samples a value using a provided callback function.
  24957. *
  24958. * @extends Node
  24959. */
  24960. class SampleNode extends Node {
  24961. /**
  24962. * Returns the type of the node.
  24963. *
  24964. * @type {string}
  24965. * @readonly
  24966. * @static
  24967. */
  24968. static get type() {
  24969. return 'SampleNode';
  24970. }
  24971. /**
  24972. * Creates an instance of SampleNode.
  24973. *
  24974. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  24975. * @param {?Node<vec2>} [uvNode=null] - The UV node to be used in the texture sampling.
  24976. */
  24977. constructor( callback, uvNode = null ) {
  24978. super();
  24979. this.callback = callback;
  24980. /**
  24981. * Represents the texture coordinates.
  24982. *
  24983. * @type {?Node<vec2|vec3>}
  24984. * @default null
  24985. */
  24986. this.uvNode = uvNode;
  24987. /**
  24988. * This flag can be used for type testing.
  24989. *
  24990. * @type {boolean}
  24991. * @readonly
  24992. * @default true
  24993. */
  24994. this.isSampleNode = true;
  24995. }
  24996. /**
  24997. * Sets up the node by sampling with the default UV accessor.
  24998. *
  24999. * @returns {Node} The result of the callback function when called with the UV node.
  25000. */
  25001. setup() {
  25002. return this.sample( uv$1() );
  25003. }
  25004. /**
  25005. * Calls the callback function with the provided UV node.
  25006. *
  25007. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  25008. * @returns {Node} The result of the callback function.
  25009. */
  25010. sample( uv ) {
  25011. return this.callback( uv );
  25012. }
  25013. }
  25014. /**
  25015. * Helper function to create a SampleNode wrapped as a node object.
  25016. *
  25017. * @function
  25018. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  25019. * @param {?Node<vec2>} [uv=null] - The UV node to be used in the texture sampling.
  25020. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  25021. */
  25022. const sample = ( callback, uv = null ) => nodeObject( new SampleNode( callback, nodeObject( uv ) ) );
  25023. /**
  25024. * EventNode is a node that executes a callback during specific update phases.
  25025. *
  25026. * @augments Node
  25027. */
  25028. class EventNode extends Node {
  25029. static get type() {
  25030. return 'EventNode';
  25031. }
  25032. /**
  25033. * Creates an EventNode.
  25034. *
  25035. * @param {string} eventType - The type of event
  25036. * @param {Function} callback - The callback to execute on update.
  25037. */
  25038. constructor( eventType, callback ) {
  25039. super( 'void' );
  25040. this.eventType = eventType;
  25041. this.callback = callback;
  25042. if ( eventType === EventNode.OBJECT ) {
  25043. this.updateType = NodeUpdateType.OBJECT;
  25044. } else if ( eventType === EventNode.MATERIAL ) {
  25045. this.updateType = NodeUpdateType.RENDER;
  25046. }
  25047. }
  25048. update( frame ) {
  25049. this.callback( frame );
  25050. }
  25051. }
  25052. EventNode.OBJECT = 'object';
  25053. EventNode.MATERIAL = 'material';
  25054. /**
  25055. * Helper to create an EventNode and add it to the stack.
  25056. *
  25057. * @param {string} type - The event type.
  25058. * @param {Function} callback - The callback function.
  25059. * @returns {EventNode}
  25060. */
  25061. const createEvent = ( type, callback ) => nodeObject( new EventNode( type, callback ) ).toStack();
  25062. /**
  25063. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  25064. *
  25065. * 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.
  25066. *
  25067. * @param {Function} callback - The callback function.
  25068. * @returns {EventNode}
  25069. */
  25070. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  25071. /**
  25072. * Creates an event that triggers a function when the first object that uses the material is rendered.
  25073. *
  25074. * 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.
  25075. *
  25076. * @param {Function} callback - The callback function.
  25077. * @returns {EventNode}
  25078. */
  25079. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  25080. /**
  25081. * This special type of instanced buffer attribute is intended for compute shaders.
  25082. * In earlier three.js versions it was only possible to update attribute data
  25083. * on the CPU via JavaScript and then upload the data to the GPU. With the
  25084. * new material system and renderer it is now possible to use compute shaders
  25085. * to compute the data for an attribute more efficiently on the GPU.
  25086. *
  25087. * The idea is to create an instance of this class and provide it as an input
  25088. * to {@link StorageBufferNode}.
  25089. *
  25090. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  25091. *
  25092. * @augments InstancedBufferAttribute
  25093. */
  25094. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  25095. /**
  25096. * Constructs a new storage instanced buffer attribute.
  25097. *
  25098. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  25099. * The subsequent parameters are then obsolete.
  25100. * @param {number} itemSize - The item size.
  25101. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  25102. */
  25103. constructor( count, itemSize, typeClass = Float32Array ) {
  25104. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  25105. super( array, itemSize );
  25106. /**
  25107. * This flag can be used for type testing.
  25108. *
  25109. * @type {boolean}
  25110. * @readonly
  25111. * @default true
  25112. */
  25113. this.isStorageInstancedBufferAttribute = true;
  25114. }
  25115. }
  25116. /**
  25117. * This special type of buffer attribute is intended for compute shaders.
  25118. * In earlier three.js versions it was only possible to update attribute data
  25119. * on the CPU via JavaScript and then upload the data to the GPU. With the
  25120. * new material system and renderer it is now possible to use compute shaders
  25121. * to compute the data for an attribute more efficiently on the GPU.
  25122. *
  25123. * The idea is to create an instance of this class and provide it as an input
  25124. * to {@link StorageBufferNode}.
  25125. *
  25126. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  25127. *
  25128. * @augments BufferAttribute
  25129. */
  25130. class StorageBufferAttribute extends BufferAttribute {
  25131. /**
  25132. * Constructs a new storage buffer attribute.
  25133. *
  25134. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  25135. * The subsequent parameters are then obsolete.
  25136. * @param {number} itemSize - The item size.
  25137. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  25138. */
  25139. constructor( count, itemSize, typeClass = Float32Array ) {
  25140. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  25141. super( array, itemSize );
  25142. /**
  25143. * This flag can be used for type testing.
  25144. *
  25145. * @type {boolean}
  25146. * @readonly
  25147. * @default true
  25148. */
  25149. this.isStorageBufferAttribute = true;
  25150. }
  25151. }
  25152. /**
  25153. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  25154. *
  25155. * @tsl
  25156. * @function
  25157. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  25158. * @param {string|Struct} [type='float'] - The data type.
  25159. * @returns {StorageBufferNode}
  25160. */
  25161. const attributeArray = ( count, type = 'float' ) => {
  25162. let itemSize, typedArray;
  25163. if ( type.isStruct === true ) {
  25164. itemSize = type.layout.getLength();
  25165. typedArray = getTypedArrayFromType( 'float' );
  25166. } else {
  25167. itemSize = getLengthFromType( type );
  25168. typedArray = getTypedArrayFromType( type );
  25169. }
  25170. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  25171. const node = storage( buffer, type, count );
  25172. return node;
  25173. };
  25174. /**
  25175. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  25176. *
  25177. * @tsl
  25178. * @function
  25179. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  25180. * @param {string|Struct} [type='float'] - The data type.
  25181. * @returns {StorageBufferNode}
  25182. */
  25183. const instancedArray = ( count, type = 'float' ) => {
  25184. let itemSize, typedArray;
  25185. if ( type.isStruct === true ) {
  25186. itemSize = type.layout.getLength();
  25187. typedArray = getTypedArrayFromType( 'float' );
  25188. } else {
  25189. itemSize = getLengthFromType( type );
  25190. typedArray = getTypedArrayFromType( type );
  25191. }
  25192. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  25193. const node = storage( buffer, type, count );
  25194. return node;
  25195. };
  25196. /**
  25197. * A node for representing the uv coordinates of points.
  25198. *
  25199. * Can only be used with a WebGL backend. In WebGPU, point
  25200. * primitives always have the size of one pixel and can thus
  25201. * can't be used as sprite-like objects that display textures.
  25202. *
  25203. * @augments Node
  25204. */
  25205. class PointUVNode extends Node {
  25206. static get type() {
  25207. return 'PointUVNode';
  25208. }
  25209. /**
  25210. * Constructs a new point uv node.
  25211. */
  25212. constructor() {
  25213. super( 'vec2' );
  25214. /**
  25215. * This flag can be used for type testing.
  25216. *
  25217. * @type {boolean}
  25218. * @readonly
  25219. * @default true
  25220. */
  25221. this.isPointUVNode = true;
  25222. }
  25223. generate( /*builder*/ ) {
  25224. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  25225. }
  25226. }
  25227. /**
  25228. * TSL object that represents the uv coordinates of points.
  25229. *
  25230. * @tsl
  25231. * @type {PointUVNode}
  25232. */
  25233. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  25234. const _e1 = /*@__PURE__*/ new Euler();
  25235. const _m1 = /*@__PURE__*/ new Matrix4();
  25236. /**
  25237. * This module allows access to a collection of scene properties. The following predefined TSL objects
  25238. * are available for easier use:
  25239. *
  25240. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  25241. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  25242. * - `backgroundRotation`: A node that represents the scene's background rotation.
  25243. *
  25244. * @augments Node
  25245. */
  25246. class SceneNode extends Node {
  25247. static get type() {
  25248. return 'SceneNode';
  25249. }
  25250. /**
  25251. * Constructs a new scene node.
  25252. *
  25253. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  25254. * @param {?Scene} [scene=null] - A reference to the scene.
  25255. */
  25256. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  25257. super();
  25258. /**
  25259. * The scope defines the type of scene property that is accessed.
  25260. *
  25261. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  25262. */
  25263. this.scope = scope;
  25264. /**
  25265. * A reference to the scene that is going to be accessed.
  25266. *
  25267. * @type {?Scene}
  25268. * @default null
  25269. */
  25270. this.scene = scene;
  25271. }
  25272. /**
  25273. * Depending on the scope, the method returns a different type of node that represents
  25274. * the respective scene property.
  25275. *
  25276. * @param {NodeBuilder} builder - The current node builder.
  25277. * @return {Node} The output node.
  25278. */
  25279. setup( builder ) {
  25280. const scope = this.scope;
  25281. const scene = this.scene !== null ? this.scene : builder.scene;
  25282. let output;
  25283. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  25284. output = reference( 'backgroundBlurriness', 'float', scene );
  25285. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  25286. output = reference( 'backgroundIntensity', 'float', scene );
  25287. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  25288. output = uniform( 'mat4' ).setName( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  25289. const background = scene.background;
  25290. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  25291. _e1.copy( scene.backgroundRotation );
  25292. // accommodate left-handed frame
  25293. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  25294. _m1.makeRotationFromEuler( _e1 );
  25295. } else {
  25296. _m1.identity();
  25297. }
  25298. return _m1;
  25299. } );
  25300. } else {
  25301. error( 'SceneNode: Unknown scope:', scope );
  25302. }
  25303. return output;
  25304. }
  25305. }
  25306. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  25307. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  25308. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  25309. /**
  25310. * TSL object that represents the scene's background blurriness.
  25311. *
  25312. * @tsl
  25313. * @type {SceneNode}
  25314. */
  25315. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  25316. /**
  25317. * TSL object that represents the scene's background intensity.
  25318. *
  25319. * @tsl
  25320. * @type {SceneNode}
  25321. */
  25322. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  25323. /**
  25324. * TSL object that represents the scene's background rotation.
  25325. *
  25326. * @tsl
  25327. * @type {SceneNode}
  25328. */
  25329. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  25330. /**
  25331. * This special version of a texture node can be used to
  25332. * write data into a storage texture with a compute shader.
  25333. *
  25334. * ```js
  25335. * const storageTexture = new THREE.StorageTexture( width, height );
  25336. *
  25337. * const computeTexture = Fn( ( { storageTexture } ) => {
  25338. *
  25339. * const posX = instanceIndex.mod( width );
  25340. * const posY = instanceIndex.div( width );
  25341. * const indexUV = uvec2( posX, posY );
  25342. *
  25343. * // generate RGB values
  25344. *
  25345. * const r = 1;
  25346. * const g = 1;
  25347. * const b = 1;
  25348. *
  25349. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  25350. *
  25351. * } );
  25352. *
  25353. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  25354. * renderer.computeAsync( computeNode );
  25355. * ```
  25356. *
  25357. * This node can only be used with a WebGPU backend.
  25358. *
  25359. * @augments TextureNode
  25360. */
  25361. class StorageTextureNode extends TextureNode {
  25362. static get type() {
  25363. return 'StorageTextureNode';
  25364. }
  25365. /**
  25366. * Constructs a new storage texture node.
  25367. *
  25368. * @param {StorageTexture} value - The storage texture.
  25369. * @param {Node<vec2|vec3>} uvNode - The uv node.
  25370. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  25371. */
  25372. constructor( value, uvNode, storeNode = null ) {
  25373. super( value, uvNode );
  25374. /**
  25375. * The value node that should be stored in the texture.
  25376. *
  25377. * @type {?Node}
  25378. * @default null
  25379. */
  25380. this.storeNode = storeNode;
  25381. /**
  25382. * The mip level to write to for storage textures.
  25383. *
  25384. * @type {number}
  25385. * @default 0
  25386. */
  25387. this.mipLevel = 0;
  25388. /**
  25389. * This flag can be used for type testing.
  25390. *
  25391. * @type {boolean}
  25392. * @readonly
  25393. * @default true
  25394. */
  25395. this.isStorageTextureNode = true;
  25396. /**
  25397. * The access type of the texture node.
  25398. *
  25399. * @type {string}
  25400. * @default 'writeOnly'
  25401. */
  25402. this.access = NodeAccess.WRITE_ONLY;
  25403. }
  25404. /**
  25405. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  25406. *
  25407. * @param {NodeBuilder} builder - The current node builder.
  25408. * @return {string} The input type.
  25409. */
  25410. getInputType( /*builder*/ ) {
  25411. return 'storageTexture';
  25412. }
  25413. setup( builder ) {
  25414. super.setup( builder );
  25415. const properties = builder.getNodeProperties( this );
  25416. properties.storeNode = this.storeNode;
  25417. return properties;
  25418. }
  25419. /**
  25420. * Defines the node access.
  25421. *
  25422. * @param {string} value - The node access.
  25423. * @return {StorageTextureNode} A reference to this node.
  25424. */
  25425. setAccess( value ) {
  25426. this.access = value;
  25427. return this;
  25428. }
  25429. /**
  25430. * Sets the mip level to write to.
  25431. *
  25432. * @param {number} level - The mip level.
  25433. * @return {StorageTextureNode} A reference to this node.
  25434. */
  25435. setMipLevel( level ) {
  25436. this.mipLevel = level;
  25437. return this;
  25438. }
  25439. /**
  25440. * Generates the code snippet of the storage node. If no `storeNode`
  25441. * is defined, the texture node is generated as normal texture.
  25442. *
  25443. * @param {NodeBuilder} builder - The current node builder.
  25444. * @param {string} output - The current output.
  25445. * @return {string} The generated code snippet.
  25446. */
  25447. generate( builder, output ) {
  25448. let snippet;
  25449. if ( this.storeNode !== null ) {
  25450. snippet = this.generateStore( builder );
  25451. } else {
  25452. snippet = super.generate( builder, output );
  25453. }
  25454. return snippet;
  25455. }
  25456. /**
  25457. * Convenience method for configuring a read/write node access.
  25458. *
  25459. * @return {StorageTextureNode} A reference to this node.
  25460. */
  25461. toReadWrite() {
  25462. return this.setAccess( NodeAccess.READ_WRITE );
  25463. }
  25464. /**
  25465. * Convenience method for configuring a read-only node access.
  25466. *
  25467. * @return {StorageTextureNode} A reference to this node.
  25468. */
  25469. toReadOnly() {
  25470. return this.setAccess( NodeAccess.READ_ONLY );
  25471. }
  25472. /**
  25473. * Convenience method for configuring a write-only node access.
  25474. *
  25475. * @return {StorageTextureNode} A reference to this node.
  25476. */
  25477. toWriteOnly() {
  25478. return this.setAccess( NodeAccess.WRITE_ONLY );
  25479. }
  25480. /**
  25481. * Generates the code snippet of the storage texture node.
  25482. *
  25483. * @param {NodeBuilder} builder - The current node builder.
  25484. */
  25485. generateStore( builder ) {
  25486. const properties = builder.getNodeProperties( this );
  25487. const { uvNode, storeNode, depthNode } = properties;
  25488. const textureProperty = super.generate( builder, 'property' );
  25489. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  25490. const storeSnippet = storeNode.build( builder, 'vec4' );
  25491. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  25492. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  25493. builder.addLineFlowCode( snippet, this );
  25494. }
  25495. clone() {
  25496. const newNode = super.clone();
  25497. newNode.storeNode = this.storeNode;
  25498. newNode.mipLevel = this.mipLevel;
  25499. return newNode;
  25500. }
  25501. }
  25502. /**
  25503. * TSL function for creating a storage texture node.
  25504. *
  25505. * @tsl
  25506. * @function
  25507. * @param {StorageTexture} value - The storage texture.
  25508. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  25509. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  25510. * @returns {StorageTextureNode}
  25511. */
  25512. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  25513. /**
  25514. * TODO: Explain difference to `storageTexture()`.
  25515. *
  25516. * @tsl
  25517. * @function
  25518. * @param {StorageTexture} value - The storage texture.
  25519. * @param {Node<vec2|vec3>} uvNode - The uv node.
  25520. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  25521. * @returns {StorageTextureNode}
  25522. */
  25523. const textureStore = ( value, uvNode, storeNode ) => {
  25524. const node = storageTexture( value, uvNode, storeNode );
  25525. if ( storeNode !== null ) node.toStack();
  25526. return node;
  25527. };
  25528. const normal = Fn( ( { texture, uv } ) => {
  25529. const epsilon = 0.0001;
  25530. const ret = vec3().toVar();
  25531. If( uv.x.lessThan( epsilon ), () => {
  25532. ret.assign( vec3( 1, 0, 0 ) );
  25533. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  25534. ret.assign( vec3( 0, 1, 0 ) );
  25535. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  25536. ret.assign( vec3( 0, 0, 1 ) );
  25537. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  25538. ret.assign( vec3( -1, 0, 0 ) );
  25539. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  25540. ret.assign( vec3( 0, -1, 0 ) );
  25541. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  25542. ret.assign( vec3( 0, 0, -1 ) );
  25543. } ).Else( () => {
  25544. const step = 0.01;
  25545. 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 );
  25546. 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 );
  25547. 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 );
  25548. ret.assign( vec3( x, y, z ) );
  25549. } );
  25550. return ret.normalize();
  25551. } );
  25552. /**
  25553. * This type of uniform node represents a 3D texture.
  25554. *
  25555. * @augments TextureNode
  25556. */
  25557. class Texture3DNode extends TextureNode {
  25558. static get type() {
  25559. return 'Texture3DNode';
  25560. }
  25561. /**
  25562. * Constructs a new 3D texture node.
  25563. *
  25564. * @param {Data3DTexture} value - The 3D texture.
  25565. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  25566. * @param {?Node<int>} [levelNode=null] - The level node.
  25567. */
  25568. constructor( value, uvNode = null, levelNode = null ) {
  25569. super( value, uvNode, levelNode );
  25570. /**
  25571. * This flag can be used for type testing.
  25572. *
  25573. * @type {boolean}
  25574. * @readonly
  25575. * @default true
  25576. */
  25577. this.isTexture3DNode = true;
  25578. }
  25579. /**
  25580. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  25581. *
  25582. * @param {NodeBuilder} builder - The current node builder.
  25583. * @return {string} The input type.
  25584. */
  25585. getInputType( /*builder*/ ) {
  25586. return 'texture3D';
  25587. }
  25588. /**
  25589. * Returns a default uv node which is in context of 3D textures a three-dimensional
  25590. * uv node.
  25591. *
  25592. * @return {Node<vec3>} The default uv node.
  25593. */
  25594. getDefaultUV() {
  25595. return vec3( 0.5, 0.5, 0.5 );
  25596. }
  25597. /**
  25598. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  25599. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  25600. *
  25601. * @param {boolean} value - The update toggle.
  25602. */
  25603. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  25604. /**
  25605. * Overwrites the default implementation to return the unmodified uv node.
  25606. *
  25607. * @param {NodeBuilder} builder - The current node builder.
  25608. * @param {Node} uvNode - The uv node to setup.
  25609. * @return {Node} The unmodified uv node.
  25610. */
  25611. setupUV( builder, uvNode ) {
  25612. const texture = this.value;
  25613. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  25614. if ( this.sampler ) {
  25615. uvNode = uvNode.flipY();
  25616. } else {
  25617. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  25618. }
  25619. }
  25620. return uvNode;
  25621. }
  25622. /**
  25623. * Generates the uv code snippet.
  25624. *
  25625. * @param {NodeBuilder} builder - The current node builder.
  25626. * @param {Node} uvNode - The uv node to generate code for.
  25627. * @return {string} The generated code snippet.
  25628. */
  25629. generateUV( builder, uvNode ) {
  25630. return uvNode.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  25631. }
  25632. /**
  25633. * Generates the offset code snippet.
  25634. *
  25635. * @param {NodeBuilder} builder - The current node builder.
  25636. * @param {Node} offsetNode - The offset node to generate code for.
  25637. * @return {string} The generated code snippet.
  25638. */
  25639. generateOffset( builder, offsetNode ) {
  25640. return offsetNode.build( builder, 'ivec3' );
  25641. }
  25642. /**
  25643. * TODO.
  25644. *
  25645. * @param {Node<vec3>} uvNode - The uv node .
  25646. * @return {Node<vec3>} TODO.
  25647. */
  25648. normal( uvNode ) {
  25649. return normal( { texture: this, uv: uvNode } );
  25650. }
  25651. }
  25652. /**
  25653. * TSL function for creating a 3D texture node.
  25654. *
  25655. * @tsl
  25656. * @function
  25657. * @param {Data3DTexture} value - The 3D texture.
  25658. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  25659. * @param {?Node<int>} [levelNode=null] - The level node.
  25660. * @returns {Texture3DNode}
  25661. */
  25662. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  25663. /**
  25664. * A special type of reference node that allows to link values in
  25665. * `userData` fields to node objects.
  25666. * ```js
  25667. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  25668. *
  25669. * const material = new THREE.SpriteNodeMaterial();
  25670. * material.rotationNode = userData( 'rotation', 'float' );
  25671. * ```
  25672. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  25673. * will automatically be updated when the `rotation` user data field changes.
  25674. *
  25675. * @augments ReferenceNode
  25676. */
  25677. class UserDataNode extends ReferenceNode {
  25678. static get type() {
  25679. return 'UserDataNode';
  25680. }
  25681. /**
  25682. * Constructs a new user data node.
  25683. *
  25684. * @param {string} property - The property name that should be referenced by the node.
  25685. * @param {string} inputType - The node data type of the reference.
  25686. * @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.
  25687. */
  25688. constructor( property, inputType, userData = null ) {
  25689. super( property, inputType, userData );
  25690. /**
  25691. * A reference to the `userData` object. If not provided, the `userData`
  25692. * property of the 3D object that uses the node material is evaluated.
  25693. *
  25694. * @type {?Object}
  25695. * @default null
  25696. */
  25697. this.userData = userData;
  25698. }
  25699. /**
  25700. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  25701. * `userData` field.
  25702. *
  25703. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  25704. * @return {Object} A reference to the `userData` field.
  25705. */
  25706. updateReference( state ) {
  25707. this.reference = this.userData !== null ? this.userData : state.object.userData;
  25708. return this.reference;
  25709. }
  25710. }
  25711. /**
  25712. * TSL function for creating a user data node.
  25713. *
  25714. * @tsl
  25715. * @function
  25716. * @param {string} name - The property name that should be referenced by the node.
  25717. * @param {string} inputType - The node data type of the reference.
  25718. * @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.
  25719. * @returns {UserDataNode}
  25720. */
  25721. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  25722. const _objectData = new WeakMap();
  25723. /**
  25724. * A node for representing motion or velocity vectors. Foundation
  25725. * for advanced post processing effects like motion blur or TRAA.
  25726. *
  25727. * The node keeps track of the model, view and projection matrices
  25728. * of the previous frame and uses them to compute offsets in NDC space.
  25729. * These offsets represent the final velocity.
  25730. *
  25731. * @augments TempNode
  25732. */
  25733. class VelocityNode extends TempNode {
  25734. static get type() {
  25735. return 'VelocityNode';
  25736. }
  25737. /**
  25738. * Constructs a new vertex color node.
  25739. */
  25740. constructor() {
  25741. super( 'vec2' );
  25742. /**
  25743. * The current projection matrix.
  25744. *
  25745. * @type {?Matrix4}
  25746. * @default null
  25747. */
  25748. this.projectionMatrix = null;
  25749. /**
  25750. * Overwritten since velocity nodes are updated per object.
  25751. *
  25752. * @type {string}
  25753. * @default 'object'
  25754. */
  25755. this.updateType = NodeUpdateType.OBJECT;
  25756. /**
  25757. * Overwritten since velocity nodes save data after the update.
  25758. *
  25759. * @type {string}
  25760. * @default 'object'
  25761. */
  25762. this.updateAfterType = NodeUpdateType.OBJECT;
  25763. /**
  25764. * Uniform node representing the previous model matrix in world space.
  25765. *
  25766. * @type {UniformNode<mat4>}
  25767. * @default null
  25768. */
  25769. this.previousModelWorldMatrix = uniform( new Matrix4() );
  25770. /**
  25771. * Uniform node representing the previous projection matrix.
  25772. *
  25773. * @type {UniformNode<mat4>}
  25774. * @default null
  25775. */
  25776. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  25777. /**
  25778. * Uniform node representing the previous view matrix.
  25779. *
  25780. * @type {UniformNode<mat4>}
  25781. * @default null
  25782. */
  25783. this.previousCameraViewMatrix = uniform( new Matrix4() );
  25784. }
  25785. /**
  25786. * Sets the given projection matrix.
  25787. *
  25788. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  25789. */
  25790. setProjectionMatrix( projectionMatrix ) {
  25791. this.projectionMatrix = projectionMatrix;
  25792. }
  25793. /**
  25794. * Updates velocity specific uniforms.
  25795. *
  25796. * @param {NodeFrame} frame - A reference to the current node frame.
  25797. */
  25798. update( { frameId, camera, object } ) {
  25799. const previousModelMatrix = getPreviousMatrix( object );
  25800. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  25801. //
  25802. const cameraData = getData( camera );
  25803. if ( cameraData.frameId !== frameId ) {
  25804. cameraData.frameId = frameId;
  25805. if ( cameraData.previousProjectionMatrix === undefined ) {
  25806. cameraData.previousProjectionMatrix = new Matrix4();
  25807. cameraData.previousCameraViewMatrix = new Matrix4();
  25808. cameraData.currentProjectionMatrix = new Matrix4();
  25809. cameraData.currentCameraViewMatrix = new Matrix4();
  25810. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  25811. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  25812. } else {
  25813. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  25814. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  25815. }
  25816. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  25817. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  25818. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  25819. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  25820. }
  25821. }
  25822. /**
  25823. * Overwritten to updated velocity specific uniforms.
  25824. *
  25825. * @param {NodeFrame} frame - A reference to the current node frame.
  25826. */
  25827. updateAfter( { object } ) {
  25828. getPreviousMatrix( object ).copy( object.matrixWorld );
  25829. }
  25830. /**
  25831. * Implements the velocity computation based on the previous and current vertex data.
  25832. *
  25833. * @param {NodeBuilder} builder - A reference to the current node builder.
  25834. * @return {Node<vec2>} The motion vector.
  25835. */
  25836. setup( /*builder*/ ) {
  25837. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  25838. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  25839. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  25840. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  25841. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  25842. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  25843. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  25844. return velocity;
  25845. }
  25846. }
  25847. function getData( object ) {
  25848. let objectData = _objectData.get( object );
  25849. if ( objectData === undefined ) {
  25850. objectData = {};
  25851. _objectData.set( object, objectData );
  25852. }
  25853. return objectData;
  25854. }
  25855. function getPreviousMatrix( object, index = 0 ) {
  25856. const objectData = getData( object );
  25857. let matrix = objectData[ index ];
  25858. if ( matrix === undefined ) {
  25859. objectData[ index ] = matrix = new Matrix4();
  25860. objectData[ index ].copy( object.matrixWorld );
  25861. }
  25862. return matrix;
  25863. }
  25864. /**
  25865. * TSL object that represents the velocity of a render pass.
  25866. *
  25867. * @tsl
  25868. * @type {VelocityNode}
  25869. */
  25870. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  25871. /**
  25872. * Computes a grayscale value for the given RGB color value.
  25873. *
  25874. * @tsl
  25875. * @function
  25876. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  25877. * @return {Node<vec3>} The grayscale color.
  25878. */
  25879. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  25880. return luminance( color.rgb );
  25881. } );
  25882. /**
  25883. * Super-saturates or desaturates the given RGB color.
  25884. *
  25885. * @tsl
  25886. * @function
  25887. * @param {Node<vec3>} color - The input color.
  25888. * @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.
  25889. * @return {Node<vec3>} The saturated color.
  25890. */
  25891. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  25892. return adjustment.mix( luminance( color.rgb ), color.rgb );
  25893. } );
  25894. /**
  25895. * Selectively enhance the intensity of less saturated RGB colors. Can result
  25896. * in a more natural and visually appealing image with enhanced color depth
  25897. * compared to {@link ColorAdjustment#saturation}.
  25898. *
  25899. * @tsl
  25900. * @function
  25901. * @param {Node<vec3>} color - The input color.
  25902. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  25903. * @return {Node<vec3>} The updated color.
  25904. */
  25905. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  25906. const average = add( color.r, color.g, color.b ).div( 3.0 );
  25907. const mx = color.r.max( color.g.max( color.b ) );
  25908. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  25909. return mix( color.rgb, mx, amt );
  25910. } );
  25911. /**
  25912. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  25913. *
  25914. * @tsl
  25915. * @function
  25916. * @param {Node<vec3>} color - The input color.
  25917. * @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.
  25918. * @return {Node<vec3>} The updated color.
  25919. */
  25920. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  25921. const k = vec3( 0.57735, 0.57735, 0.57735 );
  25922. const cosAngle = adjustment.cos();
  25923. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  25924. } );
  25925. /**
  25926. * Computes the luminance for the given RGB color value.
  25927. *
  25928. * @tsl
  25929. * @function
  25930. * @param {Node<vec3>} color - The color value to compute the luminance for.
  25931. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  25932. * @return {Node<float>} The luminance.
  25933. */
  25934. const luminance = (
  25935. color,
  25936. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  25937. ) => dot( color, luminanceCoefficients );
  25938. /**
  25939. * Color Decision List (CDL) v1.2
  25940. *
  25941. * Compact representation of color grading information, defined by slope, offset, power, and
  25942. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  25943. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  25944. *
  25945. * @tsl
  25946. * @function
  25947. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  25948. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  25949. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  25950. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  25951. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  25952. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  25953. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  25954. *
  25955. * References:
  25956. * - ASC CDL v1.2
  25957. * - {@link https://blender.stackexchange.com/a/55239/43930}
  25958. * - {@link https://docs.acescentral.com/specifications/acescc/}
  25959. */
  25960. const cdl = /*@__PURE__*/ Fn( ( [
  25961. color,
  25962. slope = vec3( 1 ),
  25963. offset = vec3( 0 ),
  25964. power = vec3( 1 ),
  25965. saturation = float( 1 ),
  25966. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  25967. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  25968. ] ) => {
  25969. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  25970. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  25971. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  25972. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  25973. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  25974. const pv = v.pow( power ).toVar();
  25975. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  25976. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  25977. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  25978. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  25979. return vec4( v.rgb, color.a );
  25980. } );
  25981. /**
  25982. * Represents a posterize effect which reduces the number of colors
  25983. * in an image, resulting in a more blocky and stylized appearance.
  25984. *
  25985. * @augments TempNode
  25986. */
  25987. class PosterizeNode extends TempNode {
  25988. static get type() {
  25989. return 'PosterizeNode';
  25990. }
  25991. /**
  25992. * Constructs a new posterize node.
  25993. *
  25994. * @param {Node} sourceNode - The input color.
  25995. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25996. */
  25997. constructor( sourceNode, stepsNode ) {
  25998. super();
  25999. /**
  26000. * The input color.
  26001. *
  26002. * @type {Node}
  26003. */
  26004. this.sourceNode = sourceNode;
  26005. /**
  26006. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  26007. *
  26008. * @type {Node}
  26009. */
  26010. this.stepsNode = stepsNode;
  26011. }
  26012. setup() {
  26013. const { sourceNode, stepsNode } = this;
  26014. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  26015. }
  26016. }
  26017. /**
  26018. * TSL function for creating a posterize node.
  26019. *
  26020. * @tsl
  26021. * @function
  26022. * @param {Node} sourceNode - The input color.
  26023. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  26024. * @returns {PosterizeNode}
  26025. */
  26026. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  26027. const _size = /*@__PURE__*/ new Vector2();
  26028. /**
  26029. * Represents the texture of a pass node.
  26030. *
  26031. * @augments TextureNode
  26032. */
  26033. class PassTextureNode extends TextureNode {
  26034. static get type() {
  26035. return 'PassTextureNode';
  26036. }
  26037. /**
  26038. * Constructs a new pass texture node.
  26039. *
  26040. * @param {PassNode} passNode - The pass node.
  26041. * @param {Texture} texture - The output texture.
  26042. */
  26043. constructor( passNode, texture ) {
  26044. super( texture );
  26045. /**
  26046. * A reference to the pass node.
  26047. *
  26048. * @type {PassNode}
  26049. */
  26050. this.passNode = passNode;
  26051. this.setUpdateMatrix( false );
  26052. }
  26053. setup( builder ) {
  26054. this.passNode.build( builder );
  26055. return super.setup( builder );
  26056. }
  26057. clone() {
  26058. return new this.constructor( this.passNode, this.value );
  26059. }
  26060. }
  26061. /**
  26062. * An extension of `PassTextureNode` which allows to manage more than one
  26063. * internal texture. Relevant for the `getPreviousTexture()` related API.
  26064. *
  26065. * @augments PassTextureNode
  26066. */
  26067. class PassMultipleTextureNode extends PassTextureNode {
  26068. static get type() {
  26069. return 'PassMultipleTextureNode';
  26070. }
  26071. /**
  26072. * Constructs a new pass texture node.
  26073. *
  26074. * @param {PassNode} passNode - The pass node.
  26075. * @param {string} textureName - The output texture name.
  26076. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  26077. */
  26078. constructor( passNode, textureName, previousTexture = false ) {
  26079. // null is passed to the super call since this class does not
  26080. // use an external texture for rendering pass data into. Instead
  26081. // the texture is managed by the pass node itself
  26082. super( passNode, null );
  26083. /**
  26084. * The output texture name.
  26085. *
  26086. * @type {string}
  26087. */
  26088. this.textureName = textureName;
  26089. /**
  26090. * Whether previous frame data should be used or not.
  26091. *
  26092. * @type {boolean}
  26093. */
  26094. this.previousTexture = previousTexture;
  26095. }
  26096. /**
  26097. * Updates the texture reference of this node.
  26098. */
  26099. updateTexture() {
  26100. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  26101. }
  26102. setup( builder ) {
  26103. this.updateTexture();
  26104. return super.setup( builder );
  26105. }
  26106. clone() {
  26107. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  26108. newNode.uvNode = this.uvNode;
  26109. newNode.levelNode = this.levelNode;
  26110. newNode.biasNode = this.biasNode;
  26111. newNode.sampler = this.sampler;
  26112. newNode.depthNode = this.depthNode;
  26113. newNode.compareNode = this.compareNode;
  26114. newNode.gradNode = this.gradNode;
  26115. newNode.offsetNode = this.offsetNode;
  26116. return newNode;
  26117. }
  26118. }
  26119. /**
  26120. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  26121. * This pass produces a render for the given scene and camera and can provide multiple outputs
  26122. * via MRT for further processing.
  26123. *
  26124. * ```js
  26125. * const postProcessing = new PostProcessing( renderer );
  26126. *
  26127. * const scenePass = pass( scene, camera );
  26128. *
  26129. * postProcessing.outputNode = scenePass;
  26130. * ```
  26131. *
  26132. * @augments TempNode
  26133. */
  26134. class PassNode extends TempNode {
  26135. static get type() {
  26136. return 'PassNode';
  26137. }
  26138. /**
  26139. * Constructs a new pass node.
  26140. *
  26141. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  26142. * @param {Scene} scene - A reference to the scene.
  26143. * @param {Camera} camera - A reference to the camera.
  26144. * @param {Object} options - Options for the internal render target.
  26145. */
  26146. constructor( scope, scene, camera, options = {} ) {
  26147. super( 'vec4' );
  26148. /**
  26149. * The scope of the pass. The scope determines whether the node outputs color or depth.
  26150. *
  26151. * @type {('color'|'depth')}
  26152. */
  26153. this.scope = scope;
  26154. /**
  26155. * A reference to the scene.
  26156. *
  26157. * @type {Scene}
  26158. */
  26159. this.scene = scene;
  26160. /**
  26161. * A reference to the camera.
  26162. *
  26163. * @type {Camera}
  26164. */
  26165. this.camera = camera;
  26166. /**
  26167. * Options for the internal render target.
  26168. *
  26169. * @type {Object}
  26170. */
  26171. this.options = options;
  26172. /**
  26173. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  26174. *
  26175. * @private
  26176. * @type {number}
  26177. * @default 1
  26178. */
  26179. this._pixelRatio = 1;
  26180. /**
  26181. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  26182. * @private
  26183. * @type {number}
  26184. * @default 1
  26185. */
  26186. this._width = 1;
  26187. /**
  26188. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  26189. * @private
  26190. * @type {number}
  26191. * @default 1
  26192. */
  26193. this._height = 1;
  26194. const depthTexture = new DepthTexture();
  26195. depthTexture.isRenderTargetTexture = true;
  26196. //depthTexture.type = FloatType;
  26197. depthTexture.name = 'depth';
  26198. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  26199. renderTarget.texture.name = 'output';
  26200. renderTarget.depthTexture = depthTexture;
  26201. /**
  26202. * The pass's render target.
  26203. *
  26204. * @type {RenderTarget}
  26205. */
  26206. this.renderTarget = renderTarget;
  26207. /**
  26208. * A dictionary holding the internal result textures.
  26209. *
  26210. * @private
  26211. * @type {Object<string, Texture>}
  26212. */
  26213. this._textures = {
  26214. output: renderTarget.texture,
  26215. depth: depthTexture
  26216. };
  26217. /**
  26218. * A dictionary holding the internal texture nodes.
  26219. *
  26220. * @private
  26221. * @type {Object<string, TextureNode>}
  26222. */
  26223. this._textureNodes = {};
  26224. /**
  26225. * A dictionary holding the internal depth nodes.
  26226. *
  26227. * @private
  26228. * @type {Object}
  26229. */
  26230. this._linearDepthNodes = {};
  26231. /**
  26232. * A dictionary holding the internal viewZ nodes.
  26233. *
  26234. * @private
  26235. * @type {Object}
  26236. */
  26237. this._viewZNodes = {};
  26238. /**
  26239. * A dictionary holding the texture data of the previous frame.
  26240. * Used for computing velocity/motion vectors.
  26241. *
  26242. * @private
  26243. * @type {Object<string, Texture>}
  26244. */
  26245. this._previousTextures = {};
  26246. /**
  26247. * A dictionary holding the texture nodes of the previous frame.
  26248. * Used for computing velocity/motion vectors.
  26249. *
  26250. * @private
  26251. * @type {Object<string, TextureNode>}
  26252. */
  26253. this._previousTextureNodes = {};
  26254. /**
  26255. * The `near` property of the camera as a uniform.
  26256. *
  26257. * @private
  26258. * @type {UniformNode}
  26259. */
  26260. this._cameraNear = uniform( 0 );
  26261. /**
  26262. * The `far` property of the camera as a uniform.
  26263. *
  26264. * @private
  26265. * @type {UniformNode}
  26266. */
  26267. this._cameraFar = uniform( 0 );
  26268. /**
  26269. * A MRT node configuring the MRT settings.
  26270. *
  26271. * @private
  26272. * @type {?MRTNode}
  26273. * @default null
  26274. */
  26275. this._mrt = null;
  26276. /**
  26277. * Layer object for configuring the camera that is used
  26278. * to produce the pass.
  26279. *
  26280. * @private
  26281. * @type {?Layers}
  26282. * @default null
  26283. */
  26284. this._layers = null;
  26285. /**
  26286. * Scales the resolution of the internal render target.
  26287. *
  26288. * @private
  26289. * @type {number}
  26290. * @default 1
  26291. */
  26292. this._resolutionScale = 1;
  26293. /**
  26294. * Custom viewport definition.
  26295. *
  26296. * @private
  26297. * @type {?Vector4}
  26298. * @default null
  26299. */
  26300. this._viewport = null;
  26301. /**
  26302. * Custom scissor definition.
  26303. *
  26304. * @private
  26305. * @type {?Vector4}
  26306. * @default null
  26307. */
  26308. this._scissor = null;
  26309. /**
  26310. * This flag can be used for type testing.
  26311. *
  26312. * @type {boolean}
  26313. * @readonly
  26314. * @default true
  26315. */
  26316. this.isPassNode = true;
  26317. /**
  26318. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  26319. * scene once per frame in its {@link PassNode#updateBefore} method.
  26320. *
  26321. * @type {string}
  26322. * @default 'frame'
  26323. */
  26324. this.updateBeforeType = NodeUpdateType.FRAME;
  26325. /**
  26326. * This flag is used for global cache.
  26327. *
  26328. * @type {boolean}
  26329. * @default true
  26330. */
  26331. this.global = true;
  26332. }
  26333. /**
  26334. * Sets the resolution scale for the pass.
  26335. * The resolution scale is a factor that is multiplied with the renderer's width and height.
  26336. *
  26337. * @param {number} resolutionScale - The resolution scale to set. A value of `1` means full resolution.
  26338. * @return {PassNode} A reference to this pass.
  26339. */
  26340. setResolutionScale( resolutionScale ) {
  26341. this._resolutionScale = resolutionScale;
  26342. return this;
  26343. }
  26344. /**
  26345. * Gets the current resolution scale of the pass.
  26346. *
  26347. * @return {number} The current resolution scale. A value of `1` means full resolution.
  26348. */
  26349. getResolutionScale() {
  26350. return this._resolutionScale;
  26351. }
  26352. /**
  26353. * Sets the resolution for the pass.
  26354. * The resolution is a factor that is multiplied with the renderer's width and height.
  26355. *
  26356. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  26357. * @return {PassNode} A reference to this pass.
  26358. * @deprecated since r181. Use {@link PassNode#setResolutionScale `setResolutionScale()`} instead.
  26359. */
  26360. setResolution( resolution ) { // @deprecated, r181
  26361. warn( 'PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead.' );
  26362. return this.setResolutionScale( resolution );
  26363. }
  26364. /**
  26365. * Gets the current resolution of the pass.
  26366. *
  26367. * @return {number} The current resolution. A value of `1` means full resolution.
  26368. * @deprecated since r181. Use {@link PassNode#getResolutionScale `getResolutionScale()`} instead.
  26369. */
  26370. getResolution() { // @deprecated, r181
  26371. warn( 'PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead.' );
  26372. return this.getResolutionScale();
  26373. }
  26374. /**
  26375. * Sets the layer configuration that should be used when rendering the pass.
  26376. *
  26377. * @param {Layers} layers - The layers object to set.
  26378. * @return {PassNode} A reference to this pass.
  26379. */
  26380. setLayers( layers ) {
  26381. this._layers = layers;
  26382. return this;
  26383. }
  26384. /**
  26385. * Gets the current layer configuration of the pass.
  26386. *
  26387. * @return {?Layers} .
  26388. */
  26389. getLayers() {
  26390. return this._layers;
  26391. }
  26392. /**
  26393. * Sets the given MRT node to setup MRT for this pass.
  26394. *
  26395. * @param {MRTNode} mrt - The MRT object.
  26396. * @return {PassNode} A reference to this pass.
  26397. */
  26398. setMRT( mrt ) {
  26399. this._mrt = mrt;
  26400. return this;
  26401. }
  26402. /**
  26403. * Returns the current MRT node.
  26404. *
  26405. * @return {MRTNode} The current MRT node.
  26406. */
  26407. getMRT() {
  26408. return this._mrt;
  26409. }
  26410. /**
  26411. * Returns the texture for the given output name.
  26412. *
  26413. * @param {string} name - The output name to get the texture for.
  26414. * @return {Texture} The texture.
  26415. */
  26416. getTexture( name ) {
  26417. let texture = this._textures[ name ];
  26418. if ( texture === undefined ) {
  26419. const refTexture = this.renderTarget.texture;
  26420. texture = refTexture.clone();
  26421. texture.name = name;
  26422. this._textures[ name ] = texture;
  26423. this.renderTarget.textures.push( texture );
  26424. }
  26425. return texture;
  26426. }
  26427. /**
  26428. * Returns the texture holding the data of the previous frame for the given output name.
  26429. *
  26430. * @param {string} name - The output name to get the texture for.
  26431. * @return {Texture} The texture holding the data of the previous frame.
  26432. */
  26433. getPreviousTexture( name ) {
  26434. let texture = this._previousTextures[ name ];
  26435. if ( texture === undefined ) {
  26436. texture = this.getTexture( name ).clone();
  26437. this._previousTextures[ name ] = texture;
  26438. }
  26439. return texture;
  26440. }
  26441. /**
  26442. * Switches current and previous textures for the given output name.
  26443. *
  26444. * @param {string} name - The output name.
  26445. */
  26446. toggleTexture( name ) {
  26447. const prevTexture = this._previousTextures[ name ];
  26448. if ( prevTexture !== undefined ) {
  26449. const texture = this._textures[ name ];
  26450. const index = this.renderTarget.textures.indexOf( texture );
  26451. this.renderTarget.textures[ index ] = prevTexture;
  26452. this._textures[ name ] = prevTexture;
  26453. this._previousTextures[ name ] = texture;
  26454. this._textureNodes[ name ].updateTexture();
  26455. this._previousTextureNodes[ name ].updateTexture();
  26456. }
  26457. }
  26458. /**
  26459. * Returns the texture node for the given output name.
  26460. *
  26461. * @param {string} [name='output'] - The output name to get the texture node for.
  26462. * @return {TextureNode} The texture node.
  26463. */
  26464. getTextureNode( name = 'output' ) {
  26465. let textureNode = this._textureNodes[ name ];
  26466. if ( textureNode === undefined ) {
  26467. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  26468. textureNode.updateTexture();
  26469. this._textureNodes[ name ] = textureNode;
  26470. }
  26471. return textureNode;
  26472. }
  26473. /**
  26474. * Returns the previous texture node for the given output name.
  26475. *
  26476. * @param {string} [name='output'] - The output name to get the previous texture node for.
  26477. * @return {TextureNode} The previous texture node.
  26478. */
  26479. getPreviousTextureNode( name = 'output' ) {
  26480. let textureNode = this._previousTextureNodes[ name ];
  26481. if ( textureNode === undefined ) {
  26482. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  26483. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  26484. textureNode.updateTexture();
  26485. this._previousTextureNodes[ name ] = textureNode;
  26486. }
  26487. return textureNode;
  26488. }
  26489. /**
  26490. * Returns a viewZ node of this pass.
  26491. *
  26492. * @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.
  26493. * @return {Node} The viewZ node.
  26494. */
  26495. getViewZNode( name = 'depth' ) {
  26496. let viewZNode = this._viewZNodes[ name ];
  26497. if ( viewZNode === undefined ) {
  26498. const cameraNear = this._cameraNear;
  26499. const cameraFar = this._cameraFar;
  26500. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  26501. }
  26502. return viewZNode;
  26503. }
  26504. /**
  26505. * Returns a linear depth node of this pass.
  26506. *
  26507. * @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.
  26508. * @return {Node} The linear depth node.
  26509. */
  26510. getLinearDepthNode( name = 'depth' ) {
  26511. let linearDepthNode = this._linearDepthNodes[ name ];
  26512. if ( linearDepthNode === undefined ) {
  26513. const cameraNear = this._cameraNear;
  26514. const cameraFar = this._cameraFar;
  26515. const viewZNode = this.getViewZNode( name );
  26516. // TODO: just if ( builder.camera.isPerspectiveCamera )
  26517. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  26518. }
  26519. return linearDepthNode;
  26520. }
  26521. /**
  26522. * Precompiles the pass.
  26523. *
  26524. * Note that this method must be called after the pass configuration is complete.
  26525. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  26526. *
  26527. * @async
  26528. * @param {Renderer} renderer - The renderer.
  26529. * @return {Promise} A Promise that resolves when the compile has been finished.
  26530. * @see {@link Renderer#compileAsync}
  26531. */
  26532. async compileAsync( renderer ) {
  26533. const currentRenderTarget = renderer.getRenderTarget();
  26534. const currentMRT = renderer.getMRT();
  26535. renderer.setRenderTarget( this.renderTarget );
  26536. renderer.setMRT( this._mrt );
  26537. await renderer.compileAsync( this.scene, this.camera );
  26538. renderer.setRenderTarget( currentRenderTarget );
  26539. renderer.setMRT( currentMRT );
  26540. }
  26541. setup( { renderer } ) {
  26542. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  26543. this.renderTarget.texture.type = renderer.getColorBufferType();
  26544. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  26545. }
  26546. updateBefore( frame ) {
  26547. const { renderer } = frame;
  26548. const { scene } = this;
  26549. let camera;
  26550. let pixelRatio;
  26551. const outputRenderTarget = renderer.getOutputRenderTarget();
  26552. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  26553. pixelRatio = 1;
  26554. camera = renderer.xr.getCamera();
  26555. renderer.xr.updateCamera( camera );
  26556. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  26557. } else {
  26558. camera = this.camera;
  26559. pixelRatio = renderer.getPixelRatio();
  26560. renderer.getSize( _size );
  26561. }
  26562. this._pixelRatio = pixelRatio;
  26563. this.setSize( _size.width, _size.height );
  26564. const currentRenderTarget = renderer.getRenderTarget();
  26565. const currentMRT = renderer.getMRT();
  26566. const currentAutoClear = renderer.autoClear;
  26567. const currentMask = camera.layers.mask;
  26568. this._cameraNear.value = camera.near;
  26569. this._cameraFar.value = camera.far;
  26570. if ( this._layers !== null ) {
  26571. camera.layers.mask = this._layers.mask;
  26572. }
  26573. for ( const name in this._previousTextures ) {
  26574. this.toggleTexture( name );
  26575. }
  26576. renderer.setRenderTarget( this.renderTarget );
  26577. renderer.setMRT( this._mrt );
  26578. renderer.autoClear = true;
  26579. const currentSceneName = scene.name;
  26580. scene.name = this.name ? this.name : scene.name;
  26581. renderer.render( scene, camera );
  26582. scene.name = currentSceneName;
  26583. renderer.setRenderTarget( currentRenderTarget );
  26584. renderer.setMRT( currentMRT );
  26585. renderer.autoClear = currentAutoClear;
  26586. camera.layers.mask = currentMask;
  26587. }
  26588. /**
  26589. * Sets the size of the pass's render target. Honors the pixel ratio.
  26590. *
  26591. * @param {number} width - The width to set.
  26592. * @param {number} height - The height to set.
  26593. */
  26594. setSize( width, height ) {
  26595. this._width = width;
  26596. this._height = height;
  26597. const effectiveWidth = Math.floor( this._width * this._pixelRatio * this._resolutionScale );
  26598. const effectiveHeight = Math.floor( this._height * this._pixelRatio * this._resolutionScale );
  26599. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  26600. if ( this._scissor !== null ) this.renderTarget.scissor.copy( this._scissor );
  26601. if ( this._viewport !== null ) this.renderTarget.viewport.copy( this._viewport );
  26602. }
  26603. /**
  26604. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  26605. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  26606. * with `null` as the single argument.
  26607. *
  26608. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  26609. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  26610. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  26611. * @param {number} width - The width of the scissor box in logical pixel unit.
  26612. * @param {number} height - The height of the scissor box in logical pixel unit.
  26613. */
  26614. setScissor( x, y, width, height ) {
  26615. if ( x === null ) {
  26616. this._scissor = null;
  26617. } else {
  26618. if ( this._scissor === null ) this._scissor = new Vector4();
  26619. if ( x.isVector4 ) {
  26620. this._scissor.copy( x );
  26621. } else {
  26622. this._scissor.set( x, y, width, height );
  26623. }
  26624. this._scissor.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  26625. }
  26626. }
  26627. /**
  26628. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  26629. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  26630. * with `null` as the single argument.
  26631. *
  26632. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  26633. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  26634. * @param {number} width - The width of the viewport in logical pixel unit.
  26635. * @param {number} height - The height of the viewport in logical pixel unit.
  26636. */
  26637. setViewport( x, y, width, height ) {
  26638. if ( x === null ) {
  26639. this._viewport = null;
  26640. } else {
  26641. if ( this._viewport === null ) this._viewport = new Vector4();
  26642. if ( x.isVector4 ) {
  26643. this._viewport.copy( x );
  26644. } else {
  26645. this._viewport.set( x, y, width, height );
  26646. }
  26647. this._viewport.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  26648. }
  26649. }
  26650. /**
  26651. * Sets the pixel ratio the pass's render target and updates the size.
  26652. *
  26653. * @param {number} pixelRatio - The pixel ratio to set.
  26654. */
  26655. setPixelRatio( pixelRatio ) {
  26656. this._pixelRatio = pixelRatio;
  26657. this.setSize( this._width, this._height );
  26658. }
  26659. /**
  26660. * Frees internal resources. Should be called when the node is no longer in use.
  26661. */
  26662. dispose() {
  26663. this.renderTarget.dispose();
  26664. }
  26665. }
  26666. /**
  26667. * @static
  26668. * @type {'color'}
  26669. * @default 'color'
  26670. */
  26671. PassNode.COLOR = 'color';
  26672. /**
  26673. * @static
  26674. * @type {'depth'}
  26675. * @default 'depth'
  26676. */
  26677. PassNode.DEPTH = 'depth';
  26678. /**
  26679. * TSL function for creating a pass node.
  26680. *
  26681. * @tsl
  26682. * @function
  26683. * @param {Scene} scene - A reference to the scene.
  26684. * @param {Camera} camera - A reference to the camera.
  26685. * @param {Object} options - Options for the internal render target.
  26686. * @returns {PassNode}
  26687. */
  26688. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  26689. /**
  26690. * TSL function for creating a pass texture node.
  26691. *
  26692. * @tsl
  26693. * @function
  26694. * @param {PassNode} pass - The pass node.
  26695. * @param {Texture} texture - The output texture.
  26696. * @returns {PassTextureNode}
  26697. */
  26698. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  26699. /**
  26700. * TSL function for creating a depth pass node.
  26701. *
  26702. * @tsl
  26703. * @function
  26704. * @param {Scene} scene - A reference to the scene.
  26705. * @param {Camera} camera - A reference to the camera.
  26706. * @param {Object} options - Options for the internal render target.
  26707. * @returns {PassNode}
  26708. */
  26709. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  26710. /**
  26711. * Represents a render pass for producing a toon outline effect on compatible objects.
  26712. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  26713. * will receive the outline.
  26714. *
  26715. * ```js
  26716. * const postProcessing = new PostProcessing( renderer );
  26717. *
  26718. * const scenePass = toonOutlinePass( scene, camera );
  26719. *
  26720. * postProcessing.outputNode = scenePass;
  26721. * ```
  26722. * @augments PassNode
  26723. */
  26724. class ToonOutlinePassNode extends PassNode {
  26725. static get type() {
  26726. return 'ToonOutlinePassNode';
  26727. }
  26728. /**
  26729. * Constructs a new outline pass node.
  26730. *
  26731. * @param {Scene} scene - A reference to the scene.
  26732. * @param {Camera} camera - A reference to the camera.
  26733. * @param {Node} colorNode - Defines the outline's color.
  26734. * @param {Node} thicknessNode - Defines the outline's thickness.
  26735. * @param {Node} alphaNode - Defines the outline's alpha.
  26736. */
  26737. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  26738. super( PassNode.COLOR, scene, camera );
  26739. /**
  26740. * Defines the outline's color.
  26741. *
  26742. * @type {Node}
  26743. */
  26744. this.colorNode = colorNode;
  26745. /**
  26746. * Defines the outline's thickness.
  26747. *
  26748. * @type {Node}
  26749. */
  26750. this.thicknessNode = thicknessNode;
  26751. /**
  26752. * Defines the outline's alpha.
  26753. *
  26754. * @type {Node}
  26755. */
  26756. this.alphaNode = alphaNode;
  26757. /**
  26758. * An internal material cache.
  26759. *
  26760. * @private
  26761. * @type {WeakMap<Material, NodeMaterial>}
  26762. */
  26763. this._materialCache = new WeakMap();
  26764. /**
  26765. * The name of this pass.
  26766. *
  26767. * @type {string}
  26768. * @default 'Outline Pass'
  26769. */
  26770. this.name = 'Outline Pass';
  26771. }
  26772. updateBefore( frame ) {
  26773. const { renderer } = frame;
  26774. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  26775. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  26776. // only render outline for supported materials
  26777. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  26778. if ( material.wireframe === false ) {
  26779. const outlineMaterial = this._getOutlineMaterial( material );
  26780. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  26781. }
  26782. }
  26783. // default
  26784. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  26785. } );
  26786. super.updateBefore( frame );
  26787. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  26788. }
  26789. /**
  26790. * Creates the material used for outline rendering.
  26791. *
  26792. * @private
  26793. * @return {NodeMaterial} The outline material.
  26794. */
  26795. _createMaterial() {
  26796. const material = new NodeMaterial();
  26797. material.isMeshToonOutlineMaterial = true;
  26798. material.name = 'Toon_Outline';
  26799. material.side = BackSide;
  26800. // vertex node
  26801. const outlineNormal = normalLocal.negate();
  26802. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  26803. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  26804. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  26805. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  26806. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  26807. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  26808. // color node
  26809. material.colorNode = vec4( this.colorNode, this.alphaNode );
  26810. return material;
  26811. }
  26812. /**
  26813. * For the given toon material, this method returns a corresponding
  26814. * outline material.
  26815. *
  26816. * @private
  26817. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  26818. * @return {NodeMaterial} The outline material.
  26819. */
  26820. _getOutlineMaterial( originalMaterial ) {
  26821. let outlineMaterial = this._materialCache.get( originalMaterial );
  26822. if ( outlineMaterial === undefined ) {
  26823. outlineMaterial = this._createMaterial();
  26824. this._materialCache.set( originalMaterial, outlineMaterial );
  26825. }
  26826. return outlineMaterial;
  26827. }
  26828. }
  26829. /**
  26830. * TSL function for creating a toon outline pass node.
  26831. *
  26832. * @tsl
  26833. * @function
  26834. * @param {Scene} scene - A reference to the scene.
  26835. * @param {Camera} camera - A reference to the camera.
  26836. * @param {Color} color - Defines the outline's color.
  26837. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  26838. * @param {number} [alpha=1] - Defines the outline's alpha.
  26839. * @returns {ToonOutlinePassNode}
  26840. */
  26841. 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 ) ) );
  26842. /**
  26843. * Linear tone mapping, exposure only.
  26844. *
  26845. * @tsl
  26846. * @function
  26847. * @param {Node<vec3>} color - The color that should be tone mapped.
  26848. * @param {Node<float>} exposure - The exposure.
  26849. * @return {Node<vec3>} The tone mapped color.
  26850. */
  26851. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26852. return color.mul( exposure ).clamp();
  26853. } ).setLayout( {
  26854. name: 'linearToneMapping',
  26855. type: 'vec3',
  26856. inputs: [
  26857. { name: 'color', type: 'vec3' },
  26858. { name: 'exposure', type: 'float' }
  26859. ]
  26860. } );
  26861. /**
  26862. * Reinhard tone mapping.
  26863. *
  26864. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  26865. *
  26866. * @tsl
  26867. * @function
  26868. * @param {Node<vec3>} color - The color that should be tone mapped.
  26869. * @param {Node<float>} exposure - The exposure.
  26870. * @return {Node<vec3>} The tone mapped color.
  26871. */
  26872. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26873. color = color.mul( exposure );
  26874. return color.div( color.add( 1.0 ) ).clamp();
  26875. } ).setLayout( {
  26876. name: 'reinhardToneMapping',
  26877. type: 'vec3',
  26878. inputs: [
  26879. { name: 'color', type: 'vec3' },
  26880. { name: 'exposure', type: 'float' }
  26881. ]
  26882. } );
  26883. /**
  26884. * Cineon tone mapping.
  26885. *
  26886. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  26887. *
  26888. * @tsl
  26889. * @function
  26890. * @param {Node<vec3>} color - The color that should be tone mapped.
  26891. * @param {Node<float>} exposure - The exposure.
  26892. * @return {Node<vec3>} The tone mapped color.
  26893. */
  26894. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26895. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  26896. color = color.mul( exposure );
  26897. color = color.sub( 0.004 ).max( 0.0 );
  26898. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  26899. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  26900. return a.div( b ).pow( 2.2 );
  26901. } ).setLayout( {
  26902. name: 'cineonToneMapping',
  26903. type: 'vec3',
  26904. inputs: [
  26905. { name: 'color', type: 'vec3' },
  26906. { name: 'exposure', type: 'float' }
  26907. ]
  26908. } );
  26909. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  26910. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  26911. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  26912. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  26913. return a.div( b );
  26914. } );
  26915. /**
  26916. * ACESFilmic tone mapping.
  26917. *
  26918. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  26919. *
  26920. * @tsl
  26921. * @function
  26922. * @param {Node<vec3>} color - The color that should be tone mapped.
  26923. * @param {Node<float>} exposure - The exposure.
  26924. * @return {Node<vec3>} The tone mapped color.
  26925. */
  26926. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26927. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  26928. const ACESInputMat = mat3(
  26929. 0.59719, 0.35458, 0.04823,
  26930. 0.07600, 0.90834, 0.01566,
  26931. 0.02840, 0.13383, 0.83777
  26932. );
  26933. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  26934. const ACESOutputMat = mat3(
  26935. 1.60475, -0.53108, -0.07367,
  26936. -0.10208, 1.10813, -605e-5,
  26937. -327e-5, -0.07276, 1.07602
  26938. );
  26939. color = color.mul( exposure ).div( 0.6 );
  26940. color = ACESInputMat.mul( color );
  26941. // Apply RRT and ODT
  26942. color = RRTAndODTFit( color );
  26943. color = ACESOutputMat.mul( color );
  26944. // Clamp to [0, 1]
  26945. return color.clamp();
  26946. } ).setLayout( {
  26947. name: 'acesFilmicToneMapping',
  26948. type: 'vec3',
  26949. inputs: [
  26950. { name: 'color', type: 'vec3' },
  26951. { name: 'exposure', type: 'float' }
  26952. ]
  26953. } );
  26954. 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 ) );
  26955. 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 ) );
  26956. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26957. const x = vec3( x_immutable ).toVar();
  26958. const x2 = vec3( x.mul( x ) ).toVar();
  26959. const x4 = vec3( x2.mul( x2 ) ).toVar();
  26960. 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 ) ) ) );
  26961. } );
  26962. /**
  26963. * AgX tone mapping.
  26964. *
  26965. * @tsl
  26966. * @function
  26967. * @param {Node<vec3>} color - The color that should be tone mapped.
  26968. * @param {Node<float>} exposure - The exposure.
  26969. * @return {Node<vec3>} The tone mapped color.
  26970. */
  26971. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26972. const colortone = vec3( color ).toVar();
  26973. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  26974. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  26975. const AgxMinEv = float( -12.47393 );
  26976. const AgxMaxEv = float( 4.026069 );
  26977. colortone.mulAssign( exposure );
  26978. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  26979. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  26980. colortone.assign( max$1( colortone, 1e-10 ) );
  26981. colortone.assign( log2( colortone ) );
  26982. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  26983. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  26984. colortone.assign( agxDefaultContrastApprox( colortone ) );
  26985. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  26986. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  26987. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  26988. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  26989. return colortone;
  26990. } ).setLayout( {
  26991. name: 'agxToneMapping',
  26992. type: 'vec3',
  26993. inputs: [
  26994. { name: 'color', type: 'vec3' },
  26995. { name: 'exposure', type: 'float' }
  26996. ]
  26997. } );
  26998. /**
  26999. * Neutral tone mapping.
  27000. *
  27001. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  27002. *
  27003. * @tsl
  27004. * @function
  27005. * @param {Node<vec3>} color - The color that should be tone mapped.
  27006. * @param {Node<float>} exposure - The exposure.
  27007. * @return {Node<vec3>} The tone mapped color.
  27008. */
  27009. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27010. const StartCompression = float( 0.8 - 0.04 );
  27011. const Desaturation = float( 0.15 );
  27012. color = color.mul( exposure );
  27013. const x = min$1( color.r, min$1( color.g, color.b ) );
  27014. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  27015. color.subAssign( offset );
  27016. const peak = max$1( color.r, max$1( color.g, color.b ) );
  27017. If( peak.lessThan( StartCompression ), () => {
  27018. return color;
  27019. } );
  27020. const d = sub( 1, StartCompression );
  27021. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  27022. color.mulAssign( newPeak.div( peak ) );
  27023. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  27024. return mix( color, vec3( newPeak ), g );
  27025. } ).setLayout( {
  27026. name: 'neutralToneMapping',
  27027. type: 'vec3',
  27028. inputs: [
  27029. { name: 'color', type: 'vec3' },
  27030. { name: 'exposure', type: 'float' }
  27031. ]
  27032. } );
  27033. /**
  27034. * This class represents native code sections. It is the base
  27035. * class for modules like {@link FunctionNode} which allows to implement
  27036. * functions with native shader languages.
  27037. *
  27038. * @augments Node
  27039. */
  27040. class CodeNode extends Node {
  27041. static get type() {
  27042. return 'CodeNode';
  27043. }
  27044. /**
  27045. * Constructs a new code node.
  27046. *
  27047. * @param {string} [code=''] - The native code.
  27048. * @param {Array<Node>} [includes=[]] - An array of includes.
  27049. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  27050. */
  27051. constructor( code = '', includes = [], language = '' ) {
  27052. super( 'code' );
  27053. /**
  27054. * This flag can be used for type testing.
  27055. *
  27056. * @type {boolean}
  27057. * @readonly
  27058. * @default true
  27059. */
  27060. this.isCodeNode = true;
  27061. /**
  27062. * This flag is used for global cache.
  27063. *
  27064. * @type {boolean}
  27065. * @default true
  27066. */
  27067. this.global = true;
  27068. /**
  27069. * The native code.
  27070. *
  27071. * @type {string}
  27072. * @default ''
  27073. */
  27074. this.code = code;
  27075. /**
  27076. * An array of includes
  27077. *
  27078. * @type {Array<Node>}
  27079. * @default []
  27080. */
  27081. this.includes = includes;
  27082. /**
  27083. * The used language.
  27084. *
  27085. * @type {('js'|'wgsl'|'glsl')}
  27086. * @default ''
  27087. */
  27088. this.language = language;
  27089. }
  27090. /**
  27091. * Sets the includes of this code node.
  27092. *
  27093. * @param {Array<Node>} includes - The includes to set.
  27094. * @return {CodeNode} A reference to this node.
  27095. */
  27096. setIncludes( includes ) {
  27097. this.includes = includes;
  27098. return this;
  27099. }
  27100. /**
  27101. * Returns the includes of this code node.
  27102. *
  27103. * @param {NodeBuilder} builder - The current node builder.
  27104. * @return {Array<Node>} The includes.
  27105. */
  27106. getIncludes( /*builder*/ ) {
  27107. return this.includes;
  27108. }
  27109. generate( builder ) {
  27110. const includes = this.getIncludes( builder );
  27111. for ( const include of includes ) {
  27112. include.build( builder );
  27113. }
  27114. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  27115. nodeCode.code = this.code;
  27116. return nodeCode.code;
  27117. }
  27118. serialize( data ) {
  27119. super.serialize( data );
  27120. data.code = this.code;
  27121. data.language = this.language;
  27122. }
  27123. deserialize( data ) {
  27124. super.deserialize( data );
  27125. this.code = data.code;
  27126. this.language = data.language;
  27127. }
  27128. }
  27129. /**
  27130. * TSL function for creating a code node.
  27131. *
  27132. * @tsl
  27133. * @function
  27134. * @param {string} [code] - The native code.
  27135. * @param {?Array<Node>} [includes=[]] - An array of includes.
  27136. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  27137. * @returns {CodeNode}
  27138. */
  27139. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  27140. /**
  27141. * TSL function for creating a JS code node.
  27142. *
  27143. * @tsl
  27144. * @function
  27145. * @param {string} src - The native code.
  27146. * @param {Array<Node>} includes - An array of includes.
  27147. * @returns {CodeNode}
  27148. */
  27149. const js = ( src, includes ) => code( src, includes, 'js' );
  27150. /**
  27151. * TSL function for creating a WGSL code node.
  27152. *
  27153. * @tsl
  27154. * @function
  27155. * @param {string} src - The native code.
  27156. * @param {Array<Node>} includes - An array of includes.
  27157. * @returns {CodeNode}
  27158. */
  27159. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  27160. /**
  27161. * TSL function for creating a GLSL code node.
  27162. *
  27163. * @tsl
  27164. * @function
  27165. * @param {string} src - The native code.
  27166. * @param {Array<Node>} includes - An array of includes.
  27167. * @returns {CodeNode}
  27168. */
  27169. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  27170. /**
  27171. * This class represents a native shader function. It can be used to implement
  27172. * certain aspects of a node material with native shader code. There are two predefined
  27173. * TSL functions for easier usage.
  27174. *
  27175. * - `wgslFn`: Creates a WGSL function node.
  27176. * - `glslFn`: Creates a GLSL function node.
  27177. *
  27178. * A basic example with one include looks like so:
  27179. *
  27180. * ```js
  27181. * const desaturateWGSLFn = wgslFn( `
  27182. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  27183. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  27184. * return vec3<f32>( dot( lum, color ) );
  27185. * }`
  27186. *);
  27187. * const someWGSLFn = wgslFn( `
  27188. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  27189. * return desaturate( color );
  27190. * }
  27191. * `, [ desaturateWGSLFn ] );
  27192. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  27193. *```
  27194. * @augments CodeNode
  27195. */
  27196. class FunctionNode extends CodeNode {
  27197. static get type() {
  27198. return 'FunctionNode';
  27199. }
  27200. /**
  27201. * Constructs a new function node.
  27202. *
  27203. * @param {string} [code=''] - The native code.
  27204. * @param {Array<Node>} [includes=[]] - An array of includes.
  27205. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  27206. */
  27207. constructor( code = '', includes = [], language = '' ) {
  27208. super( code, includes, language );
  27209. }
  27210. /**
  27211. * Returns the type of this function node.
  27212. *
  27213. * @param {NodeBuilder} builder - The current node builder.
  27214. * @return {string} The type.
  27215. */
  27216. getNodeType( builder ) {
  27217. return this.getNodeFunction( builder ).type;
  27218. }
  27219. /**
  27220. * Returns the type of a member of this function node.
  27221. *
  27222. * @param {NodeBuilder} builder - The current node builder.
  27223. * @param {string} name - The name of the member.
  27224. * @return {string} The type of the member.
  27225. */
  27226. getMemberType( builder, name ) {
  27227. const type = this.getNodeType( builder );
  27228. const structType = builder.getStructTypeNode( type );
  27229. return structType.getMemberType( builder, name );
  27230. }
  27231. /**
  27232. * Returns the inputs of this function node.
  27233. *
  27234. * @param {NodeBuilder} builder - The current node builder.
  27235. * @return {Array<NodeFunctionInput>} The inputs.
  27236. */
  27237. getInputs( builder ) {
  27238. return this.getNodeFunction( builder ).inputs;
  27239. }
  27240. /**
  27241. * Returns the node function for this function node.
  27242. *
  27243. * @param {NodeBuilder} builder - The current node builder.
  27244. * @return {NodeFunction} The node function.
  27245. */
  27246. getNodeFunction( builder ) {
  27247. const nodeData = builder.getDataFromNode( this );
  27248. let nodeFunction = nodeData.nodeFunction;
  27249. if ( nodeFunction === undefined ) {
  27250. nodeFunction = builder.parser.parseFunction( this.code );
  27251. nodeData.nodeFunction = nodeFunction;
  27252. }
  27253. return nodeFunction;
  27254. }
  27255. generate( builder, output ) {
  27256. super.generate( builder );
  27257. const nodeFunction = this.getNodeFunction( builder );
  27258. const name = nodeFunction.name;
  27259. const type = nodeFunction.type;
  27260. const nodeCode = builder.getCodeFromNode( this, type );
  27261. if ( name !== '' ) {
  27262. // use a custom property name
  27263. nodeCode.name = name;
  27264. }
  27265. const propertyName = builder.getPropertyName( nodeCode );
  27266. const code = this.getNodeFunction( builder ).getCode( propertyName );
  27267. nodeCode.code = code + '\n';
  27268. if ( output === 'property' ) {
  27269. return propertyName;
  27270. } else {
  27271. return builder.format( `${ propertyName }()`, type, output );
  27272. }
  27273. }
  27274. }
  27275. const nativeFn = ( code, includes = [], language = '' ) => {
  27276. for ( let i = 0; i < includes.length; i ++ ) {
  27277. const include = includes[ i ];
  27278. // TSL Function: glslFn, wgslFn
  27279. if ( typeof include === 'function' ) {
  27280. includes[ i ] = include.functionNode;
  27281. }
  27282. }
  27283. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  27284. const fn = ( ...params ) => functionNode.call( ...params );
  27285. fn.functionNode = functionNode;
  27286. return fn;
  27287. };
  27288. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  27289. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  27290. /**
  27291. * `ScriptableNode` uses this class to manage script inputs and outputs.
  27292. *
  27293. * @augments Node
  27294. */
  27295. class ScriptableValueNode extends Node {
  27296. static get type() {
  27297. return 'ScriptableValueNode';
  27298. }
  27299. /**
  27300. * Constructs a new scriptable node.
  27301. *
  27302. * @param {any} [value=null] - The value.
  27303. */
  27304. constructor( value = null ) {
  27305. super();
  27306. /**
  27307. * A reference to the value.
  27308. *
  27309. * @private
  27310. * @default null
  27311. */
  27312. this._value = value;
  27313. /**
  27314. * Depending on the type of `_value`, this property might cache parsed data.
  27315. *
  27316. * @private
  27317. * @default null
  27318. */
  27319. this._cache = null;
  27320. /**
  27321. * If this node represents an input, this property represents the input type.
  27322. *
  27323. * @type {?string}
  27324. * @default null
  27325. */
  27326. this.inputType = null;
  27327. /**
  27328. * If this node represents an output, this property represents the output type.
  27329. *
  27330. * @type {?string}
  27331. * @default null
  27332. */
  27333. this.outputType = null;
  27334. /**
  27335. * An event dispatcher for managing events.
  27336. *
  27337. * @type {EventDispatcher}
  27338. */
  27339. this.events = new EventDispatcher();
  27340. /**
  27341. * This flag can be used for type testing.
  27342. *
  27343. * @type {boolean}
  27344. * @readonly
  27345. * @default true
  27346. */
  27347. this.isScriptableValueNode = true;
  27348. }
  27349. /**
  27350. * Whether this node represents an output or not.
  27351. *
  27352. * @type {boolean}
  27353. * @readonly
  27354. * @default true
  27355. */
  27356. get isScriptableOutputNode() {
  27357. return this.outputType !== null;
  27358. }
  27359. set value( val ) {
  27360. if ( this._value === val ) return;
  27361. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  27362. URL.revokeObjectURL( this._cache );
  27363. this._cache = null;
  27364. }
  27365. this._value = val;
  27366. this.events.dispatchEvent( { type: 'change' } );
  27367. this.refresh();
  27368. }
  27369. /**
  27370. * The node's value.
  27371. *
  27372. * @type {any}
  27373. */
  27374. get value() {
  27375. return this._value;
  27376. }
  27377. /**
  27378. * Dispatches the `refresh` event.
  27379. */
  27380. refresh() {
  27381. this.events.dispatchEvent( { type: 'refresh' } );
  27382. }
  27383. /**
  27384. * The `value` property usually represents a node or even binary data in form of array buffers.
  27385. * In this case, this method tries to return the actual value behind the complex type.
  27386. *
  27387. * @return {any} The value.
  27388. */
  27389. getValue() {
  27390. const value = this.value;
  27391. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  27392. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  27393. } else if ( value && value.value !== null && value.value !== undefined && (
  27394. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  27395. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  27396. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  27397. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  27398. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  27399. ( this.inputType === 'Color' && value.value.isColor ) ||
  27400. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  27401. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  27402. ) ) {
  27403. return value.value;
  27404. }
  27405. return this._cache || value;
  27406. }
  27407. /**
  27408. * Overwritten since the node type is inferred from the value.
  27409. *
  27410. * @param {NodeBuilder} builder - The current node builder.
  27411. * @return {string} The node type.
  27412. */
  27413. getNodeType( builder ) {
  27414. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  27415. }
  27416. setup() {
  27417. return this.value && this.value.isNode ? this.value : float();
  27418. }
  27419. serialize( data ) {
  27420. super.serialize( data );
  27421. if ( this.value !== null ) {
  27422. if ( this.inputType === 'ArrayBuffer' ) {
  27423. data.value = arrayBufferToBase64( this.value );
  27424. } else {
  27425. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  27426. }
  27427. } else {
  27428. data.value = null;
  27429. }
  27430. data.inputType = this.inputType;
  27431. data.outputType = this.outputType;
  27432. }
  27433. deserialize( data ) {
  27434. super.deserialize( data );
  27435. let value = null;
  27436. if ( data.value !== null ) {
  27437. if ( data.inputType === 'ArrayBuffer' ) {
  27438. value = base64ToArrayBuffer( data.value );
  27439. } else if ( data.inputType === 'Texture' ) {
  27440. value = data.meta.textures[ data.value ];
  27441. } else {
  27442. value = data.meta.nodes[ data.value ] || null;
  27443. }
  27444. }
  27445. this.value = value;
  27446. this.inputType = data.inputType;
  27447. this.outputType = data.outputType;
  27448. }
  27449. }
  27450. /**
  27451. * TSL function for creating a scriptable value node.
  27452. *
  27453. * @tsl
  27454. * @function
  27455. * @param {any} [value] - The value.
  27456. * @returns {ScriptableValueNode}
  27457. */
  27458. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  27459. /**
  27460. * A Map-like data structure for managing resources of scriptable nodes.
  27461. *
  27462. * @augments Map
  27463. */
  27464. class Resources extends Map {
  27465. get( key, callback = null, ...params ) {
  27466. if ( this.has( key ) ) return super.get( key );
  27467. if ( callback !== null ) {
  27468. const value = callback( ...params );
  27469. this.set( key, value );
  27470. return value;
  27471. }
  27472. }
  27473. }
  27474. class Parameters {
  27475. constructor( scriptableNode ) {
  27476. this.scriptableNode = scriptableNode;
  27477. }
  27478. get parameters() {
  27479. return this.scriptableNode.parameters;
  27480. }
  27481. get layout() {
  27482. return this.scriptableNode.getLayout();
  27483. }
  27484. getInputLayout( id ) {
  27485. return this.scriptableNode.getInputLayout( id );
  27486. }
  27487. get( name ) {
  27488. const param = this.parameters[ name ];
  27489. const value = param ? param.getValue() : null;
  27490. return value;
  27491. }
  27492. }
  27493. /**
  27494. * Defines the resources (e.g. namespaces) of scriptable nodes.
  27495. *
  27496. * @type {Resources}
  27497. */
  27498. const ScriptableNodeResources = new Resources();
  27499. /**
  27500. * This type of node allows to implement nodes with custom scripts. The script
  27501. * section is represented as an instance of `CodeNode` written with JavaScript.
  27502. * The script itself must adhere to a specific structure.
  27503. *
  27504. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  27505. * - layout: The layout object defines the script's interface (inputs and outputs).
  27506. *
  27507. * ```js
  27508. * ScriptableNodeResources.set( 'TSL', TSL );
  27509. *
  27510. * const scriptableNode = scriptable( js( `
  27511. * layout = {
  27512. * outputType: 'node',
  27513. * elements: [
  27514. * { name: 'source', inputType: 'node' },
  27515. * ]
  27516. * };
  27517. *
  27518. * const { mul, oscSine } = TSL;
  27519. *
  27520. * function main() {
  27521. * const source = parameters.get( 'source' ) || float();
  27522. * return mul( source, oscSine() ) );
  27523. * }
  27524. *
  27525. * ` ) );
  27526. *
  27527. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  27528. *
  27529. * const material = new THREE.MeshBasicNodeMaterial();
  27530. * material.colorNode = scriptableNode;
  27531. * ```
  27532. *
  27533. * @augments Node
  27534. */
  27535. class ScriptableNode extends Node {
  27536. static get type() {
  27537. return 'ScriptableNode';
  27538. }
  27539. /**
  27540. * Constructs a new scriptable node.
  27541. *
  27542. * @param {?CodeNode} [codeNode=null] - The code node.
  27543. * @param {Object} [parameters={}] - The parameters definition.
  27544. */
  27545. constructor( codeNode = null, parameters = {} ) {
  27546. super();
  27547. /**
  27548. * The code node.
  27549. *
  27550. * @type {?CodeNode}
  27551. * @default null
  27552. */
  27553. this.codeNode = codeNode;
  27554. /**
  27555. * The parameters definition.
  27556. *
  27557. * @type {Object}
  27558. * @default {}
  27559. */
  27560. this.parameters = parameters;
  27561. this._local = new Resources();
  27562. this._output = scriptableValue( null );
  27563. this._outputs = {};
  27564. this._source = this.source;
  27565. this._method = null;
  27566. this._object = null;
  27567. this._value = null;
  27568. this._needsOutputUpdate = true;
  27569. this.onRefresh = this.onRefresh.bind( this );
  27570. /**
  27571. * This flag can be used for type testing.
  27572. *
  27573. * @type {boolean}
  27574. * @readonly
  27575. * @default true
  27576. */
  27577. this.isScriptableNode = true;
  27578. }
  27579. /**
  27580. * The source code of the scriptable node.
  27581. *
  27582. * @type {string}
  27583. */
  27584. get source() {
  27585. return this.codeNode ? this.codeNode.code : '';
  27586. }
  27587. /**
  27588. * Sets the reference of a local script variable.
  27589. *
  27590. * @param {string} name - The variable name.
  27591. * @param {Object} value - The reference to set.
  27592. * @return {Resources} The resource map
  27593. */
  27594. setLocal( name, value ) {
  27595. return this._local.set( name, value );
  27596. }
  27597. /**
  27598. * Gets the value of a local script variable.
  27599. *
  27600. * @param {string} name - The variable name.
  27601. * @return {Object} The value.
  27602. */
  27603. getLocal( name ) {
  27604. return this._local.get( name );
  27605. }
  27606. /**
  27607. * Event listener for the `refresh` event.
  27608. */
  27609. onRefresh() {
  27610. this._refresh();
  27611. }
  27612. /**
  27613. * Returns an input from the layout with the given id/name.
  27614. *
  27615. * @param {string} id - The id/name of the input.
  27616. * @return {Object} The element entry.
  27617. */
  27618. getInputLayout( id ) {
  27619. for ( const element of this.getLayout() ) {
  27620. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  27621. return element;
  27622. }
  27623. }
  27624. }
  27625. /**
  27626. * Returns an output from the layout with the given id/name.
  27627. *
  27628. * @param {string} id - The id/name of the output.
  27629. * @return {Object} The element entry.
  27630. */
  27631. getOutputLayout( id ) {
  27632. for ( const element of this.getLayout() ) {
  27633. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  27634. return element;
  27635. }
  27636. }
  27637. }
  27638. /**
  27639. * Defines a script output for the given name and value.
  27640. *
  27641. * @param {string} name - The name of the output.
  27642. * @param {Node} value - The node value.
  27643. * @return {ScriptableNode} A reference to this node.
  27644. */
  27645. setOutput( name, value ) {
  27646. const outputs = this._outputs;
  27647. if ( outputs[ name ] === undefined ) {
  27648. outputs[ name ] = scriptableValue( value );
  27649. } else {
  27650. outputs[ name ].value = value;
  27651. }
  27652. return this;
  27653. }
  27654. /**
  27655. * Returns a script output for the given name.
  27656. *
  27657. * @param {string} name - The name of the output.
  27658. * @return {ScriptableValueNode} The node value.
  27659. */
  27660. getOutput( name ) {
  27661. return this._outputs[ name ];
  27662. }
  27663. /**
  27664. * Returns a parameter for the given name
  27665. *
  27666. * @param {string} name - The name of the parameter.
  27667. * @return {ScriptableValueNode} The node value.
  27668. */
  27669. getParameter( name ) {
  27670. return this.parameters[ name ];
  27671. }
  27672. /**
  27673. * Sets a value for the given parameter name.
  27674. *
  27675. * @param {string} name - The parameter name.
  27676. * @param {any} value - The parameter value.
  27677. * @return {ScriptableNode} A reference to this node.
  27678. */
  27679. setParameter( name, value ) {
  27680. const parameters = this.parameters;
  27681. if ( value && value.isScriptableNode ) {
  27682. this.deleteParameter( name );
  27683. parameters[ name ] = value;
  27684. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  27685. } else if ( value && value.isScriptableValueNode ) {
  27686. this.deleteParameter( name );
  27687. parameters[ name ] = value;
  27688. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  27689. } else if ( parameters[ name ] === undefined ) {
  27690. parameters[ name ] = scriptableValue( value );
  27691. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  27692. } else {
  27693. parameters[ name ].value = value;
  27694. }
  27695. return this;
  27696. }
  27697. /**
  27698. * Returns the value of this node which is the value of
  27699. * the default output.
  27700. *
  27701. * @return {Node} The value.
  27702. */
  27703. getValue() {
  27704. return this.getDefaultOutput().getValue();
  27705. }
  27706. /**
  27707. * Deletes a parameter from the script.
  27708. *
  27709. * @param {string} name - The parameter to remove.
  27710. * @return {ScriptableNode} A reference to this node.
  27711. */
  27712. deleteParameter( name ) {
  27713. let valueNode = this.parameters[ name ];
  27714. if ( valueNode ) {
  27715. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  27716. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  27717. }
  27718. return this;
  27719. }
  27720. /**
  27721. * Deletes all parameters from the script.
  27722. *
  27723. * @return {ScriptableNode} A reference to this node.
  27724. */
  27725. clearParameters() {
  27726. for ( const name of Object.keys( this.parameters ) ) {
  27727. this.deleteParameter( name );
  27728. }
  27729. this.needsUpdate = true;
  27730. return this;
  27731. }
  27732. /**
  27733. * Calls a function from the script.
  27734. *
  27735. * @param {string} name - The function name.
  27736. * @param {...any} params - A list of parameters.
  27737. * @return {any} The result of the function call.
  27738. */
  27739. call( name, ...params ) {
  27740. const object = this.getObject();
  27741. const method = object[ name ];
  27742. if ( typeof method === 'function' ) {
  27743. return method( ...params );
  27744. }
  27745. }
  27746. /**
  27747. * Asynchronously calls a function from the script.
  27748. *
  27749. * @param {string} name - The function name.
  27750. * @param {...any} params - A list of parameters.
  27751. * @return {Promise<any>} The result of the function call.
  27752. */
  27753. async callAsync( name, ...params ) {
  27754. const object = this.getObject();
  27755. const method = object[ name ];
  27756. if ( typeof method === 'function' ) {
  27757. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  27758. }
  27759. }
  27760. /**
  27761. * Overwritten since the node types is inferred from the script's output.
  27762. *
  27763. * @param {NodeBuilder} builder - The current node builder
  27764. * @return {string} The node type.
  27765. */
  27766. getNodeType( builder ) {
  27767. return this.getDefaultOutputNode().getNodeType( builder );
  27768. }
  27769. /**
  27770. * Refreshes the script node.
  27771. *
  27772. * @param {?string} [output=null] - An optional output.
  27773. */
  27774. refresh( output = null ) {
  27775. if ( output !== null ) {
  27776. this.getOutput( output ).refresh();
  27777. } else {
  27778. this._refresh();
  27779. }
  27780. }
  27781. /**
  27782. * Returns an object representation of the script.
  27783. *
  27784. * @return {Object} The result object.
  27785. */
  27786. getObject() {
  27787. if ( this.needsUpdate ) this.dispose();
  27788. if ( this._object !== null ) return this._object;
  27789. //
  27790. const refresh = () => this.refresh();
  27791. const setOutput = ( id, value ) => this.setOutput( id, value );
  27792. const parameters = new Parameters( this );
  27793. const THREE = ScriptableNodeResources.get( 'THREE' );
  27794. const TSL = ScriptableNodeResources.get( 'TSL' );
  27795. const method = this.getMethod();
  27796. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  27797. this._object = method( ...params );
  27798. const layout = this._object.layout;
  27799. if ( layout ) {
  27800. if ( layout.cache === false ) {
  27801. this._local.clear();
  27802. }
  27803. // default output
  27804. this._output.outputType = layout.outputType || null;
  27805. if ( Array.isArray( layout.elements ) ) {
  27806. for ( const element of layout.elements ) {
  27807. const id = element.id || element.name;
  27808. if ( element.inputType ) {
  27809. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  27810. this.getParameter( id ).inputType = element.inputType;
  27811. }
  27812. if ( element.outputType ) {
  27813. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  27814. this.getOutput( id ).outputType = element.outputType;
  27815. }
  27816. }
  27817. }
  27818. }
  27819. return this._object;
  27820. }
  27821. deserialize( data ) {
  27822. super.deserialize( data );
  27823. for ( const name in this.parameters ) {
  27824. let valueNode = this.parameters[ name ];
  27825. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  27826. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  27827. }
  27828. }
  27829. /**
  27830. * Returns the layout of the script.
  27831. *
  27832. * @return {Object} The script's layout.
  27833. */
  27834. getLayout() {
  27835. return this.getObject().layout;
  27836. }
  27837. /**
  27838. * Returns default node output of the script.
  27839. *
  27840. * @return {Node} The default node output.
  27841. */
  27842. getDefaultOutputNode() {
  27843. const output = this.getDefaultOutput().value;
  27844. if ( output && output.isNode ) {
  27845. return output;
  27846. }
  27847. return float();
  27848. }
  27849. /**
  27850. * Returns default output of the script.
  27851. *
  27852. * @return {ScriptableValueNode} The default output.
  27853. */
  27854. getDefaultOutput() {
  27855. return this._exec()._output;
  27856. }
  27857. /**
  27858. * Returns a function created from the node's script.
  27859. *
  27860. * @return {Function} The function representing the node's code.
  27861. */
  27862. getMethod() {
  27863. if ( this.needsUpdate ) this.dispose();
  27864. if ( this._method !== null ) return this._method;
  27865. //
  27866. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  27867. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  27868. const properties = interfaceProps.join( ', ' );
  27869. const declarations = 'var ' + properties + '; var output = {};\n';
  27870. const returns = '\nreturn { ...output, ' + properties + ' };';
  27871. const code = declarations + this.codeNode.code + returns;
  27872. //
  27873. this._method = new Function( ...parametersProps, code );
  27874. return this._method;
  27875. }
  27876. /**
  27877. * Frees all internal resources.
  27878. */
  27879. dispose() {
  27880. if ( this._method === null ) return;
  27881. if ( this._object && typeof this._object.dispose === 'function' ) {
  27882. this._object.dispose();
  27883. }
  27884. this._method = null;
  27885. this._object = null;
  27886. this._source = null;
  27887. this._value = null;
  27888. this._needsOutputUpdate = true;
  27889. this._output.value = null;
  27890. this._outputs = {};
  27891. }
  27892. setup() {
  27893. return this.getDefaultOutputNode();
  27894. }
  27895. getCacheKey( force ) {
  27896. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  27897. for ( const param in this.parameters ) {
  27898. values.push( this.parameters[ param ].getCacheKey( force ) );
  27899. }
  27900. return hashArray( values );
  27901. }
  27902. set needsUpdate( value ) {
  27903. if ( value === true ) this.dispose();
  27904. }
  27905. get needsUpdate() {
  27906. return this.source !== this._source;
  27907. }
  27908. /**
  27909. * Executes the `main` function of the script.
  27910. *
  27911. * @private
  27912. * @return {ScriptableNode} A reference to this node.
  27913. */
  27914. _exec() {
  27915. if ( this.codeNode === null ) return this;
  27916. if ( this._needsOutputUpdate === true ) {
  27917. this._value = this.call( 'main' );
  27918. this._needsOutputUpdate = false;
  27919. }
  27920. this._output.value = this._value;
  27921. return this;
  27922. }
  27923. /**
  27924. * Executes the refresh.
  27925. *
  27926. * @private
  27927. */
  27928. _refresh() {
  27929. this.needsUpdate = true;
  27930. this._exec();
  27931. this._output.refresh();
  27932. }
  27933. }
  27934. /**
  27935. * TSL function for creating a scriptable node.
  27936. *
  27937. * @tsl
  27938. * @function
  27939. * @param {CodeNode} [codeNode] - The code node.
  27940. * @param {?Object} [parameters={}] - The parameters definition.
  27941. * @returns {ScriptableNode}
  27942. */
  27943. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  27944. /**
  27945. * Returns a node that represents the `z` coordinate in view space
  27946. * for the current fragment. It's a different representation of the
  27947. * default depth value.
  27948. *
  27949. * This value can be part of a computation that defines how the fog
  27950. * density increases when moving away from the camera.
  27951. *
  27952. * @param {NodeBuilder} builder - The current node builder.
  27953. * @return {Node} The viewZ node.
  27954. */
  27955. function getViewZNode( builder ) {
  27956. let viewZ;
  27957. const getViewZ = builder.context.getViewZ;
  27958. if ( getViewZ !== undefined ) {
  27959. viewZ = getViewZ( this );
  27960. }
  27961. return ( viewZ || positionView.z ).negate();
  27962. }
  27963. /**
  27964. * Constructs a new range factor node.
  27965. *
  27966. * @tsl
  27967. * @function
  27968. * @param {Node} near - Defines the near value.
  27969. * @param {Node} far - Defines the far value.
  27970. */
  27971. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  27972. const viewZ = getViewZNode( builder );
  27973. return smoothstep( near, far, viewZ );
  27974. } );
  27975. /**
  27976. * Represents an exponential squared fog. This type of fog gives
  27977. * a clear view near the camera and a faster than exponentially
  27978. * densening fog farther from the camera.
  27979. *
  27980. * @tsl
  27981. * @function
  27982. * @param {Node} density - Defines the fog density.
  27983. */
  27984. const densityFogFactor = Fn( ( [ density ], builder ) => {
  27985. const viewZ = getViewZNode( builder );
  27986. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  27987. } );
  27988. /**
  27989. * This class can be used to configure a fog for the scene.
  27990. * Nodes of this type are assigned to `Scene.fogNode`.
  27991. *
  27992. * @tsl
  27993. * @function
  27994. * @param {Node} color - Defines the color of the fog.
  27995. * @param {Node} factor - Defines how the fog is factored in the scene.
  27996. */
  27997. const fog = Fn( ( [ color, factor ] ) => {
  27998. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  27999. } );
  28000. // Deprecated
  28001. /**
  28002. * @tsl
  28003. * @function
  28004. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  28005. *
  28006. * @param {Node} color
  28007. * @param {Node} near
  28008. * @param {Node} far
  28009. * @returns {Function}
  28010. */
  28011. function rangeFog( color, near, far ) { // @deprecated, r171
  28012. warn( 'TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  28013. return fog( color, rangeFogFactor( near, far ) );
  28014. }
  28015. /**
  28016. * @tsl
  28017. * @function
  28018. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  28019. *
  28020. * @param {Node} color
  28021. * @param {Node} density
  28022. * @returns {Function}
  28023. */
  28024. function densityFog( color, density ) { // @deprecated, r171
  28025. warn( 'TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  28026. return fog( color, densityFogFactor( density ) );
  28027. }
  28028. let min = null;
  28029. let max = null;
  28030. /**
  28031. * `RangeNode` generates random instanced attribute data in a defined range.
  28032. * An exemplary use case for this utility node is to generate random per-instance
  28033. * colors:
  28034. * ```js
  28035. * const material = new MeshBasicNodeMaterial();
  28036. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  28037. * const mesh = new InstancedMesh( geometry, material, count );
  28038. * ```
  28039. * @augments Node
  28040. */
  28041. class RangeNode extends Node {
  28042. static get type() {
  28043. return 'RangeNode';
  28044. }
  28045. /**
  28046. * Constructs a new range node.
  28047. *
  28048. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  28049. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  28050. */
  28051. constructor( minNode = float(), maxNode = float() ) {
  28052. super();
  28053. /**
  28054. * A node defining the lower bound of the range.
  28055. *
  28056. * @type {Node<any>}
  28057. * @default float()
  28058. */
  28059. this.minNode = minNode;
  28060. /**
  28061. * A node defining the upper bound of the range.
  28062. *
  28063. * @type {Node<any>}
  28064. * @default float()
  28065. */
  28066. this.maxNode = maxNode;
  28067. }
  28068. /**
  28069. * Returns the vector length which is computed based on the range definition.
  28070. *
  28071. * @param {NodeBuilder} builder - The current node builder.
  28072. * @return {number} The vector length.
  28073. */
  28074. getVectorLength( builder ) {
  28075. const minNode = this.getConstNode( this.minNode );
  28076. const maxNode = this.getConstNode( this.maxNode );
  28077. const minLength = builder.getTypeLength( getValueType( minNode.value ) );
  28078. const maxLength = builder.getTypeLength( getValueType( maxNode.value ) );
  28079. return minLength > maxLength ? minLength : maxLength;
  28080. }
  28081. /**
  28082. * This method is overwritten since the node type is inferred from range definition.
  28083. *
  28084. * @param {NodeBuilder} builder - The current node builder.
  28085. * @return {string} The node type.
  28086. */
  28087. getNodeType( builder ) {
  28088. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  28089. }
  28090. /**
  28091. * Returns a constant node from the given node by traversing it.
  28092. *
  28093. * @param {Node} node - The node to traverse.
  28094. * @returns {Node} The constant node, if found.
  28095. */
  28096. getConstNode( node ) {
  28097. let output = null;
  28098. node.traverse( n => {
  28099. if ( n.isConstNode === true ) {
  28100. output = n;
  28101. }
  28102. } );
  28103. if ( output === null ) {
  28104. throw new Error( 'THREE.TSL: No "ConstNode" found in node graph.' );
  28105. }
  28106. return output;
  28107. }
  28108. setup( builder ) {
  28109. const object = builder.object;
  28110. let output = null;
  28111. if ( object.count > 1 ) {
  28112. const minNode = this.getConstNode( this.minNode );
  28113. const maxNode = this.getConstNode( this.maxNode );
  28114. const minValue = minNode.value;
  28115. const maxValue = maxNode.value;
  28116. const minLength = builder.getTypeLength( getValueType( minValue ) );
  28117. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  28118. min = min || new Vector4();
  28119. max = max || new Vector4();
  28120. min.setScalar( 0 );
  28121. max.setScalar( 0 );
  28122. if ( minLength === 1 ) min.setScalar( minValue );
  28123. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  28124. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  28125. if ( maxLength === 1 ) max.setScalar( maxValue );
  28126. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  28127. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  28128. const stride = 4;
  28129. const length = stride * object.count;
  28130. const array = new Float32Array( length );
  28131. for ( let i = 0; i < length; i ++ ) {
  28132. const index = i % stride;
  28133. const minElementValue = min.getComponent( index );
  28134. const maxElementValue = max.getComponent( index );
  28135. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  28136. }
  28137. const nodeType = this.getNodeType( builder );
  28138. if ( object.count <= 4096 ) {
  28139. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  28140. } else {
  28141. // TODO: Improve anonymous buffer attribute creation removing this part
  28142. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  28143. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  28144. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  28145. }
  28146. } else {
  28147. output = float( 0 );
  28148. }
  28149. return output;
  28150. }
  28151. }
  28152. /**
  28153. * TSL function for creating a range node.
  28154. *
  28155. * @tsl
  28156. * @function
  28157. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  28158. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  28159. * @returns {RangeNode}
  28160. */
  28161. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  28162. /**
  28163. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  28164. * about the currently running dispatch and/or the device it is running on.
  28165. *
  28166. * This node can only be used with a WebGPU backend.
  28167. *
  28168. * @augments Node
  28169. */
  28170. class ComputeBuiltinNode extends Node {
  28171. static get type() {
  28172. return 'ComputeBuiltinNode';
  28173. }
  28174. /**
  28175. * Constructs a new compute builtin node.
  28176. *
  28177. * @param {string} builtinName - The built-in name.
  28178. * @param {string} nodeType - The node type.
  28179. */
  28180. constructor( builtinName, nodeType ) {
  28181. super( nodeType );
  28182. /**
  28183. * The built-in name.
  28184. *
  28185. * @private
  28186. * @type {string}
  28187. */
  28188. this._builtinName = builtinName;
  28189. }
  28190. /**
  28191. * This method is overwritten since hash is derived from the built-in name.
  28192. *
  28193. * @param {NodeBuilder} builder - The current node builder.
  28194. * @return {string} The hash.
  28195. */
  28196. getHash( builder ) {
  28197. return this.getBuiltinName( builder );
  28198. }
  28199. /**
  28200. * This method is overwritten since the node type is simply derived from `nodeType`..
  28201. *
  28202. * @param {NodeBuilder} builder - The current node builder.
  28203. * @return {string} The node type.
  28204. */
  28205. getNodeType( /*builder*/ ) {
  28206. return this.nodeType;
  28207. }
  28208. /**
  28209. * Sets the builtin name.
  28210. *
  28211. * @param {string} builtinName - The built-in name.
  28212. * @return {ComputeBuiltinNode} A reference to this node.
  28213. */
  28214. setBuiltinName( builtinName ) {
  28215. this._builtinName = builtinName;
  28216. return this;
  28217. }
  28218. /**
  28219. * Returns the builtin name.
  28220. *
  28221. * @param {NodeBuilder} builder - The current node builder.
  28222. * @return {string} The builtin name.
  28223. */
  28224. getBuiltinName( /*builder*/ ) {
  28225. return this._builtinName;
  28226. }
  28227. /**
  28228. * Whether the current node builder has the builtin or not.
  28229. *
  28230. * @param {NodeBuilder} builder - The current node builder.
  28231. * @return {boolean} Whether the builder has the builtin or not.
  28232. */
  28233. hasBuiltin( builder ) {
  28234. return builder.hasBuiltin( this._builtinName );
  28235. }
  28236. generate( builder, output ) {
  28237. const builtinName = this.getBuiltinName( builder );
  28238. const nodeType = this.getNodeType( builder );
  28239. if ( builder.shaderStage === 'compute' ) {
  28240. return builder.format( builtinName, nodeType, output );
  28241. } else {
  28242. warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  28243. return builder.generateConst( nodeType );
  28244. }
  28245. }
  28246. serialize( data ) {
  28247. super.serialize( data );
  28248. data.global = this.global;
  28249. data._builtinName = this._builtinName;
  28250. }
  28251. deserialize( data ) {
  28252. super.deserialize( data );
  28253. this.global = data.global;
  28254. this._builtinName = data._builtinName;
  28255. }
  28256. }
  28257. /**
  28258. * TSL function for creating a compute builtin node.
  28259. *
  28260. * @tsl
  28261. * @function
  28262. * @param {string} name - The built-in name.
  28263. * @param {string} nodeType - The node type.
  28264. * @returns {ComputeBuiltinNode}
  28265. */
  28266. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  28267. /**
  28268. * Represents the number of workgroups dispatched by the compute shader.
  28269. * ```js
  28270. * // Run 512 invocations/threads with a workgroup size of 128.
  28271. * const computeFn = Fn(() => {
  28272. *
  28273. * // numWorkgroups.x = 4
  28274. * storageBuffer.element(0).assign(numWorkgroups.x)
  28275. *
  28276. * })().compute(512, [128]);
  28277. *
  28278. * // Run 512 invocations/threads with the default workgroup size of 64.
  28279. * const computeFn = Fn(() => {
  28280. *
  28281. * // numWorkgroups.x = 8
  28282. * storageBuffer.element(0).assign(numWorkgroups.x)
  28283. *
  28284. * })().compute(512);
  28285. * ```
  28286. *
  28287. * @tsl
  28288. * @type {ComputeBuiltinNode<uvec3>}
  28289. */
  28290. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  28291. /**
  28292. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  28293. * ```js
  28294. * // Execute 12 compute threads with a workgroup size of 3.
  28295. * const computeFn = Fn( () => {
  28296. *
  28297. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  28298. *
  28299. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  28300. *
  28301. * } ).Else( () => {
  28302. *
  28303. * storageBuffer.element( instanceIndex ).assign( 0 );
  28304. *
  28305. * } );
  28306. *
  28307. * } )().compute( 12, [ 3 ] );
  28308. *
  28309. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  28310. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  28311. * ```
  28312. *
  28313. * @tsl
  28314. * @type {ComputeBuiltinNode<uvec3>}
  28315. */
  28316. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  28317. /**
  28318. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  28319. *
  28320. * @tsl
  28321. * @type {ComputeBuiltinNode<uvec3>}
  28322. */
  28323. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  28324. /**
  28325. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  28326. *
  28327. * @tsl
  28328. * @type {ComputeBuiltinNode<uvec3>}
  28329. */
  28330. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  28331. /**
  28332. * A device dependent variable that exposes the size of the current invocation's subgroup.
  28333. *
  28334. * @tsl
  28335. * @type {ComputeBuiltinNode<uint>}
  28336. */
  28337. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  28338. /**
  28339. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  28340. *
  28341. * This node can only be used with a WebGPU backend.
  28342. *
  28343. * @augments Node
  28344. */
  28345. class BarrierNode extends Node {
  28346. /**
  28347. * Constructs a new barrier node.
  28348. *
  28349. * @param {string} scope - The scope defines the behavior of the node.
  28350. */
  28351. constructor( scope ) {
  28352. super();
  28353. this.scope = scope;
  28354. }
  28355. generate( builder ) {
  28356. const { scope } = this;
  28357. const { renderer } = builder;
  28358. if ( renderer.backend.isWebGLBackend === true ) {
  28359. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  28360. } else {
  28361. builder.addLineFlowCode( `${scope}Barrier()`, this );
  28362. }
  28363. }
  28364. }
  28365. /**
  28366. * TSL function for creating a barrier node.
  28367. *
  28368. * @tsl
  28369. * @function
  28370. * @param {string} scope - The scope defines the behavior of the node..
  28371. * @returns {BarrierNode}
  28372. */
  28373. const barrier = nodeProxy( BarrierNode );
  28374. /**
  28375. * TSL function for creating a workgroup barrier. All compute shader
  28376. * invocations must wait for each invocation within a workgroup to
  28377. * complete before the barrier can be surpassed.
  28378. *
  28379. * @tsl
  28380. * @function
  28381. * @returns {BarrierNode}
  28382. */
  28383. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  28384. /**
  28385. * TSL function for creating a storage barrier. All invocations must
  28386. * wait for each access to variables within the 'storage' address space
  28387. * to complete before the barrier can be passed.
  28388. *
  28389. * @tsl
  28390. * @function
  28391. * @returns {BarrierNode}
  28392. */
  28393. const storageBarrier = () => barrier( 'storage' ).toStack();
  28394. /**
  28395. * TSL function for creating a texture barrier. All invocations must
  28396. * wait for each access to variables within the 'texture' address space
  28397. * to complete before the barrier can be passed.
  28398. *
  28399. * @tsl
  28400. * @function
  28401. * @returns {BarrierNode}
  28402. */
  28403. const textureBarrier = () => barrier( 'texture' ).toStack();
  28404. /**
  28405. * Represents an element of a 'workgroup' scoped buffer.
  28406. *
  28407. * @augments ArrayElementNode
  28408. */
  28409. class WorkgroupInfoElementNode extends ArrayElementNode {
  28410. /**
  28411. * Constructs a new workgroup info element node.
  28412. *
  28413. * @param {Node} workgroupInfoNode - The workgroup info node.
  28414. * @param {Node} indexNode - The index node that defines the element access.
  28415. */
  28416. constructor( workgroupInfoNode, indexNode ) {
  28417. super( workgroupInfoNode, indexNode );
  28418. /**
  28419. * This flag can be used for type testing.
  28420. *
  28421. * @type {boolean}
  28422. * @readonly
  28423. * @default true
  28424. */
  28425. this.isWorkgroupInfoElementNode = true;
  28426. }
  28427. generate( builder, output ) {
  28428. let snippet;
  28429. const isAssignContext = builder.context.assign;
  28430. snippet = super.generate( builder );
  28431. if ( isAssignContext !== true ) {
  28432. const type = this.getNodeType( builder );
  28433. snippet = builder.format( snippet, type, output );
  28434. }
  28435. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  28436. return snippet;
  28437. }
  28438. }
  28439. /**
  28440. * A node allowing the user to create a 'workgroup' scoped buffer within the
  28441. * context of a compute shader. Typically, workgroup scoped buffers are
  28442. * created to hold data that is transferred from a global storage scope into
  28443. * a local workgroup scope. For invocations within a workgroup, data
  28444. * access speeds on 'workgroup' scoped buffers can be significantly faster
  28445. * than similar access operations on globally accessible storage buffers.
  28446. *
  28447. * This node can only be used with a WebGPU backend.
  28448. *
  28449. * @augments Node
  28450. */
  28451. class WorkgroupInfoNode extends Node {
  28452. /**
  28453. * Constructs a new buffer scoped to type scope.
  28454. *
  28455. * @param {string} scope - TODO.
  28456. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  28457. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  28458. */
  28459. constructor( scope, bufferType, bufferCount = 0 ) {
  28460. super( bufferType );
  28461. /**
  28462. * The buffer type.
  28463. *
  28464. * @type {string}
  28465. */
  28466. this.bufferType = bufferType;
  28467. /**
  28468. * The buffer count.
  28469. *
  28470. * @type {number}
  28471. * @default 0
  28472. */
  28473. this.bufferCount = bufferCount;
  28474. /**
  28475. * This flag can be used for type testing.
  28476. *
  28477. * @type {boolean}
  28478. * @readonly
  28479. * @default true
  28480. */
  28481. this.isWorkgroupInfoNode = true;
  28482. /**
  28483. * The data type of the array buffer.
  28484. *
  28485. * @type {string}
  28486. */
  28487. this.elementType = bufferType;
  28488. /**
  28489. * TODO.
  28490. *
  28491. * @type {string}
  28492. */
  28493. this.scope = scope;
  28494. /**
  28495. * The name of the workgroup scoped buffer.
  28496. *
  28497. * @type {string}
  28498. * @default ''
  28499. */
  28500. this.name = '';
  28501. }
  28502. /**
  28503. * Sets the name of this node.
  28504. *
  28505. * @param {string} name - The name to set.
  28506. * @return {WorkgroupInfoNode} A reference to this node.
  28507. */
  28508. setName( name ) {
  28509. this.name = name;
  28510. return this;
  28511. }
  28512. /**
  28513. * Sets the name/label of this node.
  28514. *
  28515. * @deprecated
  28516. * @param {string} name - The name to set.
  28517. * @return {WorkgroupInfoNode} A reference to this node.
  28518. */
  28519. label( name ) {
  28520. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  28521. return this.setName( name );
  28522. }
  28523. /**
  28524. * Sets the scope of this node.
  28525. *
  28526. * @param {string} scope - The scope to set.
  28527. * @return {WorkgroupInfoNode} A reference to this node.
  28528. */
  28529. setScope( scope ) {
  28530. this.scope = scope;
  28531. return this;
  28532. }
  28533. /**
  28534. * The data type of the array buffer.
  28535. *
  28536. * @return {string} The element type.
  28537. */
  28538. getElementType() {
  28539. return this.elementType;
  28540. }
  28541. /**
  28542. * Overwrites the default implementation since the input type
  28543. * is inferred from the scope.
  28544. *
  28545. * @param {NodeBuilder} builder - The current node builder.
  28546. * @return {string} The input type.
  28547. */
  28548. getInputType( /*builder*/ ) {
  28549. return `${this.scope}Array`;
  28550. }
  28551. /**
  28552. * This method can be used to access elements via an index node.
  28553. *
  28554. * @param {IndexNode} indexNode - indexNode.
  28555. * @return {WorkgroupInfoElementNode} A reference to an element.
  28556. */
  28557. element( indexNode ) {
  28558. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  28559. }
  28560. generate( builder ) {
  28561. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  28562. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  28563. }
  28564. }
  28565. /**
  28566. * TSL function for creating a workgroup info node.
  28567. * Creates a new 'workgroup' scoped array buffer.
  28568. *
  28569. * @tsl
  28570. * @function
  28571. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  28572. * @param {number} [count=0] - The number of elements in the buffer.
  28573. * @returns {WorkgroupInfoNode}
  28574. */
  28575. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  28576. /**
  28577. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  28578. * within a shader. In an atomic function, any modification to an atomic variable will
  28579. * occur as an indivisible step with a defined order relative to other modifications.
  28580. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  28581. * atomic operations will not interfere with each other.
  28582. *
  28583. * This node can only be used with a WebGPU backend.
  28584. *
  28585. * @augments Node
  28586. */
  28587. class AtomicFunctionNode extends Node {
  28588. static get type() {
  28589. return 'AtomicFunctionNode';
  28590. }
  28591. /**
  28592. * Constructs a new atomic function node.
  28593. *
  28594. * @param {string} method - The signature of the atomic function to construct.
  28595. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28596. * @param {Node} valueNode - The value that mutates the atomic variable.
  28597. */
  28598. constructor( method, pointerNode, valueNode ) {
  28599. super( 'uint' );
  28600. /**
  28601. * The signature of the atomic function to construct.
  28602. *
  28603. * @type {string}
  28604. */
  28605. this.method = method;
  28606. /**
  28607. * An atomic variable or element of an atomic buffer.
  28608. *
  28609. * @type {Node}
  28610. */
  28611. this.pointerNode = pointerNode;
  28612. /**
  28613. * A value that modifies the atomic variable.
  28614. *
  28615. * @type {Node}
  28616. */
  28617. this.valueNode = valueNode;
  28618. /**
  28619. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  28620. *
  28621. * @type {boolean}
  28622. * @default true
  28623. */
  28624. this.parents = true;
  28625. }
  28626. /**
  28627. * Overwrites the default implementation to return the type of
  28628. * the pointer node.
  28629. *
  28630. * @param {NodeBuilder} builder - The current node builder.
  28631. * @return {string} The input type.
  28632. */
  28633. getInputType( builder ) {
  28634. return this.pointerNode.getNodeType( builder );
  28635. }
  28636. /**
  28637. * Overwritten since the node type is inferred from the input type.
  28638. *
  28639. * @param {NodeBuilder} builder - The current node builder.
  28640. * @return {string} The node type.
  28641. */
  28642. getNodeType( builder ) {
  28643. return this.getInputType( builder );
  28644. }
  28645. generate( builder ) {
  28646. const properties = builder.getNodeProperties( this );
  28647. const parents = properties.parents;
  28648. const method = this.method;
  28649. const type = this.getNodeType( builder );
  28650. const inputType = this.getInputType( builder );
  28651. const a = this.pointerNode;
  28652. const b = this.valueNode;
  28653. const params = [];
  28654. params.push( `&${ a.build( builder, inputType ) }` );
  28655. if ( b !== null ) {
  28656. params.push( b.build( builder, inputType ) );
  28657. }
  28658. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  28659. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  28660. if ( isVoid ) {
  28661. builder.addLineFlowCode( methodSnippet, this );
  28662. } else {
  28663. if ( properties.constNode === undefined ) {
  28664. properties.constNode = expression( methodSnippet, type ).toConst();
  28665. }
  28666. return properties.constNode.build( builder );
  28667. }
  28668. }
  28669. }
  28670. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  28671. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  28672. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  28673. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  28674. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  28675. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  28676. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  28677. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  28678. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  28679. /**
  28680. * TSL function for creating an atomic function node.
  28681. *
  28682. * @tsl
  28683. * @function
  28684. * @param {string} method - The signature of the atomic function to construct.
  28685. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28686. * @param {Node} valueNode - The value that mutates the atomic variable.
  28687. * @returns {AtomicFunctionNode}
  28688. */
  28689. const atomicNode = nodeProxy( AtomicFunctionNode );
  28690. /**
  28691. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  28692. *
  28693. * @tsl
  28694. * @function
  28695. * @param {string} method - The signature of the atomic function to construct.
  28696. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28697. * @param {Node} valueNode - The value that mutates the atomic variable.
  28698. * @returns {AtomicFunctionNode}
  28699. */
  28700. const atomicFunc = ( method, pointerNode, valueNode ) => {
  28701. return atomicNode( method, pointerNode, valueNode ).toStack();
  28702. };
  28703. /**
  28704. * Loads the value stored in the atomic variable.
  28705. *
  28706. * @tsl
  28707. * @function
  28708. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28709. * @returns {AtomicFunctionNode}
  28710. */
  28711. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  28712. /**
  28713. * Stores a value in the atomic variable.
  28714. *
  28715. * @tsl
  28716. * @function
  28717. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28718. * @param {Node} valueNode - The value that mutates the atomic variable.
  28719. * @returns {AtomicFunctionNode}
  28720. */
  28721. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  28722. /**
  28723. * Increments the value stored in the atomic variable.
  28724. *
  28725. * @tsl
  28726. * @function
  28727. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28728. * @param {Node} valueNode - The value that mutates the atomic variable.
  28729. * @returns {AtomicFunctionNode}
  28730. */
  28731. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  28732. /**
  28733. * Decrements the value stored in the atomic variable.
  28734. *
  28735. * @tsl
  28736. * @function
  28737. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28738. * @param {Node} valueNode - The value that mutates the atomic variable.
  28739. * @returns {AtomicFunctionNode}
  28740. */
  28741. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  28742. /**
  28743. * Stores in an atomic variable the maximum between its current value and a parameter.
  28744. *
  28745. * @tsl
  28746. * @function
  28747. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28748. * @param {Node} valueNode - The value that mutates the atomic variable.
  28749. * @returns {AtomicFunctionNode}
  28750. */
  28751. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  28752. /**
  28753. * Stores in an atomic variable the minimum between its current value and a parameter.
  28754. *
  28755. * @tsl
  28756. * @function
  28757. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28758. * @param {Node} valueNode - The value that mutates the atomic variable.
  28759. * @returns {AtomicFunctionNode}
  28760. */
  28761. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  28762. /**
  28763. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  28764. *
  28765. * @tsl
  28766. * @function
  28767. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28768. * @param {Node} valueNode - The value that mutates the atomic variable.
  28769. * @returns {AtomicFunctionNode}
  28770. */
  28771. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  28772. /**
  28773. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  28774. *
  28775. * @tsl
  28776. * @function
  28777. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28778. * @param {Node} valueNode - The value that mutates the atomic variable.
  28779. * @returns {AtomicFunctionNode}
  28780. */
  28781. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  28782. /**
  28783. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  28784. *
  28785. * @tsl
  28786. * @function
  28787. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28788. * @param {Node} valueNode - The value that mutates the atomic variable.
  28789. * @returns {AtomicFunctionNode}
  28790. */
  28791. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  28792. /**
  28793. * This class represents a set of built in WGSL shader functions that sync
  28794. * synchronously execute an operation across a subgroup, or 'warp', of compute
  28795. * or fragment shader invocations within a workgroup. Typically, these functions
  28796. * will synchronously execute an operation using data from all active invocations
  28797. * within the subgroup, then broadcast that result to all active invocations. In
  28798. * other graphics APIs, subgroup functions are also referred to as wave intrinsics
  28799. * (DirectX/HLSL) or warp intrinsics (CUDA).
  28800. *
  28801. * @augments TempNode
  28802. */
  28803. class SubgroupFunctionNode extends TempNode {
  28804. static get type() {
  28805. return 'SubgroupFunctionNode';
  28806. }
  28807. /**
  28808. * Constructs a new function node.
  28809. *
  28810. * @param {string} method - The subgroup/wave intrinsic method to construct.
  28811. * @param {Node} [aNode=null] - The method's first argument.
  28812. * @param {Node} [bNode=null] - The method's second argument.
  28813. */
  28814. constructor( method, aNode = null, bNode = null ) {
  28815. super();
  28816. /**
  28817. * The subgroup/wave intrinsic method to construct.
  28818. *
  28819. * @type {String}
  28820. */
  28821. this.method = method;
  28822. /**
  28823. * The method's first argument.
  28824. *
  28825. * @type {Node}
  28826. */
  28827. this.aNode = aNode;
  28828. /**
  28829. * The method's second argument.
  28830. *
  28831. * @type {Node}
  28832. */
  28833. this.bNode = bNode;
  28834. }
  28835. getInputType( builder ) {
  28836. const aType = this.aNode ? this.aNode.getNodeType( builder ) : null;
  28837. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  28838. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  28839. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  28840. if ( aLen > bLen ) {
  28841. return aType;
  28842. } else {
  28843. return bType;
  28844. }
  28845. }
  28846. getNodeType( builder ) {
  28847. const method = this.method;
  28848. if ( method === SubgroupFunctionNode.SUBGROUP_ELECT ) {
  28849. return 'bool';
  28850. } else if ( method === SubgroupFunctionNode.SUBGROUP_BALLOT ) {
  28851. return 'uvec4';
  28852. } else {
  28853. return this.getInputType( builder );
  28854. }
  28855. }
  28856. generate( builder, output ) {
  28857. const method = this.method;
  28858. const type = this.getNodeType( builder );
  28859. const inputType = this.getInputType( builder );
  28860. const a = this.aNode;
  28861. const b = this.bNode;
  28862. const params = [];
  28863. if (
  28864. method === SubgroupFunctionNode.SUBGROUP_BROADCAST ||
  28865. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE ||
  28866. method === SubgroupFunctionNode.QUAD_BROADCAST
  28867. ) {
  28868. const bType = b.getNodeType( builder );
  28869. params.push(
  28870. a.build( builder, type ),
  28871. b.build( builder, bType === 'float' ? 'int' : type )
  28872. );
  28873. } else if (
  28874. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ||
  28875. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ||
  28876. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP
  28877. ) {
  28878. params.push(
  28879. a.build( builder, type ),
  28880. b.build( builder, 'uint' )
  28881. );
  28882. } else {
  28883. if ( a !== null ) params.push( a.build( builder, inputType ) );
  28884. if ( b !== null ) params.push( b.build( builder, inputType ) );
  28885. }
  28886. const paramsString = params.length === 0 ? '()' : `( ${params.join( ', ' )} )`;
  28887. return builder.format( `${ builder.getMethod( method, type ) }${paramsString}`, type, output );
  28888. }
  28889. serialize( data ) {
  28890. super.serialize( data );
  28891. data.method = this.method;
  28892. }
  28893. deserialize( data ) {
  28894. super.deserialize( data );
  28895. this.method = data.method;
  28896. }
  28897. }
  28898. // 0 inputs
  28899. SubgroupFunctionNode.SUBGROUP_ELECT = 'subgroupElect';
  28900. // 1 input
  28901. SubgroupFunctionNode.SUBGROUP_BALLOT = 'subgroupBallot';
  28902. SubgroupFunctionNode.SUBGROUP_ADD = 'subgroupAdd';
  28903. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD = 'subgroupInclusiveAdd';
  28904. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND = 'subgroupExclusiveAdd';
  28905. SubgroupFunctionNode.SUBGROUP_MUL = 'subgroupMul';
  28906. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL = 'subgroupInclusiveMul';
  28907. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL = 'subgroupExclusiveMul';
  28908. SubgroupFunctionNode.SUBGROUP_AND = 'subgroupAnd';
  28909. SubgroupFunctionNode.SUBGROUP_OR = 'subgroupOr';
  28910. SubgroupFunctionNode.SUBGROUP_XOR = 'subgroupXor';
  28911. SubgroupFunctionNode.SUBGROUP_MIN = 'subgroupMin';
  28912. SubgroupFunctionNode.SUBGROUP_MAX = 'subgroupMax';
  28913. SubgroupFunctionNode.SUBGROUP_ALL = 'subgroupAll';
  28914. SubgroupFunctionNode.SUBGROUP_ANY = 'subgroupAny';
  28915. SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST = 'subgroupBroadcastFirst';
  28916. SubgroupFunctionNode.QUAD_SWAP_X = 'quadSwapX';
  28917. SubgroupFunctionNode.QUAD_SWAP_Y = 'quadSwapY';
  28918. SubgroupFunctionNode.QUAD_SWAP_DIAGONAL = 'quadSwapDiagonal';
  28919. // 2 inputs
  28920. SubgroupFunctionNode.SUBGROUP_BROADCAST = 'subgroupBroadcast';
  28921. SubgroupFunctionNode.SUBGROUP_SHUFFLE = 'subgroupShuffle';
  28922. SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR = 'subgroupShuffleXor';
  28923. SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP = 'subgroupShuffleUp';
  28924. SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN = 'subgroupShuffleDown';
  28925. SubgroupFunctionNode.QUAD_BROADCAST = 'quadBroadcast';
  28926. /**
  28927. * Returns true if this invocation has the lowest subgroup_invocation_id
  28928. * among active invocations in the subgroup.
  28929. *
  28930. * @tsl
  28931. * @method
  28932. * @return {bool} The result of the computation.
  28933. */
  28934. const subgroupElect = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ELECT ).setParameterLength( 0 );
  28935. /**
  28936. * Returns a set of bitfields where the bit corresponding to subgroup_invocation_id
  28937. * is 1 if pred is true for that active invocation and 0 otherwise.
  28938. *
  28939. * @tsl
  28940. * @method
  28941. * @param {bool} pred - A boolean that sets the bit corresponding to the invocations subgroup invocation id.
  28942. * @return {vec4<u32>}- A bitfield corresponding to the pred value of each subgroup invocation.
  28943. */
  28944. const subgroupBallot = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BALLOT ).setParameterLength( 1 );
  28945. /**
  28946. * A reduction that adds e among all active invocations and returns that result.
  28947. *
  28948. * @tsl
  28949. * @method
  28950. * @param {number} e - The value provided to the reduction by the current invocation.
  28951. * @return {number} The accumulated result of the reduction operation.
  28952. */
  28953. const subgroupAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ADD ).setParameterLength( 1 );
  28954. /**
  28955. * An inclusive scan returning the sum of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  28956. *
  28957. * @tsl
  28958. * @method
  28959. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  28960. * @return {number} The accumulated result of the inclusive scan operation.
  28961. */
  28962. const subgroupInclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD ).setParameterLength( 1 );
  28963. /**
  28964. * An exclusive scan that returns the sum of e for all active invocations with subgroup_invocation_id less than this invocation.
  28965. *
  28966. * @tsl
  28967. * @method
  28968. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  28969. * @return {number} The accumulated result of the exclusive scan operation.
  28970. */
  28971. const subgroupExclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND ).setParameterLength( 1 );
  28972. /**
  28973. * A reduction that multiplies e among all active invocations and returns that result.
  28974. *
  28975. * @tsl
  28976. * @method
  28977. * @param {number} e - The value provided to the reduction by the current invocation.
  28978. * @return {number} The accumulated result of the reduction operation.
  28979. */
  28980. const subgroupMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MUL ).setParameterLength( 1 );
  28981. /**
  28982. * An inclusive scan returning the product of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  28983. *
  28984. * @tsl
  28985. * @method
  28986. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  28987. * @return {number} The accumulated result of the inclusive scan operation.
  28988. */
  28989. const subgroupInclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL ).setParameterLength( 1 );
  28990. /**
  28991. * An exclusive scan that returns the product of e for all active invocations with subgroup_invocation_id less than this invocation.
  28992. *
  28993. * @tsl
  28994. * @method
  28995. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  28996. * @return {number} The accumulated result of the exclusive scan operation.
  28997. */
  28998. const subgroupExclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL ).setParameterLength( 1 );
  28999. /**
  29000. * A reduction that performs a bitwise and of e among all active invocations and returns that result.
  29001. *
  29002. * @tsl
  29003. * @method
  29004. * @param {number} e - The value provided to the reduction by the current invocation.
  29005. * @return {number} The result of the reduction operation.
  29006. */
  29007. const subgroupAnd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_AND ).setParameterLength( 1 );
  29008. /**
  29009. * A reduction that performs a bitwise or of e among all active invocations and returns that result.
  29010. *
  29011. * @tsl
  29012. * @method
  29013. * @param {number} e - The value provided to the reduction by the current invocation.
  29014. * @return {number} The result of the reduction operation.
  29015. */
  29016. const subgroupOr = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_OR ).setParameterLength( 1 );
  29017. /**
  29018. * A reduction that performs a bitwise xor of e among all active invocations and returns that result.
  29019. *
  29020. * @tsl
  29021. * @method
  29022. * @param {number} e - The value provided to the reduction by the current invocation.
  29023. * @return {number} The result of the reduction operation.
  29024. */
  29025. const subgroupXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_XOR ).setParameterLength( 1 );
  29026. /**
  29027. * A reduction that performs a min of e among all active invocations and returns that result.
  29028. *
  29029. * @tsl
  29030. * @method
  29031. * @param {number} e - The value provided to the reduction by the current invocation.
  29032. * @return {number} The result of the reduction operation.
  29033. */
  29034. const subgroupMin = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MIN ).setParameterLength( 1 );
  29035. /**
  29036. * A reduction that performs a max of e among all active invocations and returns that result.
  29037. *
  29038. * @tsl
  29039. * @method
  29040. * @param {number} e - The value provided to the reduction by the current invocation.
  29041. * @return {number} The result of the reduction operation.
  29042. */
  29043. const subgroupMax = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MAX ).setParameterLength( 1 );
  29044. /**
  29045. * Returns true if e is true for all active invocations in the subgroup.
  29046. *
  29047. * @tsl
  29048. * @method
  29049. * @return {bool} The result of the computation.
  29050. */
  29051. const subgroupAll = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ALL ).setParameterLength( 0 );
  29052. /**
  29053. * Returns true if e is true for any active invocation in the subgroup
  29054. *
  29055. * @tsl
  29056. * @method
  29057. * @return {bool} The result of the computation.
  29058. */
  29059. const subgroupAny = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ANY ).setParameterLength( 0 );
  29060. /**
  29061. * Broadcasts e from the active invocation with the lowest subgroup_invocation_id in the subgroup to all other active invocations.
  29062. *
  29063. * @tsl
  29064. * @method
  29065. * @param {number} e - The value to broadcast from the lowest subgroup invocation.
  29066. * @param {number} id - The subgroup invocation to broadcast from.
  29067. * @return {number} The broadcast value.
  29068. */
  29069. const subgroupBroadcastFirst = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST ).setParameterLength( 2 );
  29070. /**
  29071. * Swaps e between invocations in the quad in the X direction.
  29072. *
  29073. * @tsl
  29074. * @method
  29075. * @param {number} e - The value to swap from the current invocation.
  29076. * @return {number} The value received from the swap operation.
  29077. */
  29078. const quadSwapX = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_X ).setParameterLength( 1 );
  29079. /**
  29080. * Swaps e between invocations in the quad in the Y direction.
  29081. *
  29082. * @tsl
  29083. * @method
  29084. * @param {number} e - The value to swap from the current invocation.
  29085. * @return {number} The value received from the swap operation.
  29086. */
  29087. const quadSwapY = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_Y ).setParameterLength( 1 );
  29088. /**
  29089. * Swaps e between invocations in the quad diagonally.
  29090. *
  29091. * @tsl
  29092. * @method
  29093. * @param {number} e - The value to swap from the current invocation.
  29094. * @return {number} The value received from the swap operation.
  29095. */
  29096. const quadSwapDiagonal = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_DIAGONAL ).setParameterLength( 1 );
  29097. /**
  29098. * Broadcasts e from the invocation whose subgroup_invocation_id matches id, to all active invocations.
  29099. *
  29100. * @tsl
  29101. * @method
  29102. * @param {number} e - The value to broadcast from subgroup invocation 'id'.
  29103. * @param {number} id - The subgroup invocation to broadcast from.
  29104. * @return {number} The broadcast value.
  29105. */
  29106. const subgroupBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST ).setParameterLength( 2 );
  29107. /**
  29108. * Returns v from the active invocation whose subgroup_invocation_id matches id
  29109. *
  29110. * @tsl
  29111. * @method
  29112. * @param {number} v - The value to return from subgroup invocation id^mask.
  29113. * @param {number} id - The subgroup invocation which returns the value v.
  29114. * @return {number} The broadcast value.
  29115. */
  29116. const subgroupShuffle = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE ).setParameterLength( 2 );
  29117. /**
  29118. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id ^ mask.
  29119. *
  29120. * @tsl
  29121. * @method
  29122. * @param {number} v - The value to return from subgroup invocation id^mask.
  29123. * @param {number} mask - A bitmask that determines the target invocation via a XOR operation.
  29124. * @return {number} The broadcast value.
  29125. */
  29126. const subgroupShuffleXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ).setParameterLength( 2 );
  29127. /**
  29128. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id - delta
  29129. *
  29130. * @tsl
  29131. * @method
  29132. * @param {number} v - The value to return from subgroup invocation id^mask.
  29133. * @param {number} delta - A value that offsets the current in.
  29134. * @return {number} The broadcast value.
  29135. */
  29136. const subgroupShuffleUp = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP ).setParameterLength( 2 );
  29137. /**
  29138. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id + delta
  29139. *
  29140. * @tsl
  29141. * @method
  29142. * @param {number} v - The value to return from subgroup invocation id^mask.
  29143. * @param {number} delta - A value that offsets the current subgroup invocation.
  29144. * @return {number} The broadcast value.
  29145. */
  29146. const subgroupShuffleDown = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ).setParameterLength( 2 );
  29147. /**
  29148. * Broadcasts e from the quad invocation with id equal to id.
  29149. *
  29150. * @tsl
  29151. * @method
  29152. * @param {number} e - The value to broadcast.
  29153. * @return {number} The broadcast value.
  29154. */
  29155. const quadBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_BROADCAST ).setParameterLength( 1 );
  29156. let uniformsLib;
  29157. function getLightData( light ) {
  29158. uniformsLib = uniformsLib || new WeakMap();
  29159. let uniforms = uniformsLib.get( light );
  29160. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  29161. return uniforms;
  29162. }
  29163. /**
  29164. * TSL function for getting a shadow matrix uniform node for the given light.
  29165. *
  29166. * @tsl
  29167. * @function
  29168. * @param {Light} light -The light source.
  29169. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  29170. */
  29171. function lightShadowMatrix( light ) {
  29172. const data = getLightData( light );
  29173. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  29174. // normally, shadow matrices are updated in ShadowNode. However, if the shadow matrix is used outside
  29175. // of shadow rendering (like in ProjectorLightNode), the shadow matrix still requires an update
  29176. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  29177. if ( light.shadow.camera.coordinateSystem !== frame.camera.coordinateSystem ) {
  29178. light.shadow.camera.coordinateSystem = frame.camera.coordinateSystem;
  29179. light.shadow.camera.updateProjectionMatrix();
  29180. }
  29181. light.shadow.updateMatrices( light );
  29182. }
  29183. return light.shadow.matrix;
  29184. } ) );
  29185. }
  29186. /**
  29187. * TSL function for getting projected uv coordinates for the given light.
  29188. * Relevant when using maps with spot lights.
  29189. *
  29190. * @tsl
  29191. * @function
  29192. * @param {Light} light -The light source.
  29193. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  29194. * @returns {Node<vec3>} The projected uvs.
  29195. */
  29196. function lightProjectionUV( light, position = positionWorld ) {
  29197. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  29198. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  29199. return projectionUV;
  29200. }
  29201. /**
  29202. * TSL function for getting the position in world space for the given light.
  29203. *
  29204. * @tsl
  29205. * @function
  29206. * @param {Light} light -The light source.
  29207. * @returns {UniformNode<vec3>} The light's position in world space.
  29208. */
  29209. function lightPosition( light ) {
  29210. const data = getLightData( light );
  29211. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  29212. }
  29213. /**
  29214. * TSL function for getting the light target position in world space for the given light.
  29215. *
  29216. * @tsl
  29217. * @function
  29218. * @param {Light} light -The light source.
  29219. * @returns {UniformNode<vec3>} The light target position in world space.
  29220. */
  29221. function lightTargetPosition( light ) {
  29222. const data = getLightData( light );
  29223. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  29224. }
  29225. /**
  29226. * TSL function for getting the position in view space for the given light.
  29227. *
  29228. * @tsl
  29229. * @function
  29230. * @param {Light} light - The light source.
  29231. * @returns {UniformNode<vec3>} The light's position in view space.
  29232. */
  29233. function lightViewPosition( light ) {
  29234. const data = getLightData( light );
  29235. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  29236. self.value = self.value || new Vector3();
  29237. self.value.setFromMatrixPosition( light.matrixWorld );
  29238. self.value.applyMatrix4( camera.matrixWorldInverse );
  29239. } ) );
  29240. }
  29241. /**
  29242. * TSL function for getting the light target direction for the given light.
  29243. *
  29244. * @tsl
  29245. * @function
  29246. * @param {Light} light -The light source.
  29247. * @returns {Node<vec3>} The light's target direction.
  29248. */
  29249. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  29250. const sortLights = ( lights ) => {
  29251. return lights.sort( ( a, b ) => a.id - b.id );
  29252. };
  29253. const getLightNodeById = ( id, lightNodes ) => {
  29254. for ( const lightNode of lightNodes ) {
  29255. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  29256. return lightNode;
  29257. }
  29258. }
  29259. return null;
  29260. };
  29261. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  29262. const _hashData = [];
  29263. /**
  29264. * This node represents the scene's lighting and manages the lighting model's life cycle
  29265. * for the current build 3D object. It is responsible for computing the total outgoing
  29266. * light in a given lighting context.
  29267. *
  29268. * @augments Node
  29269. */
  29270. class LightsNode extends Node {
  29271. static get type() {
  29272. return 'LightsNode';
  29273. }
  29274. /**
  29275. * Constructs a new lights node.
  29276. */
  29277. constructor() {
  29278. super( 'vec3' );
  29279. /**
  29280. * A node representing the total diffuse light.
  29281. *
  29282. * @type {Node<vec3>}
  29283. */
  29284. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  29285. /**
  29286. * A node representing the total specular light.
  29287. *
  29288. * @type {Node<vec3>}
  29289. */
  29290. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  29291. /**
  29292. * A node representing the outgoing light.
  29293. *
  29294. * @type {Node<vec3>}
  29295. */
  29296. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  29297. /**
  29298. * An array representing the lights in the scene.
  29299. *
  29300. * @private
  29301. * @type {Array<Light>}
  29302. */
  29303. this._lights = [];
  29304. /**
  29305. * For each light in the scene, this node will create a
  29306. * corresponding light node.
  29307. *
  29308. * @private
  29309. * @type {?Array<LightingNode>}
  29310. * @default null
  29311. */
  29312. this._lightNodes = null;
  29313. /**
  29314. * A hash for identifying the current light nodes setup.
  29315. *
  29316. * @private
  29317. * @type {?string}
  29318. * @default null
  29319. */
  29320. this._lightNodesHash = null;
  29321. /**
  29322. * `LightsNode` sets this property to `true` by default.
  29323. *
  29324. * @type {boolean}
  29325. * @default true
  29326. */
  29327. this.global = true;
  29328. }
  29329. /**
  29330. * Overwrites the default {@link Node#customCacheKey} implementation by including
  29331. * light data into the cache key.
  29332. *
  29333. * @return {number} The custom cache key.
  29334. */
  29335. customCacheKey() {
  29336. const lights = this._lights;
  29337. for ( let i = 0; i < lights.length; i ++ ) {
  29338. const light = lights[ i ];
  29339. _hashData.push( light.id );
  29340. _hashData.push( light.castShadow ? 1 : 0 );
  29341. if ( light.isSpotLight === true ) {
  29342. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  29343. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  29344. _hashData.push( hashMap, hashColorNode );
  29345. }
  29346. }
  29347. const cacheKey = hashArray( _hashData );
  29348. _hashData.length = 0;
  29349. return cacheKey;
  29350. }
  29351. /**
  29352. * Computes a hash value for identifying the current light nodes setup.
  29353. *
  29354. * @param {NodeBuilder} builder - A reference to the current node builder.
  29355. * @return {string} The computed hash.
  29356. */
  29357. getHash( builder ) {
  29358. if ( this._lightNodesHash === null ) {
  29359. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  29360. const hash = [];
  29361. for ( const lightNode of this._lightNodes ) {
  29362. hash.push( lightNode.getHash() );
  29363. }
  29364. this._lightNodesHash = 'lights-' + hash.join( ',' );
  29365. }
  29366. return this._lightNodesHash;
  29367. }
  29368. analyze( builder ) {
  29369. const properties = builder.getNodeProperties( this );
  29370. for ( const node of properties.nodes ) {
  29371. node.build( builder );
  29372. }
  29373. properties.outputNode.build( builder );
  29374. }
  29375. /**
  29376. * Creates lighting nodes for each scene light. This makes it possible to further
  29377. * process lights in the node system.
  29378. *
  29379. * @param {NodeBuilder} builder - A reference to the current node builder.
  29380. */
  29381. setupLightsNode( builder ) {
  29382. const lightNodes = [];
  29383. const previousLightNodes = this._lightNodes;
  29384. const lights = sortLights( this._lights );
  29385. const nodeLibrary = builder.renderer.library;
  29386. for ( const light of lights ) {
  29387. if ( light.isNode ) {
  29388. lightNodes.push( nodeObject( light ) );
  29389. } else {
  29390. let lightNode = null;
  29391. if ( previousLightNodes !== null ) {
  29392. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  29393. }
  29394. if ( lightNode === null ) {
  29395. // find the corresponding node type for a given light
  29396. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  29397. if ( lightNodeClass === null ) {
  29398. warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  29399. continue;
  29400. }
  29401. let lightNode = null;
  29402. if ( ! _lightsNodeRef.has( light ) ) {
  29403. lightNode = nodeObject( new lightNodeClass( light ) );
  29404. _lightsNodeRef.set( light, lightNode );
  29405. } else {
  29406. lightNode = _lightsNodeRef.get( light );
  29407. }
  29408. lightNodes.push( lightNode );
  29409. }
  29410. }
  29411. }
  29412. this._lightNodes = lightNodes;
  29413. }
  29414. /**
  29415. * Sets up a direct light in the lighting model.
  29416. *
  29417. * @param {Object} builder - The builder object containing the context and stack.
  29418. * @param {Object} lightNode - The light node.
  29419. * @param {Object} lightData - The light object containing color and direction properties.
  29420. */
  29421. setupDirectLight( builder, lightNode, lightData ) {
  29422. const { lightingModel, reflectedLight } = builder.context;
  29423. lightingModel.direct( {
  29424. ...lightData,
  29425. lightNode,
  29426. reflectedLight
  29427. }, builder );
  29428. }
  29429. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  29430. const { lightingModel, reflectedLight } = builder.context;
  29431. lightingModel.directRectArea( {
  29432. ...lightData,
  29433. lightNode,
  29434. reflectedLight
  29435. }, builder );
  29436. }
  29437. /**
  29438. * Setups the internal lights by building all respective
  29439. * light nodes.
  29440. *
  29441. * @param {NodeBuilder} builder - A reference to the current node builder.
  29442. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  29443. */
  29444. setupLights( builder, lightNodes ) {
  29445. for ( const lightNode of lightNodes ) {
  29446. lightNode.build( builder );
  29447. }
  29448. }
  29449. getLightNodes( builder ) {
  29450. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  29451. return this._lightNodes;
  29452. }
  29453. /**
  29454. * The implementation makes sure that for each light in the scene
  29455. * there is a corresponding light node. By building the light nodes
  29456. * and evaluating the lighting model the outgoing light is computed.
  29457. *
  29458. * @param {NodeBuilder} builder - A reference to the current node builder.
  29459. * @return {Node<vec3>} A node representing the outgoing light.
  29460. */
  29461. setup( builder ) {
  29462. const currentLightsNode = builder.lightsNode;
  29463. builder.lightsNode = this;
  29464. //
  29465. let outgoingLightNode = this.outgoingLightNode;
  29466. const context = builder.context;
  29467. const lightingModel = context.lightingModel;
  29468. const properties = builder.getNodeProperties( this );
  29469. if ( lightingModel ) {
  29470. const { totalDiffuseNode, totalSpecularNode } = this;
  29471. context.outgoingLight = outgoingLightNode;
  29472. const stack = builder.addStack();
  29473. //
  29474. properties.nodes = stack.nodes;
  29475. //
  29476. lightingModel.start( builder );
  29477. //
  29478. const { backdrop, backdropAlpha } = context;
  29479. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  29480. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  29481. if ( backdrop !== null ) {
  29482. if ( backdropAlpha !== null ) {
  29483. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  29484. } else {
  29485. totalDiffuse = vec3( backdrop );
  29486. }
  29487. }
  29488. totalDiffuseNode.assign( totalDiffuse );
  29489. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  29490. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  29491. //
  29492. lightingModel.finish( builder );
  29493. //
  29494. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  29495. } else {
  29496. properties.nodes = [];
  29497. }
  29498. //
  29499. builder.lightsNode = currentLightsNode;
  29500. return outgoingLightNode;
  29501. }
  29502. /**
  29503. * Configures this node with an array of lights.
  29504. *
  29505. * @param {Array<Light>} lights - An array of lights.
  29506. * @return {LightsNode} A reference to this node.
  29507. */
  29508. setLights( lights ) {
  29509. this._lights = lights;
  29510. this._lightNodes = null;
  29511. this._lightNodesHash = null;
  29512. return this;
  29513. }
  29514. /**
  29515. * Returns an array of the scene's lights.
  29516. *
  29517. * @return {Array<Light>} The scene's lights.
  29518. */
  29519. getLights() {
  29520. return this._lights;
  29521. }
  29522. /**
  29523. * Whether the scene has lights or not.
  29524. *
  29525. * @type {boolean}
  29526. */
  29527. get hasLights() {
  29528. return this._lights.length > 0;
  29529. }
  29530. }
  29531. /**
  29532. * TSL function for creating an instance of `LightsNode` and configuring
  29533. * it with the given array of lights.
  29534. *
  29535. * @tsl
  29536. * @function
  29537. * @param {Array<Light>} lights - An array of lights.
  29538. * @return {LightsNode} The created lights node.
  29539. */
  29540. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  29541. /**
  29542. * Base class for all shadow nodes.
  29543. *
  29544. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  29545. * Lighting nodes might share the same shadow node type or use specific ones depending on
  29546. * their requirements.
  29547. *
  29548. * @augments Node
  29549. */
  29550. class ShadowBaseNode extends Node {
  29551. static get type() {
  29552. return 'ShadowBaseNode';
  29553. }
  29554. /**
  29555. * Constructs a new shadow base node.
  29556. *
  29557. * @param {Light} light - The shadow casting light.
  29558. */
  29559. constructor( light ) {
  29560. super();
  29561. /**
  29562. * The shadow casting light.
  29563. *
  29564. * @type {Light}
  29565. */
  29566. this.light = light;
  29567. /**
  29568. * Overwritten since shadows are updated by default per render.
  29569. *
  29570. * @type {string}
  29571. * @default 'render'
  29572. */
  29573. this.updateBeforeType = NodeUpdateType.RENDER;
  29574. /**
  29575. * This flag can be used for type testing.
  29576. *
  29577. * @type {boolean}
  29578. * @readonly
  29579. * @default true
  29580. */
  29581. this.isShadowBaseNode = true;
  29582. }
  29583. /**
  29584. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  29585. *
  29586. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  29587. */
  29588. setupShadowPosition( { context, material } ) {
  29589. // Use assign inside an Fn()
  29590. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  29591. }
  29592. }
  29593. /**
  29594. * TSL object that represents the vertex position in world space during the shadow pass.
  29595. *
  29596. * @tsl
  29597. * @type {Node<vec3>}
  29598. */
  29599. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  29600. /**
  29601. * Saves the state of the given renderer and stores it into the given state object.
  29602. *
  29603. * If not state object is provided, the function creates one.
  29604. *
  29605. * @private
  29606. * @function
  29607. * @param {Renderer} renderer - The renderer.
  29608. * @param {Object} [state={}] - The state.
  29609. * @return {Object} The state.
  29610. */
  29611. function saveRendererState( renderer, state = {} ) {
  29612. state.toneMapping = renderer.toneMapping;
  29613. state.toneMappingExposure = renderer.toneMappingExposure;
  29614. state.outputColorSpace = renderer.outputColorSpace;
  29615. state.renderTarget = renderer.getRenderTarget();
  29616. state.activeCubeFace = renderer.getActiveCubeFace();
  29617. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  29618. state.renderObjectFunction = renderer.getRenderObjectFunction();
  29619. state.pixelRatio = renderer.getPixelRatio();
  29620. state.mrt = renderer.getMRT();
  29621. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  29622. state.clearAlpha = renderer.getClearAlpha();
  29623. state.autoClear = renderer.autoClear;
  29624. state.scissorTest = renderer.getScissorTest();
  29625. return state;
  29626. }
  29627. /**
  29628. * Saves the state of the given renderer and stores it into the given state object.
  29629. * Besides, the function also resets the state of the renderer to its default values.
  29630. *
  29631. * If not state object is provided, the function creates one.
  29632. *
  29633. * @private
  29634. * @function
  29635. * @param {Renderer} renderer - The renderer.
  29636. * @param {Object} [state={}] - The state.
  29637. * @return {Object} The state.
  29638. */
  29639. function resetRendererState( renderer, state ) {
  29640. state = saveRendererState( renderer, state );
  29641. renderer.setMRT( null );
  29642. renderer.setRenderObjectFunction( null );
  29643. renderer.setClearColor( 0x000000, 1 );
  29644. renderer.autoClear = true;
  29645. return state;
  29646. }
  29647. /**
  29648. * Restores the state of the given renderer from the given state object.
  29649. *
  29650. * @private
  29651. * @function
  29652. * @param {Renderer} renderer - The renderer.
  29653. * @param {Object} state - The state to restore.
  29654. */
  29655. function restoreRendererState( renderer, state ) {
  29656. renderer.toneMapping = state.toneMapping;
  29657. renderer.toneMappingExposure = state.toneMappingExposure;
  29658. renderer.outputColorSpace = state.outputColorSpace;
  29659. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  29660. renderer.setRenderObjectFunction( state.renderObjectFunction );
  29661. renderer.setPixelRatio( state.pixelRatio );
  29662. renderer.setMRT( state.mrt );
  29663. renderer.setClearColor( state.clearColor, state.clearAlpha );
  29664. renderer.autoClear = state.autoClear;
  29665. renderer.setScissorTest( state.scissorTest );
  29666. }
  29667. /**
  29668. * Saves the state of the given scene and stores it into the given state object.
  29669. *
  29670. * If not state object is provided, the function creates one.
  29671. *
  29672. * @private
  29673. * @function
  29674. * @param {Scene} scene - The scene.
  29675. * @param {Object} [state={}] - The state.
  29676. * @return {Object} The state.
  29677. */
  29678. function saveSceneState( scene, state = {} ) {
  29679. state.background = scene.background;
  29680. state.backgroundNode = scene.backgroundNode;
  29681. state.overrideMaterial = scene.overrideMaterial;
  29682. return state;
  29683. }
  29684. /**
  29685. * Saves the state of the given scene and stores it into the given state object.
  29686. * Besides, the function also resets the state of the scene to its default values.
  29687. *
  29688. * If not state object is provided, the function creates one.
  29689. *
  29690. * @private
  29691. * @function
  29692. * @param {Scene} scene - The scene.
  29693. * @param {Object} [state={}] - The state.
  29694. * @return {Object} The state.
  29695. */
  29696. function resetSceneState( scene, state ) {
  29697. state = saveSceneState( scene, state );
  29698. scene.background = null;
  29699. scene.backgroundNode = null;
  29700. scene.overrideMaterial = null;
  29701. return state;
  29702. }
  29703. /**
  29704. * Restores the state of the given scene from the given state object.
  29705. *
  29706. * @private
  29707. * @function
  29708. * @param {Scene} scene - The scene.
  29709. * @param {Object} state - The state to restore.
  29710. */
  29711. function restoreSceneState( scene, state ) {
  29712. scene.background = state.background;
  29713. scene.backgroundNode = state.backgroundNode;
  29714. scene.overrideMaterial = state.overrideMaterial;
  29715. }
  29716. /**
  29717. * Saves the state of the given renderer and scene and stores it into the given state object.
  29718. *
  29719. * If not state object is provided, the function creates one.
  29720. *
  29721. * @private
  29722. * @function
  29723. * @param {Renderer} renderer - The renderer.
  29724. * @param {Scene} scene - The scene.
  29725. * @param {Object} [state={}] - The state.
  29726. * @return {Object} The state.
  29727. */
  29728. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  29729. state = saveRendererState( renderer, state );
  29730. state = saveSceneState( scene, state );
  29731. return state;
  29732. }
  29733. /**
  29734. * Saves the state of the given renderer and scene and stores it into the given state object.
  29735. * Besides, the function also resets the state of the renderer and scene to its default values.
  29736. *
  29737. * If not state object is provided, the function creates one.
  29738. *
  29739. * @private
  29740. * @function
  29741. * @param {Renderer} renderer - The renderer.
  29742. * @param {Scene} scene - The scene.
  29743. * @param {Object} [state={}] - The state.
  29744. * @return {Object} The state.
  29745. */
  29746. function resetRendererAndSceneState( renderer, scene, state ) {
  29747. state = resetRendererState( renderer, state );
  29748. state = resetSceneState( scene, state );
  29749. return state;
  29750. }
  29751. /**
  29752. * Restores the state of the given renderer and scene from the given state object.
  29753. *
  29754. * @private
  29755. * @function
  29756. * @param {Renderer} renderer - The renderer.
  29757. * @param {Scene} scene - The scene.
  29758. * @param {Object} state - The state to restore.
  29759. */
  29760. function restoreRendererAndSceneState( renderer, scene, state ) {
  29761. restoreRendererState( renderer, state );
  29762. restoreSceneState( scene, state );
  29763. }
  29764. var RendererUtils = /*#__PURE__*/Object.freeze({
  29765. __proto__: null,
  29766. resetRendererAndSceneState: resetRendererAndSceneState,
  29767. resetRendererState: resetRendererState,
  29768. resetSceneState: resetSceneState,
  29769. restoreRendererAndSceneState: restoreRendererAndSceneState,
  29770. restoreRendererState: restoreRendererState,
  29771. restoreSceneState: restoreSceneState,
  29772. saveRendererAndSceneState: saveRendererAndSceneState,
  29773. saveRendererState: saveRendererState,
  29774. saveSceneState: saveSceneState
  29775. });
  29776. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  29777. /**
  29778. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  29779. * with a binary `[0,1]` result.
  29780. *
  29781. * @method
  29782. * @param {Object} inputs - The input parameter object.
  29783. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29784. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29785. * @return {Node<float>} The filtering result.
  29786. */
  29787. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  29788. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  29789. if ( depthTexture.isArrayTexture ) {
  29790. basic = basic.depth( depthLayer );
  29791. }
  29792. return basic.compare( shadowCoord.z );
  29793. } );
  29794. /**
  29795. * A shadow filtering function performing PCF filtering.
  29796. *
  29797. * @method
  29798. * @param {Object} inputs - The input parameter object.
  29799. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29800. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29801. * @param {LightShadow} inputs.shadow - The light shadow.
  29802. * @return {Node<float>} The filtering result.
  29803. */
  29804. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  29805. const depthCompare = ( uv, compare ) => {
  29806. let depth = texture( depthTexture, uv );
  29807. if ( depthTexture.isArrayTexture ) {
  29808. depth = depth.depth( depthLayer );
  29809. }
  29810. return depth.compare( compare );
  29811. };
  29812. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  29813. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  29814. const texelSize = vec2( 1 ).div( mapSize );
  29815. const dx0 = texelSize.x.negate().mul( radius );
  29816. const dy0 = texelSize.y.negate().mul( radius );
  29817. const dx1 = texelSize.x.mul( radius );
  29818. const dy1 = texelSize.y.mul( radius );
  29819. const dx2 = dx0.div( 2 );
  29820. const dy2 = dy0.div( 2 );
  29821. const dx3 = dx1.div( 2 );
  29822. const dy3 = dy1.div( 2 );
  29823. return add(
  29824. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  29825. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  29826. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  29827. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  29828. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  29829. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  29830. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  29831. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  29832. depthCompare( shadowCoord.xy, shadowCoord.z ),
  29833. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  29834. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  29835. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  29836. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  29837. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  29838. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  29839. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  29840. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  29841. ).mul( 1 / 17 );
  29842. } );
  29843. /**
  29844. * A shadow filtering function performing PCF soft filtering.
  29845. *
  29846. * @method
  29847. * @param {Object} inputs - The input parameter object.
  29848. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29849. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29850. * @param {LightShadow} inputs.shadow - The light shadow.
  29851. * @return {Node<float>} The filtering result.
  29852. */
  29853. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  29854. const depthCompare = ( uv, compare ) => {
  29855. let depth = texture( depthTexture, uv );
  29856. if ( depthTexture.isArrayTexture ) {
  29857. depth = depth.depth( depthLayer );
  29858. }
  29859. return depth.compare( compare );
  29860. };
  29861. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  29862. const texelSize = vec2( 1 ).div( mapSize );
  29863. const dx = texelSize.x;
  29864. const dy = texelSize.y;
  29865. const uv = shadowCoord.xy;
  29866. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  29867. uv.subAssign( f.mul( texelSize ) );
  29868. return add(
  29869. depthCompare( uv, shadowCoord.z ),
  29870. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  29871. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  29872. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  29873. mix(
  29874. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  29875. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  29876. f.x
  29877. ),
  29878. mix(
  29879. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  29880. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  29881. f.x
  29882. ),
  29883. mix(
  29884. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  29885. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  29886. f.y
  29887. ),
  29888. mix(
  29889. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  29890. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  29891. f.y
  29892. ),
  29893. mix(
  29894. mix(
  29895. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  29896. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  29897. f.x
  29898. ),
  29899. mix(
  29900. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  29901. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  29902. f.x
  29903. ),
  29904. f.y
  29905. )
  29906. ).mul( 1 / 9 );
  29907. } );
  29908. /**
  29909. * A shadow filtering function performing VSM filtering.
  29910. *
  29911. * @method
  29912. * @param {Object} inputs - The input parameter object.
  29913. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29914. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29915. * @return {Node<float>} The filtering result.
  29916. */
  29917. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  29918. const occlusion = float( 1 ).toVar();
  29919. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  29920. if ( depthTexture.isArrayTexture ) {
  29921. distribution = distribution.depth( depthLayer );
  29922. }
  29923. distribution = distribution.rg;
  29924. const hardShadow = step( shadowCoord.z, distribution.x );
  29925. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  29926. const distance = shadowCoord.z.sub( distribution.x );
  29927. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  29928. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  29929. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  29930. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  29931. } );
  29932. return occlusion;
  29933. } );
  29934. //
  29935. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  29936. let dist = positionWorld.sub( position ).length();
  29937. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  29938. dist = dist.saturate(); // clamp to [ 0, 1 ]
  29939. return dist;
  29940. } );
  29941. const linearShadowDistance = ( light ) => {
  29942. const camera = light.shadow.camera;
  29943. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  29944. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  29945. const referencePosition = objectPosition( light );
  29946. return linearDistance( referencePosition, nearDistance, farDistance );
  29947. };
  29948. /**
  29949. * Retrieves or creates a shadow material for the given light source.
  29950. *
  29951. * This function checks if a shadow material already exists for the provided light.
  29952. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  29953. * in the `shadowMaterialLib` for future use.
  29954. *
  29955. * @tsl
  29956. * @function
  29957. * @param {Light} light - The light source for which the shadow material is needed.
  29958. * If the light is a point light, a depth node is calculated
  29959. * using the linear shadow distance.
  29960. * @returns {NodeMaterial} The shadow material associated with the given light.
  29961. */
  29962. const getShadowMaterial = ( light ) => {
  29963. let material = shadowMaterialLib.get( light );
  29964. if ( material === undefined ) {
  29965. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  29966. material = new NodeMaterial();
  29967. material.colorNode = vec4( 0, 0, 0, 1 );
  29968. material.depthNode = depthNode;
  29969. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  29970. material.name = 'ShadowMaterial';
  29971. material.fog = false;
  29972. shadowMaterialLib.set( light, material );
  29973. }
  29974. return material;
  29975. };
  29976. //
  29977. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  29978. const _shadowRenderObjectKeys = [];
  29979. /**
  29980. * Creates a function to render shadow objects in a scene.
  29981. *
  29982. * @tsl
  29983. * @function
  29984. * @param {Renderer} renderer - The renderer.
  29985. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  29986. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  29987. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  29988. * @return {Function} A function that renders shadow objects.
  29989. *
  29990. * The returned function has the following parameters:
  29991. * @param {Object3D} object - The 3D object to render.
  29992. * @param {Scene} scene - The scene containing the object.
  29993. * @param {Camera} _camera - The camera used for rendering.
  29994. * @param {BufferGeometry} geometry - The geometry of the object.
  29995. * @param {Material} material - The material of the object.
  29996. * @param {Group} group - The group the object belongs to.
  29997. * @param {...any} params - Additional parameters for rendering.
  29998. */
  29999. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  30000. _shadowRenderObjectKeys[ 0 ] = renderer;
  30001. _shadowRenderObjectKeys[ 1 ] = shadow;
  30002. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  30003. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  30004. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  30005. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  30006. if ( useVelocity ) {
  30007. getDataFromObject( object ).useVelocity = true;
  30008. }
  30009. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  30010. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  30011. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  30012. }
  30013. };
  30014. renderObjectFunction.shadowType = shadowType;
  30015. renderObjectFunction.useVelocity = useVelocity;
  30016. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  30017. }
  30018. _shadowRenderObjectKeys[ 0 ] = null;
  30019. _shadowRenderObjectKeys[ 1 ] = null;
  30020. return renderObjectFunction;
  30021. };
  30022. /**
  30023. * Represents the shader code for the first VSM render pass.
  30024. *
  30025. * @method
  30026. * @param {Object} inputs - The input parameter object.
  30027. * @param {Node<float>} inputs.samples - The number of samples
  30028. * @param {Node<float>} inputs.radius - The radius.
  30029. * @param {Node<float>} inputs.size - The size.
  30030. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  30031. * @return {Node<vec2>} The VSM output.
  30032. */
  30033. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  30034. const mean = float( 0 ).toVar( 'meanVertical' );
  30035. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  30036. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  30037. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  30038. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  30039. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  30040. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  30041. if ( shadowPass.value.isArrayTexture ) {
  30042. depth = depth.depth( depthLayer );
  30043. }
  30044. depth = depth.x;
  30045. mean.addAssign( depth );
  30046. squaredMean.addAssign( depth.mul( depth ) );
  30047. } );
  30048. mean.divAssign( samples );
  30049. squaredMean.divAssign( samples );
  30050. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  30051. return vec2( mean, std_dev );
  30052. } );
  30053. /**
  30054. * Represents the shader code for the second VSM render pass.
  30055. *
  30056. * @method
  30057. * @param {Object} inputs - The input parameter object.
  30058. * @param {Node<float>} inputs.samples - The number of samples
  30059. * @param {Node<float>} inputs.radius - The radius.
  30060. * @param {Node<float>} inputs.size - The size.
  30061. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  30062. * @return {Node<vec2>} The VSM output.
  30063. */
  30064. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  30065. const mean = float( 0 ).toVar( 'meanHorizontal' );
  30066. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  30067. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  30068. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  30069. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  30070. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  30071. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  30072. if ( shadowPass.value.isArrayTexture ) {
  30073. distribution = distribution.depth( depthLayer );
  30074. }
  30075. mean.addAssign( distribution.x );
  30076. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  30077. } );
  30078. mean.divAssign( samples );
  30079. squaredMean.divAssign( samples );
  30080. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  30081. return vec2( mean, std_dev );
  30082. } );
  30083. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  30084. //
  30085. let _rendererState;
  30086. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  30087. /**
  30088. * Represents the default shadow implementation for lighting nodes.
  30089. *
  30090. * @augments ShadowBaseNode
  30091. */
  30092. class ShadowNode extends ShadowBaseNode {
  30093. static get type() {
  30094. return 'ShadowNode';
  30095. }
  30096. /**
  30097. * Constructs a new shadow node.
  30098. *
  30099. * @param {Light} light - The shadow casting light.
  30100. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  30101. */
  30102. constructor( light, shadow = null ) {
  30103. super( light );
  30104. /**
  30105. * The light shadow which defines the properties light's
  30106. * shadow.
  30107. *
  30108. * @type {?LightShadow}
  30109. * @default null
  30110. */
  30111. this.shadow = shadow || light.shadow;
  30112. /**
  30113. * A reference to the shadow map which is a render target.
  30114. *
  30115. * @type {?RenderTarget}
  30116. * @default null
  30117. */
  30118. this.shadowMap = null;
  30119. /**
  30120. * Only relevant for VSM shadows. Render target for the
  30121. * first VSM render pass.
  30122. *
  30123. * @type {?RenderTarget}
  30124. * @default null
  30125. */
  30126. this.vsmShadowMapVertical = null;
  30127. /**
  30128. * Only relevant for VSM shadows. Render target for the
  30129. * second VSM render pass.
  30130. *
  30131. * @type {?RenderTarget}
  30132. * @default null
  30133. */
  30134. this.vsmShadowMapHorizontal = null;
  30135. /**
  30136. * Only relevant for VSM shadows. Node material which
  30137. * is used to render the first VSM pass.
  30138. *
  30139. * @type {?NodeMaterial}
  30140. * @default null
  30141. */
  30142. this.vsmMaterialVertical = null;
  30143. /**
  30144. * Only relevant for VSM shadows. Node material which
  30145. * is used to render the second VSM pass.
  30146. *
  30147. * @type {?NodeMaterial}
  30148. * @default null
  30149. */
  30150. this.vsmMaterialHorizontal = null;
  30151. /**
  30152. * A reference to the output node which defines the
  30153. * final result of this shadow node.
  30154. *
  30155. * @type {?Node}
  30156. * @private
  30157. * @default null
  30158. */
  30159. this._node = null;
  30160. /**
  30161. * The current shadow map type of this shadow node.
  30162. *
  30163. * @type {?number}
  30164. * @private
  30165. * @default null
  30166. */
  30167. this._currentShadowType = null;
  30168. /**
  30169. * A Weak Map holding the current frame ID per camera. Used
  30170. * to control the update of shadow maps.
  30171. *
  30172. * @type {WeakMap<Camera,number>}
  30173. * @private
  30174. */
  30175. this._cameraFrameId = new WeakMap();
  30176. /**
  30177. * This flag can be used for type testing.
  30178. *
  30179. * @type {boolean}
  30180. * @readonly
  30181. * @default true
  30182. */
  30183. this.isShadowNode = true;
  30184. /**
  30185. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  30186. *
  30187. * @type {number}
  30188. * @readonly
  30189. * @default true
  30190. */
  30191. this.depthLayer = 0;
  30192. }
  30193. /**
  30194. * Setups the shadow filtering.
  30195. *
  30196. * @param {NodeBuilder} builder - A reference to the current node builder.
  30197. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  30198. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  30199. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30200. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  30201. * @param {LightShadow} inputs.shadow - The light shadow.
  30202. * @return {Node<float>} The result node of the shadow filtering.
  30203. */
  30204. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  30205. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  30206. .and( shadowCoord.x.lessThanEqual( 1 ) )
  30207. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  30208. .and( shadowCoord.y.lessThanEqual( 1 ) )
  30209. .and( shadowCoord.z.lessThanEqual( 1 ) );
  30210. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  30211. return frustumTest.select( shadowNode, float( 1 ) );
  30212. }
  30213. /**
  30214. * Setups the shadow coordinates.
  30215. *
  30216. * @param {NodeBuilder} builder - A reference to the current node builder.
  30217. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  30218. * @return {Node<vec3>} The shadow coordinates.
  30219. */
  30220. setupShadowCoord( builder, shadowPosition ) {
  30221. const { shadow } = this;
  30222. const { renderer } = builder;
  30223. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  30224. let shadowCoord = shadowPosition;
  30225. let coordZ;
  30226. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  30227. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  30228. coordZ = shadowCoord.z;
  30229. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  30230. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  30231. }
  30232. } else {
  30233. const w = shadowCoord.w;
  30234. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  30235. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  30236. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  30237. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  30238. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  30239. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  30240. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  30241. }
  30242. shadowCoord = vec3(
  30243. shadowCoord.x,
  30244. shadowCoord.y.oneMinus(), // follow webgpu standards
  30245. coordZ.add( bias )
  30246. );
  30247. return shadowCoord;
  30248. }
  30249. /**
  30250. * Returns the shadow filtering function for the given shadow type.
  30251. *
  30252. * @param {number} type - The shadow type.
  30253. * @return {Function} The filtering function.
  30254. */
  30255. getShadowFilterFn( type ) {
  30256. return _shadowFilterLib[ type ];
  30257. }
  30258. setupRenderTarget( shadow, builder ) {
  30259. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  30260. depthTexture.name = 'ShadowDepthTexture';
  30261. depthTexture.compareFunction = LessCompare;
  30262. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  30263. shadowMap.texture.name = 'ShadowMap';
  30264. shadowMap.texture.type = shadow.mapType;
  30265. shadowMap.depthTexture = depthTexture;
  30266. return { shadowMap, depthTexture };
  30267. }
  30268. /**
  30269. * Setups the shadow output node.
  30270. *
  30271. * @param {NodeBuilder} builder - A reference to the current node builder.
  30272. * @return {Node<vec3>} The shadow output node.
  30273. */
  30274. setupShadow( builder ) {
  30275. const { renderer, camera } = builder;
  30276. const { light, shadow } = this;
  30277. const shadowMapType = renderer.shadowMap.type;
  30278. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  30279. shadow.camera.coordinateSystem = camera.coordinateSystem;
  30280. shadow.camera.updateProjectionMatrix();
  30281. // VSM
  30282. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  30283. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  30284. if ( shadowMap.depth > 1 ) {
  30285. if ( ! shadowMap._vsmShadowMapVertical ) {
  30286. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  30287. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  30288. }
  30289. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  30290. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  30291. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  30292. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  30293. }
  30294. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  30295. } else {
  30296. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  30297. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  30298. }
  30299. let shadowPassVertical = texture( depthTexture );
  30300. if ( depthTexture.isArrayTexture ) {
  30301. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  30302. }
  30303. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  30304. if ( depthTexture.isArrayTexture ) {
  30305. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  30306. }
  30307. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  30308. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  30309. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  30310. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  30311. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  30312. material.name = 'VSMVertical';
  30313. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  30314. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  30315. material.name = 'VSMHorizontal';
  30316. }
  30317. //
  30318. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  30319. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  30320. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( normalWorld.mul( normalBias ) ) );
  30321. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  30322. //
  30323. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  30324. if ( filterFn === null ) {
  30325. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  30326. }
  30327. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  30328. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  30329. let shadowColor = texture( shadowMap.texture, shadowCoord );
  30330. if ( depthTexture.isArrayTexture ) {
  30331. shadowColor = shadowColor.depth( this.depthLayer );
  30332. }
  30333. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  30334. this.shadowMap = shadowMap;
  30335. this.shadow.map = shadowMap;
  30336. // Shadow Output + Inspector
  30337. const inspectName = `${ this.light.type } Shadow [ ${ this.light.name || 'ID: ' + this.light.id } ]`;
  30338. return shadowOutput.toInspector( `${ inspectName } / Color`, () => {
  30339. return texture( this.shadowMap.texture );
  30340. } ).toInspector( `${ inspectName } / Depth`, () => {
  30341. return textureLoad( this.shadowMap.depthTexture, uv$1().mul( textureSize( texture( this.shadowMap.depthTexture ) ) ) ).x.oneMinus();
  30342. } );
  30343. }
  30344. /**
  30345. * The implementation performs the setup of the output node. An output is only
  30346. * produces if shadow mapping is globally enabled in the renderer.
  30347. *
  30348. * @param {NodeBuilder} builder - A reference to the current node builder.
  30349. * @return {ShaderCallNodeInternal} The output node.
  30350. */
  30351. setup( builder ) {
  30352. if ( builder.renderer.shadowMap.enabled === false ) return;
  30353. return Fn( () => {
  30354. const currentShadowType = builder.renderer.shadowMap.type;
  30355. if ( this._currentShadowType !== currentShadowType ) {
  30356. this._reset();
  30357. this._node = null;
  30358. }
  30359. let node = this._node;
  30360. this.setupShadowPosition( builder );
  30361. if ( node === null ) {
  30362. this._node = node = this.setupShadow( builder );
  30363. this._currentShadowType = currentShadowType;
  30364. }
  30365. if ( builder.material.shadowNode ) { // @deprecated, r171
  30366. warn( 'NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  30367. }
  30368. if ( builder.material.receivedShadowNode ) {
  30369. node = builder.material.receivedShadowNode( node );
  30370. }
  30371. return node;
  30372. } )();
  30373. }
  30374. /**
  30375. * Renders the shadow. The logic of this function could be included
  30376. * into {@link ShadowNode#updateShadow} however more specialized shadow
  30377. * nodes might require a custom shadow map rendering. By having a
  30378. * dedicated method, it's easier to overwrite the default behavior.
  30379. *
  30380. * @param {NodeFrame} frame - A reference to the current node frame.
  30381. */
  30382. renderShadow( frame ) {
  30383. const { shadow, shadowMap, light } = this;
  30384. const { renderer, scene } = frame;
  30385. shadow.updateMatrices( light );
  30386. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  30387. const currentSceneName = scene.name;
  30388. scene.name = `Shadow Map [ ${ light.name || 'ID: ' + light.id } ]`;
  30389. renderer.render( scene, shadow.camera );
  30390. scene.name = currentSceneName;
  30391. }
  30392. /**
  30393. * Updates the shadow.
  30394. *
  30395. * @param {NodeFrame} frame - A reference to the current node frame.
  30396. */
  30397. updateShadow( frame ) {
  30398. const { shadowMap, light, shadow } = this;
  30399. const { renderer, scene, camera } = frame;
  30400. const shadowType = renderer.shadowMap.type;
  30401. const depthVersion = shadowMap.depthTexture.version;
  30402. this._depthVersionCached = depthVersion;
  30403. const _shadowCameraLayer = shadow.camera.layers.mask;
  30404. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  30405. shadow.camera.layers.mask = camera.layers.mask;
  30406. }
  30407. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  30408. const currentMRT = renderer.getMRT();
  30409. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  30410. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  30411. scene.overrideMaterial = getShadowMaterial( light );
  30412. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  30413. renderer.setClearColor( 0x000000, 0 );
  30414. renderer.setRenderTarget( shadowMap );
  30415. this.renderShadow( frame );
  30416. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  30417. // vsm blur pass
  30418. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  30419. this.vsmPass( renderer );
  30420. }
  30421. shadow.camera.layers.mask = _shadowCameraLayer;
  30422. restoreRendererAndSceneState( renderer, scene, _rendererState );
  30423. }
  30424. /**
  30425. * For VSM additional render passes are required.
  30426. *
  30427. * @param {Renderer} renderer - A reference to the current renderer.
  30428. */
  30429. vsmPass( renderer ) {
  30430. const { shadow } = this;
  30431. const depth = this.shadowMap.depth;
  30432. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  30433. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  30434. renderer.setRenderTarget( this.vsmShadowMapVertical );
  30435. _quadMesh.material = this.vsmMaterialVertical;
  30436. _quadMesh.render( renderer );
  30437. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  30438. _quadMesh.material = this.vsmMaterialHorizontal;
  30439. _quadMesh.render( renderer );
  30440. }
  30441. /**
  30442. * Frees the internal resources of this shadow node.
  30443. */
  30444. dispose() {
  30445. this._reset();
  30446. super.dispose();
  30447. }
  30448. /**
  30449. * Resets the resouce state of this shadow node.
  30450. *
  30451. * @private
  30452. */
  30453. _reset() {
  30454. this._currentShadowType = null;
  30455. if ( this.shadowMap ) {
  30456. this.shadowMap.dispose();
  30457. this.shadowMap = null;
  30458. }
  30459. if ( this.vsmShadowMapVertical !== null ) {
  30460. this.vsmShadowMapVertical.dispose();
  30461. this.vsmShadowMapVertical = null;
  30462. this.vsmMaterialVertical.dispose();
  30463. this.vsmMaterialVertical = null;
  30464. }
  30465. if ( this.vsmShadowMapHorizontal !== null ) {
  30466. this.vsmShadowMapHorizontal.dispose();
  30467. this.vsmShadowMapHorizontal = null;
  30468. this.vsmMaterialHorizontal.dispose();
  30469. this.vsmMaterialHorizontal = null;
  30470. }
  30471. }
  30472. /**
  30473. * The implementation performs the update of the shadow map if necessary.
  30474. *
  30475. * @param {NodeFrame} frame - A reference to the current node frame.
  30476. */
  30477. updateBefore( frame ) {
  30478. const { shadow } = this;
  30479. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  30480. if ( needsUpdate ) {
  30481. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  30482. needsUpdate = false;
  30483. }
  30484. this._cameraFrameId[ frame.camera ] = frame.frameId;
  30485. }
  30486. if ( needsUpdate ) {
  30487. this.updateShadow( frame );
  30488. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  30489. shadow.needsUpdate = false;
  30490. }
  30491. }
  30492. }
  30493. }
  30494. /**
  30495. * TSL function for creating an instance of `ShadowNode`.
  30496. *
  30497. * @tsl
  30498. * @function
  30499. * @param {Light} light - The shadow casting light.
  30500. * @param {?LightShadow} [shadow] - The light shadow.
  30501. * @return {ShadowNode} The created shadow node.
  30502. */
  30503. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  30504. const _clearColor$1 = /*@__PURE__*/ new Color();
  30505. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  30506. // vector suitable for 2D texture mapping. This code uses the following layout for the
  30507. // 2D texture:
  30508. //
  30509. // xzXZ
  30510. // y Y
  30511. //
  30512. // Y - Positive y direction
  30513. // y - Negative y direction
  30514. // X - Positive x direction
  30515. // x - Negative x direction
  30516. // Z - Positive z direction
  30517. // z - Negative z direction
  30518. //
  30519. // Source and test bed:
  30520. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  30521. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  30522. const v = pos.toVar();
  30523. // Number of texels to avoid at the edge of each square
  30524. const absV = abs( v );
  30525. // Intersect unit cube
  30526. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  30527. absV.mulAssign( scaleToCube );
  30528. // Apply scale to avoid seams
  30529. // two texels less per square (one texel will do for NEAREST)
  30530. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  30531. // Unwrap
  30532. // space: -1 ... 1 range for each square
  30533. //
  30534. // #X## dim := ( 4 , 2 )
  30535. // # # center := ( 1 , 1 )
  30536. const planar = vec2( v.xy ).toVar();
  30537. const almostATexel = texelSizeY.mul( 1.5 );
  30538. const almostOne = almostATexel.oneMinus();
  30539. If( absV.z.greaterThanEqual( almostOne ), () => {
  30540. If( v.z.greaterThan( 0.0 ), () => {
  30541. planar.x.assign( sub( 4.0, v.x ) );
  30542. } );
  30543. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  30544. const signX = sign( v.x );
  30545. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  30546. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  30547. const signY = sign( v.y );
  30548. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  30549. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  30550. } );
  30551. // Transform to UV space
  30552. // scale := 0.5 / dim
  30553. // translate := ( center + 0.5 ) / dim
  30554. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  30555. } ).setLayout( {
  30556. name: 'cubeToUV',
  30557. type: 'vec2',
  30558. inputs: [
  30559. { name: 'pos', type: 'vec3' },
  30560. { name: 'texelSizeY', type: 'float' }
  30561. ]
  30562. } );
  30563. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  30564. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  30565. } );
  30566. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  30567. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  30568. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  30569. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  30570. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  30571. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  30572. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  30573. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  30574. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  30575. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  30576. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  30577. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  30578. .mul( 1.0 / 9.0 );
  30579. } );
  30580. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  30581. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  30582. // the vector from the light to the world-space position of the fragment.
  30583. const lightToPosition = shadowCoord.xyz.toVar();
  30584. const lightToPositionLength = lightToPosition.length();
  30585. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  30586. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  30587. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  30588. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  30589. const result = float( 1.0 ).toVar();
  30590. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  30591. // dp = normalized distance from light to fragment position
  30592. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  30593. dp.addAssign( bias );
  30594. // bd3D = base direction 3D
  30595. const bd3D = lightToPosition.normalize();
  30596. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  30597. // percentage-closer filtering
  30598. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  30599. } );
  30600. return result;
  30601. } );
  30602. const _viewport = /*@__PURE__*/ new Vector4();
  30603. const _viewportSize = /*@__PURE__*/ new Vector2();
  30604. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  30605. /**
  30606. * Represents the shadow implementation for point light nodes.
  30607. *
  30608. * @augments ShadowNode
  30609. */
  30610. class PointShadowNode extends ShadowNode {
  30611. static get type() {
  30612. return 'PointShadowNode';
  30613. }
  30614. /**
  30615. * Constructs a new point shadow node.
  30616. *
  30617. * @param {PointLight} light - The shadow casting point light.
  30618. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  30619. */
  30620. constructor( light, shadow = null ) {
  30621. super( light, shadow );
  30622. }
  30623. /**
  30624. * Overwrites the default implementation to return point light shadow specific
  30625. * filtering functions.
  30626. *
  30627. * @param {number} type - The shadow type.
  30628. * @return {Function} The filtering function.
  30629. */
  30630. getShadowFilterFn( type ) {
  30631. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  30632. }
  30633. /**
  30634. * Overwrites the default implementation so the unaltered shadow position is used.
  30635. *
  30636. * @param {NodeBuilder} builder - A reference to the current node builder.
  30637. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  30638. * @return {Node<vec3>} The shadow coordinates.
  30639. */
  30640. setupShadowCoord( builder, shadowPosition ) {
  30641. return shadowPosition;
  30642. }
  30643. /**
  30644. * Overwrites the default implementation to only use point light specific
  30645. * shadow filter functions.
  30646. *
  30647. * @param {NodeBuilder} builder - A reference to the current node builder.
  30648. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  30649. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  30650. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  30651. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30652. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  30653. * @param {LightShadow} inputs.shadow - The light shadow.
  30654. * @return {Node<float>} The result node of the shadow filtering.
  30655. */
  30656. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  30657. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  30658. }
  30659. /**
  30660. * Overwrites the default implementation with point light specific
  30661. * rendering code.
  30662. *
  30663. * @param {NodeFrame} frame - A reference to the current node frame.
  30664. */
  30665. renderShadow( frame ) {
  30666. const { shadow, shadowMap, light } = this;
  30667. const { renderer, scene } = frame;
  30668. const shadowFrameExtents = shadow.getFrameExtents();
  30669. _shadowMapSize.copy( shadow.mapSize );
  30670. _shadowMapSize.multiply( shadowFrameExtents );
  30671. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  30672. _viewportSize.copy( shadow.mapSize );
  30673. //
  30674. const previousAutoClear = renderer.autoClear;
  30675. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  30676. const previousClearAlpha = renderer.getClearAlpha();
  30677. renderer.autoClear = false;
  30678. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  30679. renderer.clear();
  30680. const viewportCount = shadow.getViewportCount();
  30681. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  30682. const viewport = shadow.getViewport( vp );
  30683. const x = _viewportSize.x * viewport.x;
  30684. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  30685. _viewport.set(
  30686. x,
  30687. y,
  30688. _viewportSize.x * viewport.z,
  30689. _viewportSize.y * viewport.w
  30690. );
  30691. shadowMap.viewport.copy( _viewport );
  30692. shadow.updateMatrices( light, vp );
  30693. const currentSceneName = scene.name;
  30694. scene.name = `Point Light Shadow [ ${ light.name || 'ID: ' + light.id } ] - Face ${ vp + 1 }`;
  30695. renderer.render( scene, shadow.camera );
  30696. scene.name = currentSceneName;
  30697. }
  30698. //
  30699. renderer.autoClear = previousAutoClear;
  30700. renderer.setClearColor( previousClearColor, previousClearAlpha );
  30701. }
  30702. }
  30703. /**
  30704. * TSL function for creating an instance of `PointShadowNode`.
  30705. *
  30706. * @tsl
  30707. * @function
  30708. * @param {PointLight} light - The shadow casting point light.
  30709. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  30710. * @return {PointShadowNode} The created point shadow node.
  30711. */
  30712. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  30713. /**
  30714. * Base class for analytic light nodes.
  30715. *
  30716. * @augments LightingNode
  30717. */
  30718. class AnalyticLightNode extends LightingNode {
  30719. static get type() {
  30720. return 'AnalyticLightNode';
  30721. }
  30722. /**
  30723. * Constructs a new analytic light node.
  30724. *
  30725. * @param {?Light} [light=null] - The light source.
  30726. */
  30727. constructor( light = null ) {
  30728. super();
  30729. /**
  30730. * The light source.
  30731. *
  30732. * @type {?Light}
  30733. * @default null
  30734. */
  30735. this.light = light;
  30736. /**
  30737. * The light's color value.
  30738. *
  30739. * @type {Color}
  30740. */
  30741. this.color = new Color();
  30742. /**
  30743. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  30744. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  30745. *
  30746. * @type {Node}
  30747. */
  30748. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  30749. /**
  30750. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  30751. * The final color node is represented by a different node when using shadows.
  30752. *
  30753. * @type {?Node}
  30754. * @default null
  30755. */
  30756. this.baseColorNode = null;
  30757. /**
  30758. * Represents the light's shadow.
  30759. *
  30760. * @type {?ShadowNode}
  30761. * @default null
  30762. */
  30763. this.shadowNode = null;
  30764. /**
  30765. * Represents the light's shadow color.
  30766. *
  30767. * @type {?Node}
  30768. * @default null
  30769. */
  30770. this.shadowColorNode = null;
  30771. /**
  30772. * This flag can be used for type testing.
  30773. *
  30774. * @type {boolean}
  30775. * @readonly
  30776. * @default true
  30777. */
  30778. this.isAnalyticLightNode = true;
  30779. /**
  30780. * Overwritten since analytic light nodes are updated
  30781. * once per frame.
  30782. *
  30783. * @type {string}
  30784. * @default 'frame'
  30785. */
  30786. this.updateType = NodeUpdateType.FRAME;
  30787. }
  30788. getHash() {
  30789. return this.light.uuid;
  30790. }
  30791. /**
  30792. * Returns a node representing a direction vector which points from the current
  30793. * position in view space to the light's position in view space.
  30794. *
  30795. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  30796. * @return {Node<vec3>} The light vector node.
  30797. */
  30798. getLightVector( builder ) {
  30799. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  30800. }
  30801. /**
  30802. * Sets up the direct lighting for the analytic light node.
  30803. *
  30804. * @abstract
  30805. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  30806. * @return {Object|undefined} The direct light data (color and direction).
  30807. */
  30808. setupDirect( /*builder*/ ) { }
  30809. /**
  30810. * Sets up the direct rect area lighting for the analytic light node.
  30811. *
  30812. * @abstract
  30813. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  30814. * @return {Object|undefined} The direct rect area light data.
  30815. */
  30816. setupDirectRectArea( /*builder*/ ) { }
  30817. /**
  30818. * Setups the shadow node for this light. The method exists so concrete light classes
  30819. * can setup different types of shadow nodes.
  30820. *
  30821. * @return {ShadowNode} The created shadow node.
  30822. */
  30823. setupShadowNode() {
  30824. return shadow( this.light );
  30825. }
  30826. /**
  30827. * Setups the shadow for this light. This method is only executed if the light
  30828. * cast shadows and the current build object receives shadows. It incorporates
  30829. * shadows into the lighting computation.
  30830. *
  30831. * @param {NodeBuilder} builder - The current node builder.
  30832. */
  30833. setupShadow( builder ) {
  30834. const { renderer } = builder;
  30835. if ( renderer.shadowMap.enabled === false ) return;
  30836. let shadowColorNode = this.shadowColorNode;
  30837. if ( shadowColorNode === null ) {
  30838. const customShadowNode = this.light.shadow.shadowNode;
  30839. let shadowNode;
  30840. if ( customShadowNode !== undefined ) {
  30841. shadowNode = nodeObject( customShadowNode );
  30842. } else {
  30843. shadowNode = this.setupShadowNode();
  30844. }
  30845. this.shadowNode = shadowNode;
  30846. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  30847. this.baseColorNode = this.colorNode;
  30848. }
  30849. //
  30850. this.colorNode = shadowColorNode;
  30851. }
  30852. /**
  30853. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  30854. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  30855. * invocate the respective interface methods.
  30856. *
  30857. * @param {NodeBuilder} builder - The current node builder.
  30858. */
  30859. setup( builder ) {
  30860. this.colorNode = this.baseColorNode || this.colorNode;
  30861. if ( this.light.castShadow ) {
  30862. if ( builder.object.receiveShadow ) {
  30863. this.setupShadow( builder );
  30864. }
  30865. } else if ( this.shadowNode !== null ) {
  30866. this.shadowNode.dispose();
  30867. this.shadowNode = null;
  30868. this.shadowColorNode = null;
  30869. }
  30870. const directLightData = this.setupDirect( builder );
  30871. const directRectAreaLightData = this.setupDirectRectArea( builder );
  30872. if ( directLightData ) {
  30873. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  30874. }
  30875. if ( directRectAreaLightData ) {
  30876. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  30877. }
  30878. }
  30879. /**
  30880. * The update method is used to update light uniforms per frame.
  30881. * Potentially overwritten in concrete light nodes to update light
  30882. * specific uniforms.
  30883. *
  30884. * @param {NodeFrame} frame - A reference to the current node frame.
  30885. */
  30886. update( /*frame*/ ) {
  30887. const { light } = this;
  30888. this.color.copy( light.color ).multiplyScalar( light.intensity );
  30889. }
  30890. }
  30891. /**
  30892. * Represents a `discard` shader operation in TSL.
  30893. *
  30894. * @method
  30895. * @param {Object} inputs - The input parameter object.
  30896. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  30897. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  30898. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  30899. * @return {Node<float>} The distance falloff.
  30900. */
  30901. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  30902. // based upon Frostbite 3 Moving to Physically-based Rendering
  30903. // page 32, equation 26: E[window1]
  30904. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  30905. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  30906. return cutoffDistance.greaterThan( 0 ).select(
  30907. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  30908. distanceFalloff
  30909. );
  30910. } ); // validated
  30911. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  30912. const lightDirection = lightVector.normalize();
  30913. const lightDistance = lightVector.length();
  30914. const attenuation = getDistanceAttenuation( {
  30915. lightDistance,
  30916. cutoffDistance,
  30917. decayExponent
  30918. } );
  30919. const lightColor = color.mul( attenuation );
  30920. return { lightDirection, lightColor };
  30921. };
  30922. /**
  30923. * Module for representing point lights as nodes.
  30924. *
  30925. * @augments AnalyticLightNode
  30926. */
  30927. class PointLightNode extends AnalyticLightNode {
  30928. static get type() {
  30929. return 'PointLightNode';
  30930. }
  30931. /**
  30932. * Constructs a new point light node.
  30933. *
  30934. * @param {?PointLight} [light=null] - The point light source.
  30935. */
  30936. constructor( light = null ) {
  30937. super( light );
  30938. /**
  30939. * Uniform node representing the cutoff distance.
  30940. *
  30941. * @type {UniformNode<float>}
  30942. */
  30943. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  30944. /**
  30945. * Uniform node representing the decay exponent.
  30946. *
  30947. * @type {UniformNode<float>}
  30948. */
  30949. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  30950. }
  30951. /**
  30952. * Overwritten to updated point light specific uniforms.
  30953. *
  30954. * @param {NodeFrame} frame - A reference to the current node frame.
  30955. */
  30956. update( frame ) {
  30957. const { light } = this;
  30958. super.update( frame );
  30959. this.cutoffDistanceNode.value = light.distance;
  30960. this.decayExponentNode.value = light.decay;
  30961. }
  30962. /**
  30963. * Overwritten to setup point light specific shadow.
  30964. *
  30965. * @return {PointShadowNode}
  30966. */
  30967. setupShadowNode() {
  30968. return pointShadow( this.light );
  30969. }
  30970. setupDirect( builder ) {
  30971. return directPointLight( {
  30972. color: this.colorNode,
  30973. lightVector: this.getLightVector( builder ),
  30974. cutoffDistance: this.cutoffDistanceNode,
  30975. decayExponent: this.decayExponentNode
  30976. } );
  30977. }
  30978. }
  30979. /**
  30980. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  30981. *
  30982. * @tsl
  30983. * @function
  30984. * @param {Node<vec2>} coord - The uv coordinates.
  30985. * @return {Node<float>} The result data.
  30986. */
  30987. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  30988. const uv = coord.mul( 2.0 );
  30989. const cx = uv.x.floor();
  30990. const cy = uv.y.floor();
  30991. const result = cx.add( cy ).mod( 2.0 );
  30992. return result.sign();
  30993. } );
  30994. /**
  30995. * Generates a circle based on the uv coordinates.
  30996. *
  30997. * @tsl
  30998. * @function
  30999. * @param {Node<vec2>} coord - The uv to generate the circle.
  31000. * @return {Node<float>} The circle shape.
  31001. */
  31002. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  31003. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  31004. let alpha;
  31005. if ( material.alphaToCoverage && renderer.currentSamples > 0 ) {
  31006. const dlen = float( len2.fwidth() ).toVar();
  31007. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  31008. } else {
  31009. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  31010. }
  31011. return alpha;
  31012. } );
  31013. // Three.js Transpiler
  31014. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  31015. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  31016. const f = float( f_immutable ).toVar();
  31017. const t = float( t_immutable ).toVar();
  31018. const b = bool( b_immutable ).toVar();
  31019. return select( b, t, f );
  31020. } ).setLayout( {
  31021. name: 'mx_select',
  31022. type: 'float',
  31023. inputs: [
  31024. { name: 'b', type: 'bool' },
  31025. { name: 't', type: 'float' },
  31026. { name: 'f', type: 'float' }
  31027. ]
  31028. } );
  31029. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  31030. const b = bool( b_immutable ).toVar();
  31031. const val = float( val_immutable ).toVar();
  31032. return select( b, val.negate(), val );
  31033. } ).setLayout( {
  31034. name: 'mx_negate_if',
  31035. type: 'float',
  31036. inputs: [
  31037. { name: 'val', type: 'float' },
  31038. { name: 'b', type: 'bool' }
  31039. ]
  31040. } );
  31041. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  31042. const x = float( x_immutable ).toVar();
  31043. return int( floor( x ) );
  31044. } ).setLayout( {
  31045. name: 'mx_floor',
  31046. type: 'int',
  31047. inputs: [
  31048. { name: 'x', type: 'float' }
  31049. ]
  31050. } );
  31051. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  31052. const x = float( x_immutable ).toVar();
  31053. i.assign( mx_floor( x ) );
  31054. return x.sub( float( i ) );
  31055. } );
  31056. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  31057. const t = float( t_immutable ).toVar();
  31058. const s = float( s_immutable ).toVar();
  31059. const v3 = float( v3_immutable ).toVar();
  31060. const v2 = float( v2_immutable ).toVar();
  31061. const v1 = float( v1_immutable ).toVar();
  31062. const v0 = float( v0_immutable ).toVar();
  31063. const s1 = float( sub( 1.0, s ) ).toVar();
  31064. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  31065. } ).setLayout( {
  31066. name: 'mx_bilerp_0',
  31067. type: 'float',
  31068. inputs: [
  31069. { name: 'v0', type: 'float' },
  31070. { name: 'v1', type: 'float' },
  31071. { name: 'v2', type: 'float' },
  31072. { name: 'v3', type: 'float' },
  31073. { name: 's', type: 'float' },
  31074. { name: 't', type: 'float' }
  31075. ]
  31076. } );
  31077. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  31078. const t = float( t_immutable ).toVar();
  31079. const s = float( s_immutable ).toVar();
  31080. const v3 = vec3( v3_immutable ).toVar();
  31081. const v2 = vec3( v2_immutable ).toVar();
  31082. const v1 = vec3( v1_immutable ).toVar();
  31083. const v0 = vec3( v0_immutable ).toVar();
  31084. const s1 = float( sub( 1.0, s ) ).toVar();
  31085. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  31086. } ).setLayout( {
  31087. name: 'mx_bilerp_1',
  31088. type: 'vec3',
  31089. inputs: [
  31090. { name: 'v0', type: 'vec3' },
  31091. { name: 'v1', type: 'vec3' },
  31092. { name: 'v2', type: 'vec3' },
  31093. { name: 'v3', type: 'vec3' },
  31094. { name: 's', type: 'float' },
  31095. { name: 't', type: 'float' }
  31096. ]
  31097. } );
  31098. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  31099. 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 ] ) => {
  31100. const r = float( r_immutable ).toVar();
  31101. const t = float( t_immutable ).toVar();
  31102. const s = float( s_immutable ).toVar();
  31103. const v7 = float( v7_immutable ).toVar();
  31104. const v6 = float( v6_immutable ).toVar();
  31105. const v5 = float( v5_immutable ).toVar();
  31106. const v4 = float( v4_immutable ).toVar();
  31107. const v3 = float( v3_immutable ).toVar();
  31108. const v2 = float( v2_immutable ).toVar();
  31109. const v1 = float( v1_immutable ).toVar();
  31110. const v0 = float( v0_immutable ).toVar();
  31111. const s1 = float( sub( 1.0, s ) ).toVar();
  31112. const t1 = float( sub( 1.0, t ) ).toVar();
  31113. const r1 = float( sub( 1.0, r ) ).toVar();
  31114. 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 ) ) ) ) ) );
  31115. } ).setLayout( {
  31116. name: 'mx_trilerp_0',
  31117. type: 'float',
  31118. inputs: [
  31119. { name: 'v0', type: 'float' },
  31120. { name: 'v1', type: 'float' },
  31121. { name: 'v2', type: 'float' },
  31122. { name: 'v3', type: 'float' },
  31123. { name: 'v4', type: 'float' },
  31124. { name: 'v5', type: 'float' },
  31125. { name: 'v6', type: 'float' },
  31126. { name: 'v7', type: 'float' },
  31127. { name: 's', type: 'float' },
  31128. { name: 't', type: 'float' },
  31129. { name: 'r', type: 'float' }
  31130. ]
  31131. } );
  31132. 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 ] ) => {
  31133. const r = float( r_immutable ).toVar();
  31134. const t = float( t_immutable ).toVar();
  31135. const s = float( s_immutable ).toVar();
  31136. const v7 = vec3( v7_immutable ).toVar();
  31137. const v6 = vec3( v6_immutable ).toVar();
  31138. const v5 = vec3( v5_immutable ).toVar();
  31139. const v4 = vec3( v4_immutable ).toVar();
  31140. const v3 = vec3( v3_immutable ).toVar();
  31141. const v2 = vec3( v2_immutable ).toVar();
  31142. const v1 = vec3( v1_immutable ).toVar();
  31143. const v0 = vec3( v0_immutable ).toVar();
  31144. const s1 = float( sub( 1.0, s ) ).toVar();
  31145. const t1 = float( sub( 1.0, t ) ).toVar();
  31146. const r1 = float( sub( 1.0, r ) ).toVar();
  31147. 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 ) ) ) ) ) );
  31148. } ).setLayout( {
  31149. name: 'mx_trilerp_1',
  31150. type: 'vec3',
  31151. inputs: [
  31152. { name: 'v0', type: 'vec3' },
  31153. { name: 'v1', type: 'vec3' },
  31154. { name: 'v2', type: 'vec3' },
  31155. { name: 'v3', type: 'vec3' },
  31156. { name: 'v4', type: 'vec3' },
  31157. { name: 'v5', type: 'vec3' },
  31158. { name: 'v6', type: 'vec3' },
  31159. { name: 'v7', type: 'vec3' },
  31160. { name: 's', type: 'float' },
  31161. { name: 't', type: 'float' },
  31162. { name: 'r', type: 'float' }
  31163. ]
  31164. } );
  31165. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  31166. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  31167. const y = float( y_immutable ).toVar();
  31168. const x = float( x_immutable ).toVar();
  31169. const hash = uint( hash_immutable ).toVar();
  31170. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  31171. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  31172. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  31173. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  31174. } ).setLayout( {
  31175. name: 'mx_gradient_float_0',
  31176. type: 'float',
  31177. inputs: [
  31178. { name: 'hash', type: 'uint' },
  31179. { name: 'x', type: 'float' },
  31180. { name: 'y', type: 'float' }
  31181. ]
  31182. } );
  31183. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  31184. const z = float( z_immutable ).toVar();
  31185. const y = float( y_immutable ).toVar();
  31186. const x = float( x_immutable ).toVar();
  31187. const hash = uint( hash_immutable ).toVar();
  31188. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  31189. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  31190. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  31191. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  31192. } ).setLayout( {
  31193. name: 'mx_gradient_float_1',
  31194. type: 'float',
  31195. inputs: [
  31196. { name: 'hash', type: 'uint' },
  31197. { name: 'x', type: 'float' },
  31198. { name: 'y', type: 'float' },
  31199. { name: 'z', type: 'float' }
  31200. ]
  31201. } );
  31202. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  31203. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  31204. const y = float( y_immutable ).toVar();
  31205. const x = float( x_immutable ).toVar();
  31206. const hash = uvec3( hash_immutable ).toVar();
  31207. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  31208. } ).setLayout( {
  31209. name: 'mx_gradient_vec3_0',
  31210. type: 'vec3',
  31211. inputs: [
  31212. { name: 'hash', type: 'uvec3' },
  31213. { name: 'x', type: 'float' },
  31214. { name: 'y', type: 'float' }
  31215. ]
  31216. } );
  31217. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  31218. const z = float( z_immutable ).toVar();
  31219. const y = float( y_immutable ).toVar();
  31220. const x = float( x_immutable ).toVar();
  31221. const hash = uvec3( hash_immutable ).toVar();
  31222. 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 ) );
  31223. } ).setLayout( {
  31224. name: 'mx_gradient_vec3_1',
  31225. type: 'vec3',
  31226. inputs: [
  31227. { name: 'hash', type: 'uvec3' },
  31228. { name: 'x', type: 'float' },
  31229. { name: 'y', type: 'float' },
  31230. { name: 'z', type: 'float' }
  31231. ]
  31232. } );
  31233. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  31234. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  31235. const v = float( v_immutable ).toVar();
  31236. return mul( 0.6616, v );
  31237. } ).setLayout( {
  31238. name: 'mx_gradient_scale2d_0',
  31239. type: 'float',
  31240. inputs: [
  31241. { name: 'v', type: 'float' }
  31242. ]
  31243. } );
  31244. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  31245. const v = float( v_immutable ).toVar();
  31246. return mul( 0.9820, v );
  31247. } ).setLayout( {
  31248. name: 'mx_gradient_scale3d_0',
  31249. type: 'float',
  31250. inputs: [
  31251. { name: 'v', type: 'float' }
  31252. ]
  31253. } );
  31254. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  31255. const v = vec3( v_immutable ).toVar();
  31256. return mul( 0.6616, v );
  31257. } ).setLayout( {
  31258. name: 'mx_gradient_scale2d_1',
  31259. type: 'vec3',
  31260. inputs: [
  31261. { name: 'v', type: 'vec3' }
  31262. ]
  31263. } );
  31264. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  31265. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  31266. const v = vec3( v_immutable ).toVar();
  31267. return mul( 0.9820, v );
  31268. } ).setLayout( {
  31269. name: 'mx_gradient_scale3d_1',
  31270. type: 'vec3',
  31271. inputs: [
  31272. { name: 'v', type: 'vec3' }
  31273. ]
  31274. } );
  31275. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  31276. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  31277. const k = int( k_immutable ).toVar();
  31278. const x = uint( x_immutable ).toVar();
  31279. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  31280. } ).setLayout( {
  31281. name: 'mx_rotl32',
  31282. type: 'uint',
  31283. inputs: [
  31284. { name: 'x', type: 'uint' },
  31285. { name: 'k', type: 'int' }
  31286. ]
  31287. } );
  31288. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  31289. a.subAssign( c );
  31290. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  31291. c.addAssign( b );
  31292. b.subAssign( a );
  31293. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  31294. a.addAssign( c );
  31295. c.subAssign( b );
  31296. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  31297. b.addAssign( a );
  31298. a.subAssign( c );
  31299. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  31300. c.addAssign( b );
  31301. b.subAssign( a );
  31302. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  31303. a.addAssign( c );
  31304. c.subAssign( b );
  31305. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  31306. b.addAssign( a );
  31307. } );
  31308. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  31309. const c = uint( c_immutable ).toVar();
  31310. const b = uint( b_immutable ).toVar();
  31311. const a = uint( a_immutable ).toVar();
  31312. c.bitXorAssign( b );
  31313. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  31314. a.bitXorAssign( c );
  31315. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  31316. b.bitXorAssign( a );
  31317. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  31318. c.bitXorAssign( b );
  31319. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  31320. a.bitXorAssign( c );
  31321. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  31322. b.bitXorAssign( a );
  31323. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  31324. c.bitXorAssign( b );
  31325. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  31326. return c;
  31327. } ).setLayout( {
  31328. name: 'mx_bjfinal',
  31329. type: 'uint',
  31330. inputs: [
  31331. { name: 'a', type: 'uint' },
  31332. { name: 'b', type: 'uint' },
  31333. { name: 'c', type: 'uint' }
  31334. ]
  31335. } );
  31336. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  31337. const bits = uint( bits_immutable ).toVar();
  31338. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  31339. } ).setLayout( {
  31340. name: 'mx_bits_to_01',
  31341. type: 'float',
  31342. inputs: [
  31343. { name: 'bits', type: 'uint' }
  31344. ]
  31345. } );
  31346. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  31347. const t = float( t_immutable ).toVar();
  31348. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  31349. } ).setLayout( {
  31350. name: 'mx_fade',
  31351. type: 'float',
  31352. inputs: [
  31353. { name: 't', type: 'float' }
  31354. ]
  31355. } );
  31356. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  31357. const x = int( x_immutable ).toVar();
  31358. const len = uint( uint( 1 ) ).toVar();
  31359. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  31360. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  31361. } ).setLayout( {
  31362. name: 'mx_hash_int_0',
  31363. type: 'uint',
  31364. inputs: [
  31365. { name: 'x', type: 'int' }
  31366. ]
  31367. } );
  31368. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  31369. const y = int( y_immutable ).toVar();
  31370. const x = int( x_immutable ).toVar();
  31371. const len = uint( uint( 2 ) ).toVar();
  31372. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  31373. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  31374. a.addAssign( uint( x ) );
  31375. b.addAssign( uint( y ) );
  31376. return mx_bjfinal( a, b, c );
  31377. } ).setLayout( {
  31378. name: 'mx_hash_int_1',
  31379. type: 'uint',
  31380. inputs: [
  31381. { name: 'x', type: 'int' },
  31382. { name: 'y', type: 'int' }
  31383. ]
  31384. } );
  31385. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  31386. const z = int( z_immutable ).toVar();
  31387. const y = int( y_immutable ).toVar();
  31388. const x = int( x_immutable ).toVar();
  31389. const len = uint( uint( 3 ) ).toVar();
  31390. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  31391. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  31392. a.addAssign( uint( x ) );
  31393. b.addAssign( uint( y ) );
  31394. c.addAssign( uint( z ) );
  31395. return mx_bjfinal( a, b, c );
  31396. } ).setLayout( {
  31397. name: 'mx_hash_int_2',
  31398. type: 'uint',
  31399. inputs: [
  31400. { name: 'x', type: 'int' },
  31401. { name: 'y', type: 'int' },
  31402. { name: 'z', type: 'int' }
  31403. ]
  31404. } );
  31405. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  31406. const xx = int( xx_immutable ).toVar();
  31407. const z = int( z_immutable ).toVar();
  31408. const y = int( y_immutable ).toVar();
  31409. const x = int( x_immutable ).toVar();
  31410. const len = uint( uint( 4 ) ).toVar();
  31411. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  31412. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  31413. a.addAssign( uint( x ) );
  31414. b.addAssign( uint( y ) );
  31415. c.addAssign( uint( z ) );
  31416. mx_bjmix( a, b, c );
  31417. a.addAssign( uint( xx ) );
  31418. return mx_bjfinal( a, b, c );
  31419. } ).setLayout( {
  31420. name: 'mx_hash_int_3',
  31421. type: 'uint',
  31422. inputs: [
  31423. { name: 'x', type: 'int' },
  31424. { name: 'y', type: 'int' },
  31425. { name: 'z', type: 'int' },
  31426. { name: 'xx', type: 'int' }
  31427. ]
  31428. } );
  31429. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  31430. const yy = int( yy_immutable ).toVar();
  31431. const xx = int( xx_immutable ).toVar();
  31432. const z = int( z_immutable ).toVar();
  31433. const y = int( y_immutable ).toVar();
  31434. const x = int( x_immutable ).toVar();
  31435. const len = uint( uint( 5 ) ).toVar();
  31436. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  31437. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  31438. a.addAssign( uint( x ) );
  31439. b.addAssign( uint( y ) );
  31440. c.addAssign( uint( z ) );
  31441. mx_bjmix( a, b, c );
  31442. a.addAssign( uint( xx ) );
  31443. b.addAssign( uint( yy ) );
  31444. return mx_bjfinal( a, b, c );
  31445. } ).setLayout( {
  31446. name: 'mx_hash_int_4',
  31447. type: 'uint',
  31448. inputs: [
  31449. { name: 'x', type: 'int' },
  31450. { name: 'y', type: 'int' },
  31451. { name: 'z', type: 'int' },
  31452. { name: 'xx', type: 'int' },
  31453. { name: 'yy', type: 'int' }
  31454. ]
  31455. } );
  31456. 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 ] );
  31457. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  31458. const y = int( y_immutable ).toVar();
  31459. const x = int( x_immutable ).toVar();
  31460. const h = uint( mx_hash_int( x, y ) ).toVar();
  31461. const result = uvec3().toVar();
  31462. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  31463. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  31464. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  31465. return result;
  31466. } ).setLayout( {
  31467. name: 'mx_hash_vec3_0',
  31468. type: 'uvec3',
  31469. inputs: [
  31470. { name: 'x', type: 'int' },
  31471. { name: 'y', type: 'int' }
  31472. ]
  31473. } );
  31474. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  31475. const z = int( z_immutable ).toVar();
  31476. const y = int( y_immutable ).toVar();
  31477. const x = int( x_immutable ).toVar();
  31478. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  31479. const result = uvec3().toVar();
  31480. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  31481. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  31482. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  31483. return result;
  31484. } ).setLayout( {
  31485. name: 'mx_hash_vec3_1',
  31486. type: 'uvec3',
  31487. inputs: [
  31488. { name: 'x', type: 'int' },
  31489. { name: 'y', type: 'int' },
  31490. { name: 'z', type: 'int' }
  31491. ]
  31492. } );
  31493. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  31494. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31495. const p = vec2( p_immutable ).toVar();
  31496. const X = int().toVar(), Y = int().toVar();
  31497. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31498. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31499. const u = float( mx_fade( fx ) ).toVar();
  31500. const v = float( mx_fade( fy ) ).toVar();
  31501. 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();
  31502. return mx_gradient_scale2d( result );
  31503. } ).setLayout( {
  31504. name: 'mx_perlin_noise_float_0',
  31505. type: 'float',
  31506. inputs: [
  31507. { name: 'p', type: 'vec2' }
  31508. ]
  31509. } );
  31510. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31511. const p = vec3( p_immutable ).toVar();
  31512. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31513. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31514. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31515. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  31516. const u = float( mx_fade( fx ) ).toVar();
  31517. const v = float( mx_fade( fy ) ).toVar();
  31518. const w = float( mx_fade( fz ) ).toVar();
  31519. 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();
  31520. return mx_gradient_scale3d( result );
  31521. } ).setLayout( {
  31522. name: 'mx_perlin_noise_float_1',
  31523. type: 'float',
  31524. inputs: [
  31525. { name: 'p', type: 'vec3' }
  31526. ]
  31527. } );
  31528. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  31529. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31530. const p = vec2( p_immutable ).toVar();
  31531. const X = int().toVar(), Y = int().toVar();
  31532. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31533. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31534. const u = float( mx_fade( fx ) ).toVar();
  31535. const v = float( mx_fade( fy ) ).toVar();
  31536. 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();
  31537. return mx_gradient_scale2d( result );
  31538. } ).setLayout( {
  31539. name: 'mx_perlin_noise_vec3_0',
  31540. type: 'vec3',
  31541. inputs: [
  31542. { name: 'p', type: 'vec2' }
  31543. ]
  31544. } );
  31545. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31546. const p = vec3( p_immutable ).toVar();
  31547. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31548. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31549. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31550. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  31551. const u = float( mx_fade( fx ) ).toVar();
  31552. const v = float( mx_fade( fy ) ).toVar();
  31553. const w = float( mx_fade( fz ) ).toVar();
  31554. 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();
  31555. return mx_gradient_scale3d( result );
  31556. } ).setLayout( {
  31557. name: 'mx_perlin_noise_vec3_1',
  31558. type: 'vec3',
  31559. inputs: [
  31560. { name: 'p', type: 'vec3' }
  31561. ]
  31562. } );
  31563. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  31564. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31565. const p = float( p_immutable ).toVar();
  31566. const ix = int( mx_floor( p ) ).toVar();
  31567. return mx_bits_to_01( mx_hash_int( ix ) );
  31568. } ).setLayout( {
  31569. name: 'mx_cell_noise_float_0',
  31570. type: 'float',
  31571. inputs: [
  31572. { name: 'p', type: 'float' }
  31573. ]
  31574. } );
  31575. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31576. const p = vec2( p_immutable ).toVar();
  31577. const ix = int( mx_floor( p.x ) ).toVar();
  31578. const iy = int( mx_floor( p.y ) ).toVar();
  31579. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  31580. } ).setLayout( {
  31581. name: 'mx_cell_noise_float_1',
  31582. type: 'float',
  31583. inputs: [
  31584. { name: 'p', type: 'vec2' }
  31585. ]
  31586. } );
  31587. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31588. const p = vec3( p_immutable ).toVar();
  31589. const ix = int( mx_floor( p.x ) ).toVar();
  31590. const iy = int( mx_floor( p.y ) ).toVar();
  31591. const iz = int( mx_floor( p.z ) ).toVar();
  31592. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  31593. } ).setLayout( {
  31594. name: 'mx_cell_noise_float_2',
  31595. type: 'float',
  31596. inputs: [
  31597. { name: 'p', type: 'vec3' }
  31598. ]
  31599. } );
  31600. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31601. const p = vec4( p_immutable ).toVar();
  31602. const ix = int( mx_floor( p.x ) ).toVar();
  31603. const iy = int( mx_floor( p.y ) ).toVar();
  31604. const iz = int( mx_floor( p.z ) ).toVar();
  31605. const iw = int( mx_floor( p.w ) ).toVar();
  31606. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  31607. } ).setLayout( {
  31608. name: 'mx_cell_noise_float_3',
  31609. type: 'float',
  31610. inputs: [
  31611. { name: 'p', type: 'vec4' }
  31612. ]
  31613. } );
  31614. 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 ] );
  31615. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31616. const p = float( p_immutable ).toVar();
  31617. const ix = int( mx_floor( p ) ).toVar();
  31618. 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 ) ) ) );
  31619. } ).setLayout( {
  31620. name: 'mx_cell_noise_vec3_0',
  31621. type: 'vec3',
  31622. inputs: [
  31623. { name: 'p', type: 'float' }
  31624. ]
  31625. } );
  31626. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31627. const p = vec2( p_immutable ).toVar();
  31628. const ix = int( mx_floor( p.x ) ).toVar();
  31629. const iy = int( mx_floor( p.y ) ).toVar();
  31630. 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 ) ) ) );
  31631. } ).setLayout( {
  31632. name: 'mx_cell_noise_vec3_1',
  31633. type: 'vec3',
  31634. inputs: [
  31635. { name: 'p', type: 'vec2' }
  31636. ]
  31637. } );
  31638. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31639. const p = vec3( p_immutable ).toVar();
  31640. const ix = int( mx_floor( p.x ) ).toVar();
  31641. const iy = int( mx_floor( p.y ) ).toVar();
  31642. const iz = int( mx_floor( p.z ) ).toVar();
  31643. 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 ) ) ) );
  31644. } ).setLayout( {
  31645. name: 'mx_cell_noise_vec3_2',
  31646. type: 'vec3',
  31647. inputs: [
  31648. { name: 'p', type: 'vec3' }
  31649. ]
  31650. } );
  31651. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31652. const p = vec4( p_immutable ).toVar();
  31653. const ix = int( mx_floor( p.x ) ).toVar();
  31654. const iy = int( mx_floor( p.y ) ).toVar();
  31655. const iz = int( mx_floor( p.z ) ).toVar();
  31656. const iw = int( mx_floor( p.w ) ).toVar();
  31657. 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 ) ) ) );
  31658. } ).setLayout( {
  31659. name: 'mx_cell_noise_vec3_3',
  31660. type: 'vec3',
  31661. inputs: [
  31662. { name: 'p', type: 'vec4' }
  31663. ]
  31664. } );
  31665. 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 ] );
  31666. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31667. const diminish = float( diminish_immutable ).toVar();
  31668. const lacunarity = float( lacunarity_immutable ).toVar();
  31669. const octaves = int( octaves_immutable ).toVar();
  31670. const p = vec3( p_immutable ).toVar();
  31671. const result = float( 0.0 ).toVar();
  31672. const amplitude = float( 1.0 ).toVar();
  31673. Loop( octaves, () => {
  31674. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  31675. amplitude.mulAssign( diminish );
  31676. p.mulAssign( lacunarity );
  31677. } );
  31678. return result;
  31679. } ).setLayout( {
  31680. name: 'mx_fractal_noise_float',
  31681. type: 'float',
  31682. inputs: [
  31683. { name: 'p', type: 'vec3' },
  31684. { name: 'octaves', type: 'int' },
  31685. { name: 'lacunarity', type: 'float' },
  31686. { name: 'diminish', type: 'float' }
  31687. ]
  31688. } );
  31689. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31690. const diminish = float( diminish_immutable ).toVar();
  31691. const lacunarity = float( lacunarity_immutable ).toVar();
  31692. const octaves = int( octaves_immutable ).toVar();
  31693. const p = vec3( p_immutable ).toVar();
  31694. const result = vec3( 0.0 ).toVar();
  31695. const amplitude = float( 1.0 ).toVar();
  31696. Loop( octaves, () => {
  31697. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  31698. amplitude.mulAssign( diminish );
  31699. p.mulAssign( lacunarity );
  31700. } );
  31701. return result;
  31702. } ).setLayout( {
  31703. name: 'mx_fractal_noise_vec3',
  31704. type: 'vec3',
  31705. inputs: [
  31706. { name: 'p', type: 'vec3' },
  31707. { name: 'octaves', type: 'int' },
  31708. { name: 'lacunarity', type: 'float' },
  31709. { name: 'diminish', type: 'float' }
  31710. ]
  31711. } );
  31712. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31713. const diminish = float( diminish_immutable ).toVar();
  31714. const lacunarity = float( lacunarity_immutable ).toVar();
  31715. const octaves = int( octaves_immutable ).toVar();
  31716. const p = vec3( p_immutable ).toVar();
  31717. 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 ) );
  31718. } ).setLayout( {
  31719. name: 'mx_fractal_noise_vec2',
  31720. type: 'vec2',
  31721. inputs: [
  31722. { name: 'p', type: 'vec3' },
  31723. { name: 'octaves', type: 'int' },
  31724. { name: 'lacunarity', type: 'float' },
  31725. { name: 'diminish', type: 'float' }
  31726. ]
  31727. } );
  31728. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31729. const diminish = float( diminish_immutable ).toVar();
  31730. const lacunarity = float( lacunarity_immutable ).toVar();
  31731. const octaves = int( octaves_immutable ).toVar();
  31732. const p = vec3( p_immutable ).toVar();
  31733. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  31734. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  31735. return vec4( c, f );
  31736. } ).setLayout( {
  31737. name: 'mx_fractal_noise_vec4',
  31738. type: 'vec4',
  31739. inputs: [
  31740. { name: 'p', type: 'vec3' },
  31741. { name: 'octaves', type: 'int' },
  31742. { name: 'lacunarity', type: 'float' },
  31743. { name: 'diminish', type: 'float' }
  31744. ]
  31745. } );
  31746. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  31747. const metric = int( metric_immutable ).toVar();
  31748. const jitter = float( jitter_immutable ).toVar();
  31749. const yoff = int( yoff_immutable ).toVar();
  31750. const xoff = int( xoff_immutable ).toVar();
  31751. const y = int( y_immutable ).toVar();
  31752. const x = int( x_immutable ).toVar();
  31753. const p = vec2( p_immutable ).toVar();
  31754. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  31755. const off = vec2( tmp.x, tmp.y ).toVar();
  31756. off.subAssign( 0.5 );
  31757. off.mulAssign( jitter );
  31758. off.addAssign( 0.5 );
  31759. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  31760. const diff = vec2( cellpos.sub( p ) ).toVar();
  31761. If( metric.equal( int( 2 ) ), () => {
  31762. return abs( diff.x ).add( abs( diff.y ) );
  31763. } );
  31764. If( metric.equal( int( 3 ) ), () => {
  31765. return max$1( abs( diff.x ), abs( diff.y ) );
  31766. } );
  31767. return dot( diff, diff );
  31768. } ).setLayout( {
  31769. name: 'mx_worley_distance_0',
  31770. type: 'float',
  31771. inputs: [
  31772. { name: 'p', type: 'vec2' },
  31773. { name: 'x', type: 'int' },
  31774. { name: 'y', type: 'int' },
  31775. { name: 'xoff', type: 'int' },
  31776. { name: 'yoff', type: 'int' },
  31777. { name: 'jitter', type: 'float' },
  31778. { name: 'metric', type: 'int' }
  31779. ]
  31780. } );
  31781. 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 ] ) => {
  31782. const metric = int( metric_immutable ).toVar();
  31783. const jitter = float( jitter_immutable ).toVar();
  31784. const zoff = int( zoff_immutable ).toVar();
  31785. const yoff = int( yoff_immutable ).toVar();
  31786. const xoff = int( xoff_immutable ).toVar();
  31787. const z = int( z_immutable ).toVar();
  31788. const y = int( y_immutable ).toVar();
  31789. const x = int( x_immutable ).toVar();
  31790. const p = vec3( p_immutable ).toVar();
  31791. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  31792. off.subAssign( 0.5 );
  31793. off.mulAssign( jitter );
  31794. off.addAssign( 0.5 );
  31795. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  31796. const diff = vec3( cellpos.sub( p ) ).toVar();
  31797. If( metric.equal( int( 2 ) ), () => {
  31798. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  31799. } );
  31800. If( metric.equal( int( 3 ) ), () => {
  31801. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  31802. } );
  31803. return dot( diff, diff );
  31804. } ).setLayout( {
  31805. name: 'mx_worley_distance_1',
  31806. type: 'float',
  31807. inputs: [
  31808. { name: 'p', type: 'vec3' },
  31809. { name: 'x', type: 'int' },
  31810. { name: 'y', type: 'int' },
  31811. { name: 'z', type: 'int' },
  31812. { name: 'xoff', type: 'int' },
  31813. { name: 'yoff', type: 'int' },
  31814. { name: 'zoff', type: 'int' },
  31815. { name: 'jitter', type: 'float' },
  31816. { name: 'metric', type: 'int' }
  31817. ]
  31818. } );
  31819. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  31820. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31821. const metric = int( metric_immutable ).toVar();
  31822. const jitter = float( jitter_immutable ).toVar();
  31823. const p = vec2( p_immutable ).toVar();
  31824. const X = int().toVar(), Y = int().toVar();
  31825. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  31826. const sqdist = float( 1e6 ).toVar();
  31827. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31828. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31829. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  31830. sqdist.assign( min$1( sqdist, dist ) );
  31831. } );
  31832. } );
  31833. If( metric.equal( int( 0 ) ), () => {
  31834. sqdist.assign( sqrt( sqdist ) );
  31835. } );
  31836. return sqdist;
  31837. } ).setLayout( {
  31838. name: 'mx_worley_noise_float_0',
  31839. type: 'float',
  31840. inputs: [
  31841. { name: 'p', type: 'vec2' },
  31842. { name: 'jitter', type: 'float' },
  31843. { name: 'metric', type: 'int' }
  31844. ]
  31845. } );
  31846. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31847. const metric = int( metric_immutable ).toVar();
  31848. const jitter = float( jitter_immutable ).toVar();
  31849. const p = vec2( p_immutable ).toVar();
  31850. const X = int().toVar(), Y = int().toVar();
  31851. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  31852. const sqdist = vec2( 1e6, 1e6 ).toVar();
  31853. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31854. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31855. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  31856. If( dist.lessThan( sqdist.x ), () => {
  31857. sqdist.y.assign( sqdist.x );
  31858. sqdist.x.assign( dist );
  31859. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31860. sqdist.y.assign( dist );
  31861. } );
  31862. } );
  31863. } );
  31864. If( metric.equal( int( 0 ) ), () => {
  31865. sqdist.assign( sqrt( sqdist ) );
  31866. } );
  31867. return sqdist;
  31868. } ).setLayout( {
  31869. name: 'mx_worley_noise_vec2_0',
  31870. type: 'vec2',
  31871. inputs: [
  31872. { name: 'p', type: 'vec2' },
  31873. { name: 'jitter', type: 'float' },
  31874. { name: 'metric', type: 'int' }
  31875. ]
  31876. } );
  31877. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31878. const metric = int( metric_immutable ).toVar();
  31879. const jitter = float( jitter_immutable ).toVar();
  31880. const p = vec2( p_immutable ).toVar();
  31881. const X = int().toVar(), Y = int().toVar();
  31882. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  31883. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  31884. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31885. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31886. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  31887. If( dist.lessThan( sqdist.x ), () => {
  31888. sqdist.z.assign( sqdist.y );
  31889. sqdist.y.assign( sqdist.x );
  31890. sqdist.x.assign( dist );
  31891. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31892. sqdist.z.assign( sqdist.y );
  31893. sqdist.y.assign( dist );
  31894. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  31895. sqdist.z.assign( dist );
  31896. } );
  31897. } );
  31898. } );
  31899. If( metric.equal( int( 0 ) ), () => {
  31900. sqdist.assign( sqrt( sqdist ) );
  31901. } );
  31902. return sqdist;
  31903. } ).setLayout( {
  31904. name: 'mx_worley_noise_vec3_0',
  31905. type: 'vec3',
  31906. inputs: [
  31907. { name: 'p', type: 'vec2' },
  31908. { name: 'jitter', type: 'float' },
  31909. { name: 'metric', type: 'int' }
  31910. ]
  31911. } );
  31912. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31913. const metric = int( metric_immutable ).toVar();
  31914. const jitter = float( jitter_immutable ).toVar();
  31915. const p = vec3( p_immutable ).toVar();
  31916. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31917. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  31918. const sqdist = float( 1e6 ).toVar();
  31919. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31920. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31921. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  31922. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  31923. sqdist.assign( min$1( sqdist, dist ) );
  31924. } );
  31925. } );
  31926. } );
  31927. If( metric.equal( int( 0 ) ), () => {
  31928. sqdist.assign( sqrt( sqdist ) );
  31929. } );
  31930. return sqdist;
  31931. } ).setLayout( {
  31932. name: 'mx_worley_noise_float_1',
  31933. type: 'float',
  31934. inputs: [
  31935. { name: 'p', type: 'vec3' },
  31936. { name: 'jitter', type: 'float' },
  31937. { name: 'metric', type: 'int' }
  31938. ]
  31939. } );
  31940. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  31941. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31942. const metric = int( metric_immutable ).toVar();
  31943. const jitter = float( jitter_immutable ).toVar();
  31944. const p = vec3( p_immutable ).toVar();
  31945. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31946. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  31947. const sqdist = vec2( 1e6, 1e6 ).toVar();
  31948. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31949. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31950. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  31951. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  31952. If( dist.lessThan( sqdist.x ), () => {
  31953. sqdist.y.assign( sqdist.x );
  31954. sqdist.x.assign( dist );
  31955. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31956. sqdist.y.assign( dist );
  31957. } );
  31958. } );
  31959. } );
  31960. } );
  31961. If( metric.equal( int( 0 ) ), () => {
  31962. sqdist.assign( sqrt( sqdist ) );
  31963. } );
  31964. return sqdist;
  31965. } ).setLayout( {
  31966. name: 'mx_worley_noise_vec2_1',
  31967. type: 'vec2',
  31968. inputs: [
  31969. { name: 'p', type: 'vec3' },
  31970. { name: 'jitter', type: 'float' },
  31971. { name: 'metric', type: 'int' }
  31972. ]
  31973. } );
  31974. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  31975. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31976. const metric = int( metric_immutable ).toVar();
  31977. const jitter = float( jitter_immutable ).toVar();
  31978. const p = vec3( p_immutable ).toVar();
  31979. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31980. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  31981. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  31982. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31983. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31984. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  31985. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  31986. If( dist.lessThan( sqdist.x ), () => {
  31987. sqdist.z.assign( sqdist.y );
  31988. sqdist.y.assign( sqdist.x );
  31989. sqdist.x.assign( dist );
  31990. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31991. sqdist.z.assign( sqdist.y );
  31992. sqdist.y.assign( dist );
  31993. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  31994. sqdist.z.assign( dist );
  31995. } );
  31996. } );
  31997. } );
  31998. } );
  31999. If( metric.equal( int( 0 ) ), () => {
  32000. sqdist.assign( sqrt( sqdist ) );
  32001. } );
  32002. return sqdist;
  32003. } ).setLayout( {
  32004. name: 'mx_worley_noise_vec3_1',
  32005. type: 'vec3',
  32006. inputs: [
  32007. { name: 'p', type: 'vec3' },
  32008. { name: 'jitter', type: 'float' },
  32009. { name: 'metric', type: 'int' }
  32010. ]
  32011. } );
  32012. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  32013. // Unified Noise 2D
  32014. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  32015. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  32016. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  32017. octaves_immutable, lacunarity_immutable, diminish_immutable
  32018. ] ) => {
  32019. const noiseType = int( noiseType_immutable ).toVar();
  32020. const texcoord = vec2( texcoord_immutable ).toVar();
  32021. const freq = vec2( freq_immutable ).toVar();
  32022. const offset = vec2( offset_immutable ).toVar();
  32023. const jitter = float( jitter_immutable ).toVar();
  32024. const outmin = float( outmin_immutable ).toVar();
  32025. const outmax = float( outmax_immutable ).toVar();
  32026. const clampoutput = bool( clampoutput_immutable ).toVar();
  32027. const octaves = int( octaves_immutable ).toVar();
  32028. const lacunarity = float( lacunarity_immutable ).toVar();
  32029. const diminish = float( diminish_immutable ).toVar();
  32030. // Compute input position
  32031. const p = texcoord.mul( freq ).add( offset );
  32032. const result = float( 0.0 ).toVar();
  32033. // Perlin
  32034. If( noiseType.equal( int( 0 ) ), () => {
  32035. result.assign( mx_perlin_noise_vec3( p ) );
  32036. } );
  32037. // Cell
  32038. If( noiseType.equal( int( 1 ) ), () => {
  32039. result.assign( mx_cell_noise_vec3( p ) );
  32040. } );
  32041. // Worley (metric=0 = euclidean)
  32042. If( noiseType.equal( int( 2 ) ), () => {
  32043. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  32044. } );
  32045. // Fractal (use vec3(p, 0.0) for 2D input)
  32046. If( noiseType.equal( int( 3 ) ), () => {
  32047. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  32048. } );
  32049. // Remap output to [outmin, outmax]
  32050. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  32051. // Clamp if requested
  32052. If( clampoutput, () => {
  32053. result.assign( clamp( result, outmin, outmax ) );
  32054. } );
  32055. return result;
  32056. } ).setLayout( {
  32057. name: 'mx_unifiednoise2d',
  32058. type: 'float',
  32059. inputs: [
  32060. { name: 'noiseType', type: 'int' },
  32061. { name: 'texcoord', type: 'vec2' },
  32062. { name: 'freq', type: 'vec2' },
  32063. { name: 'offset', type: 'vec2' },
  32064. { name: 'jitter', type: 'float' },
  32065. { name: 'outmin', type: 'float' },
  32066. { name: 'outmax', type: 'float' },
  32067. { name: 'clampoutput', type: 'bool' },
  32068. { name: 'octaves', type: 'int' },
  32069. { name: 'lacunarity', type: 'float' },
  32070. { name: 'diminish', type: 'float' }
  32071. ]
  32072. } );
  32073. // Unified Noise 3D
  32074. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  32075. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  32076. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  32077. octaves_immutable, lacunarity_immutable, diminish_immutable
  32078. ] ) => {
  32079. const noiseType = int( noiseType_immutable ).toVar();
  32080. const position = vec3( position_immutable ).toVar();
  32081. const freq = vec3( freq_immutable ).toVar();
  32082. const offset = vec3( offset_immutable ).toVar();
  32083. const jitter = float( jitter_immutable ).toVar();
  32084. const outmin = float( outmin_immutable ).toVar();
  32085. const outmax = float( outmax_immutable ).toVar();
  32086. const clampoutput = bool( clampoutput_immutable ).toVar();
  32087. const octaves = int( octaves_immutable ).toVar();
  32088. const lacunarity = float( lacunarity_immutable ).toVar();
  32089. const diminish = float( diminish_immutable ).toVar();
  32090. // Compute input position
  32091. const p = position.mul( freq ).add( offset );
  32092. const result = float( 0.0 ).toVar();
  32093. // Perlin
  32094. If( noiseType.equal( int( 0 ) ), () => {
  32095. result.assign( mx_perlin_noise_vec3( p ) );
  32096. } );
  32097. // Cell
  32098. If( noiseType.equal( int( 1 ) ), () => {
  32099. result.assign( mx_cell_noise_vec3( p ) );
  32100. } );
  32101. // Worley (metric=0 = euclidean)
  32102. If( noiseType.equal( int( 2 ) ), () => {
  32103. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  32104. } );
  32105. // Fractal
  32106. If( noiseType.equal( int( 3 ) ), () => {
  32107. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  32108. } );
  32109. // Remap output to [outmin, outmax]
  32110. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  32111. // Clamp if requested
  32112. If( clampoutput, () => {
  32113. result.assign( clamp( result, outmin, outmax ) );
  32114. } );
  32115. return result;
  32116. } ).setLayout( {
  32117. name: 'mx_unifiednoise3d',
  32118. type: 'float',
  32119. inputs: [
  32120. { name: 'noiseType', type: 'int' },
  32121. { name: 'position', type: 'vec3' },
  32122. { name: 'freq', type: 'vec3' },
  32123. { name: 'offset', type: 'vec3' },
  32124. { name: 'jitter', type: 'float' },
  32125. { name: 'outmin', type: 'float' },
  32126. { name: 'outmax', type: 'float' },
  32127. { name: 'clampoutput', type: 'bool' },
  32128. { name: 'octaves', type: 'int' },
  32129. { name: 'lacunarity', type: 'float' },
  32130. { name: 'diminish', type: 'float' }
  32131. ]
  32132. } );
  32133. // Three.js Transpiler
  32134. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  32135. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  32136. const s = hsv.y;
  32137. const v = hsv.z;
  32138. const result = vec3().toVar();
  32139. If( s.lessThan( 0.0001 ), () => {
  32140. result.assign( vec3( v, v, v ) );
  32141. } ).Else( () => {
  32142. let h = hsv.x;
  32143. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  32144. const hi = int( trunc( h ) );
  32145. const f = h.sub( float( hi ) );
  32146. const p = v.mul( s.oneMinus() );
  32147. const q = v.mul( s.mul( f ).oneMinus() );
  32148. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  32149. If( hi.equal( int( 0 ) ), () => {
  32150. result.assign( vec3( v, t, p ) );
  32151. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  32152. result.assign( vec3( q, v, p ) );
  32153. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  32154. result.assign( vec3( p, v, t ) );
  32155. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  32156. result.assign( vec3( p, q, v ) );
  32157. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  32158. result.assign( vec3( t, p, v ) );
  32159. } ).Else( () => {
  32160. result.assign( vec3( v, p, q ) );
  32161. } );
  32162. } );
  32163. return result;
  32164. } ).setLayout( {
  32165. name: 'mx_hsvtorgb',
  32166. type: 'vec3',
  32167. inputs: [
  32168. { name: 'hsv', type: 'vec3' }
  32169. ]
  32170. } );
  32171. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  32172. const c = vec3( c_immutable ).toVar();
  32173. const r = float( c.x ).toVar();
  32174. const g = float( c.y ).toVar();
  32175. const b = float( c.z ).toVar();
  32176. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  32177. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  32178. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  32179. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  32180. v.assign( maxcomp );
  32181. If( maxcomp.greaterThan( 0.0 ), () => {
  32182. s.assign( delta.div( maxcomp ) );
  32183. } ).Else( () => {
  32184. s.assign( 0.0 );
  32185. } );
  32186. If( s.lessThanEqual( 0.0 ), () => {
  32187. h.assign( 0.0 );
  32188. } ).Else( () => {
  32189. If( r.greaterThanEqual( maxcomp ), () => {
  32190. h.assign( g.sub( b ).div( delta ) );
  32191. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  32192. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  32193. } ).Else( () => {
  32194. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  32195. } );
  32196. h.mulAssign( 1.0 / 6.0 );
  32197. If( h.lessThan( 0.0 ), () => {
  32198. h.addAssign( 1.0 );
  32199. } );
  32200. } );
  32201. return vec3( h, s, v );
  32202. } ).setLayout( {
  32203. name: 'mx_rgbtohsv',
  32204. type: 'vec3',
  32205. inputs: [
  32206. { name: 'c', type: 'vec3' }
  32207. ]
  32208. } );
  32209. // Three.js Transpiler
  32210. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  32211. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  32212. const color = vec3( color_immutable ).toVar();
  32213. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  32214. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  32215. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  32216. return mix( linSeg, powSeg, isAbove );
  32217. } ).setLayout( {
  32218. name: 'mx_srgb_texture_to_lin_rec709',
  32219. type: 'vec3',
  32220. inputs: [
  32221. { name: 'color', type: 'vec3' }
  32222. ]
  32223. } );
  32224. const mx_aastep = ( threshold, value ) => {
  32225. threshold = float( threshold );
  32226. value = float( value );
  32227. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  32228. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  32229. };
  32230. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  32231. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  32232. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  32233. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  32234. const mx_ramp4 = (
  32235. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  32236. ) => {
  32237. const u = texcoord.x.clamp();
  32238. const v = texcoord.y.clamp();
  32239. const top = mix( valuetl, valuetr, u );
  32240. const bottom = mix( valuebl, valuebr, u );
  32241. return mix( top, bottom, v );
  32242. };
  32243. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  32244. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  32245. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  32246. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  32247. const mx_safepower = ( in1, in2 = 1 ) => {
  32248. in1 = float( in1 );
  32249. return in1.abs().pow( in2 ).mul( in1.sign() );
  32250. };
  32251. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  32252. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  32253. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  32254. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  32255. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  32256. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  32257. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  32258. return noise_vec4.mul( amplitude ).add( pivot );
  32259. };
  32260. 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 );
  32261. 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 );
  32262. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  32263. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  32264. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  32265. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  32266. 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 );
  32267. 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 );
  32268. 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 );
  32269. 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 );
  32270. // === Moved from MaterialXLoader.js ===
  32271. // Math ops
  32272. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  32273. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  32274. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  32275. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  32276. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  32277. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  32278. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  32279. const mx_timer = () => time;
  32280. const mx_frame = () => frameId;
  32281. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  32282. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  32283. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  32284. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  32285. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  32286. const mx_separate = ( in1, channelOrOut = null ) => {
  32287. if ( typeof channelOrOut === 'string' ) {
  32288. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  32289. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  32290. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  32291. }
  32292. if ( typeof channelOrOut === 'number' ) {
  32293. return in1.element( channelOrOut );
  32294. }
  32295. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  32296. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  32297. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  32298. }
  32299. return in1;
  32300. };
  32301. const mx_place2d = (
  32302. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  32303. ) => {
  32304. let uv = texcoord;
  32305. if ( pivot ) uv = uv.sub( pivot );
  32306. if ( scale ) uv = uv.mul( scale );
  32307. if ( rotate ) {
  32308. const rad = rotate.mul( Math.PI / 180.0 );
  32309. const cosR = rad.cos();
  32310. const sinR = rad.sin();
  32311. uv = vec2(
  32312. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  32313. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  32314. );
  32315. }
  32316. if ( pivot ) uv = uv.add( pivot );
  32317. if ( offset ) uv = uv.add( offset );
  32318. return uv;
  32319. };
  32320. const mx_rotate2d = ( input, amount ) => {
  32321. input = vec2( input );
  32322. amount = float( amount );
  32323. const radians = amount.mul( Math.PI / 180.0 );
  32324. return rotate( input, radians );
  32325. };
  32326. const mx_rotate3d = ( input, amount, axis ) => {
  32327. input = vec3( input );
  32328. amount = float( amount );
  32329. axis = vec3( axis );
  32330. const radians = amount.mul( Math.PI / 180.0 );
  32331. const nAxis = axis.normalize();
  32332. const cosA = radians.cos();
  32333. const sinA = radians.sin();
  32334. const oneMinusCosA = float( 1 ).sub( cosA );
  32335. const rot =
  32336. input.mul( cosA )
  32337. .add( nAxis.cross( input ).mul( sinA ) )
  32338. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  32339. return rot;
  32340. };
  32341. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  32342. input = vec3( input );
  32343. scale = float( scale );
  32344. return bumpMap( input, scale );
  32345. };
  32346. /**
  32347. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  32348. *
  32349. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  32350. *
  32351. * ```js
  32352. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  32353. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  32354. * ```
  32355. *
  32356. * @tsl
  32357. * @function
  32358. * @param {Node<vec3>} normal - The normal to correct.
  32359. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  32360. * @param {Node<vec3>} cubePos - The cube position.
  32361. * @return {Node<vec3>} The parallax corrected normal.
  32362. */
  32363. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  32364. const nDir = normalize( normal ).toVar();
  32365. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  32366. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  32367. const rbminmax = vec3().toVar();
  32368. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  32369. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  32370. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  32371. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  32372. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  32373. return boxIntersection.sub( cubePos );
  32374. } );
  32375. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  32376. // normal is assumed to have unit length
  32377. const x = normal.x, y = normal.y, z = normal.z;
  32378. // band 0
  32379. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  32380. // band 1
  32381. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  32382. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  32383. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  32384. // band 2
  32385. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  32386. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  32387. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  32388. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  32389. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  32390. return result;
  32391. } );
  32392. // constants
  32393. var TSL = /*#__PURE__*/Object.freeze({
  32394. __proto__: null,
  32395. BRDF_GGX: BRDF_GGX,
  32396. BRDF_Lambert: BRDF_Lambert,
  32397. BasicPointShadowFilter: BasicPointShadowFilter,
  32398. BasicShadowFilter: BasicShadowFilter,
  32399. Break: Break,
  32400. Const: Const,
  32401. Continue: Continue,
  32402. DFGApprox: DFGApprox,
  32403. D_GGX: D_GGX,
  32404. Discard: Discard,
  32405. EPSILON: EPSILON,
  32406. F_Schlick: F_Schlick,
  32407. Fn: Fn,
  32408. HALF_PI: HALF_PI,
  32409. INFINITY: INFINITY,
  32410. If: If,
  32411. Loop: Loop,
  32412. NodeAccess: NodeAccess,
  32413. NodeShaderStage: NodeShaderStage,
  32414. NodeType: NodeType,
  32415. NodeUpdateType: NodeUpdateType,
  32416. OnMaterialUpdate: OnMaterialUpdate,
  32417. OnObjectUpdate: OnObjectUpdate,
  32418. PCFShadowFilter: PCFShadowFilter,
  32419. PCFSoftShadowFilter: PCFSoftShadowFilter,
  32420. PI: PI,
  32421. PI2: PI2,
  32422. PointShadowFilter: PointShadowFilter,
  32423. Return: Return,
  32424. Schlick_to_F0: Schlick_to_F0,
  32425. ScriptableNodeResources: ScriptableNodeResources,
  32426. ShaderNode: ShaderNode,
  32427. Stack: Stack,
  32428. Switch: Switch,
  32429. TBNViewMatrix: TBNViewMatrix,
  32430. TWO_PI: TWO_PI,
  32431. VSMShadowFilter: VSMShadowFilter,
  32432. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  32433. Var: Var,
  32434. VarIntent: VarIntent,
  32435. abs: abs,
  32436. acesFilmicToneMapping: acesFilmicToneMapping,
  32437. acos: acos,
  32438. add: add,
  32439. addMethodChaining: addMethodChaining,
  32440. addNodeElement: addNodeElement,
  32441. agxToneMapping: agxToneMapping,
  32442. all: all,
  32443. alphaT: alphaT,
  32444. and: and,
  32445. anisotropy: anisotropy,
  32446. anisotropyB: anisotropyB,
  32447. anisotropyT: anisotropyT,
  32448. any: any,
  32449. append: append,
  32450. array: array,
  32451. arrayBuffer: arrayBuffer,
  32452. asin: asin,
  32453. assign: assign,
  32454. atan: atan,
  32455. atan2: atan2,
  32456. atomicAdd: atomicAdd,
  32457. atomicAnd: atomicAnd,
  32458. atomicFunc: atomicFunc,
  32459. atomicLoad: atomicLoad,
  32460. atomicMax: atomicMax,
  32461. atomicMin: atomicMin,
  32462. atomicOr: atomicOr,
  32463. atomicStore: atomicStore,
  32464. atomicSub: atomicSub,
  32465. atomicXor: atomicXor,
  32466. attenuationColor: attenuationColor,
  32467. attenuationDistance: attenuationDistance,
  32468. attribute: attribute,
  32469. attributeArray: attributeArray,
  32470. backgroundBlurriness: backgroundBlurriness,
  32471. backgroundIntensity: backgroundIntensity,
  32472. backgroundRotation: backgroundRotation,
  32473. batch: batch,
  32474. bentNormalView: bentNormalView,
  32475. billboarding: billboarding,
  32476. bitAnd: bitAnd,
  32477. bitNot: bitNot,
  32478. bitOr: bitOr,
  32479. bitXor: bitXor,
  32480. bitangentGeometry: bitangentGeometry,
  32481. bitangentLocal: bitangentLocal,
  32482. bitangentView: bitangentView,
  32483. bitangentWorld: bitangentWorld,
  32484. bitcast: bitcast,
  32485. blendBurn: blendBurn,
  32486. blendColor: blendColor,
  32487. blendDodge: blendDodge,
  32488. blendOverlay: blendOverlay,
  32489. blendScreen: blendScreen,
  32490. blur: blur,
  32491. bool: bool,
  32492. buffer: buffer,
  32493. bufferAttribute: bufferAttribute,
  32494. builtin: builtin,
  32495. bumpMap: bumpMap,
  32496. burn: burn,
  32497. bvec2: bvec2,
  32498. bvec3: bvec3,
  32499. bvec4: bvec4,
  32500. bypass: bypass,
  32501. cache: cache,
  32502. call: call,
  32503. cameraFar: cameraFar,
  32504. cameraIndex: cameraIndex,
  32505. cameraNear: cameraNear,
  32506. cameraNormalMatrix: cameraNormalMatrix,
  32507. cameraPosition: cameraPosition,
  32508. cameraProjectionMatrix: cameraProjectionMatrix,
  32509. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  32510. cameraViewMatrix: cameraViewMatrix,
  32511. cameraViewport: cameraViewport,
  32512. cameraWorldMatrix: cameraWorldMatrix,
  32513. cbrt: cbrt,
  32514. cdl: cdl,
  32515. ceil: ceil,
  32516. checker: checker,
  32517. cineonToneMapping: cineonToneMapping,
  32518. clamp: clamp,
  32519. clearcoat: clearcoat,
  32520. clearcoatNormalView: clearcoatNormalView,
  32521. clearcoatRoughness: clearcoatRoughness,
  32522. code: code,
  32523. color: color,
  32524. colorSpaceToWorking: colorSpaceToWorking,
  32525. colorToDirection: colorToDirection,
  32526. compute: compute,
  32527. computeKernel: computeKernel,
  32528. computeSkinning: computeSkinning,
  32529. context: context,
  32530. convert: convert,
  32531. convertColorSpace: convertColorSpace,
  32532. convertToTexture: convertToTexture,
  32533. cos: cos,
  32534. cross: cross,
  32535. cubeTexture: cubeTexture,
  32536. cubeTextureBase: cubeTextureBase,
  32537. cubeToUV: cubeToUV,
  32538. dFdx: dFdx,
  32539. dFdy: dFdy,
  32540. dashSize: dashSize,
  32541. debug: debug,
  32542. decrement: decrement,
  32543. decrementBefore: decrementBefore,
  32544. defaultBuildStages: defaultBuildStages,
  32545. defaultShaderStages: defaultShaderStages,
  32546. defined: defined,
  32547. degrees: degrees,
  32548. deltaTime: deltaTime,
  32549. densityFog: densityFog,
  32550. densityFogFactor: densityFogFactor,
  32551. depth: depth,
  32552. depthPass: depthPass,
  32553. determinant: determinant,
  32554. difference: difference,
  32555. diffuseColor: diffuseColor,
  32556. directPointLight: directPointLight,
  32557. directionToColor: directionToColor,
  32558. directionToFaceDirection: directionToFaceDirection,
  32559. dispersion: dispersion,
  32560. distance: distance,
  32561. div: div,
  32562. dodge: dodge,
  32563. dot: dot,
  32564. drawIndex: drawIndex,
  32565. dynamicBufferAttribute: dynamicBufferAttribute,
  32566. element: element,
  32567. emissive: emissive,
  32568. equal: equal,
  32569. equals: equals,
  32570. equirectUV: equirectUV,
  32571. exp: exp,
  32572. exp2: exp2,
  32573. expression: expression,
  32574. faceDirection: faceDirection,
  32575. faceForward: faceForward,
  32576. faceforward: faceforward,
  32577. float: float,
  32578. floatBitsToInt: floatBitsToInt,
  32579. floatBitsToUint: floatBitsToUint,
  32580. floor: floor,
  32581. fog: fog,
  32582. fract: fract,
  32583. frameGroup: frameGroup,
  32584. frameId: frameId,
  32585. frontFacing: frontFacing,
  32586. fwidth: fwidth,
  32587. gain: gain,
  32588. gapSize: gapSize,
  32589. getConstNodeType: getConstNodeType,
  32590. getCurrentStack: getCurrentStack,
  32591. getDirection: getDirection,
  32592. getDistanceAttenuation: getDistanceAttenuation,
  32593. getGeometryRoughness: getGeometryRoughness,
  32594. getNormalFromDepth: getNormalFromDepth,
  32595. getParallaxCorrectNormal: getParallaxCorrectNormal,
  32596. getRoughness: getRoughness,
  32597. getScreenPosition: getScreenPosition,
  32598. getShIrradianceAt: getShIrradianceAt,
  32599. getShadowMaterial: getShadowMaterial,
  32600. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  32601. getTextureIndex: getTextureIndex,
  32602. getViewPosition: getViewPosition,
  32603. globalId: globalId,
  32604. glsl: glsl,
  32605. glslFn: glslFn,
  32606. grayscale: grayscale,
  32607. greaterThan: greaterThan,
  32608. greaterThanEqual: greaterThanEqual,
  32609. hash: hash,
  32610. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  32611. highpModelViewMatrix: highpModelViewMatrix,
  32612. hue: hue,
  32613. increment: increment,
  32614. incrementBefore: incrementBefore,
  32615. inspector: inspector,
  32616. instance: instance,
  32617. instanceIndex: instanceIndex,
  32618. instancedArray: instancedArray,
  32619. instancedBufferAttribute: instancedBufferAttribute,
  32620. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  32621. instancedMesh: instancedMesh,
  32622. int: int,
  32623. intBitsToFloat: intBitsToFloat,
  32624. interleavedGradientNoise: interleavedGradientNoise,
  32625. inverse: inverse,
  32626. inverseSqrt: inverseSqrt,
  32627. inversesqrt: inversesqrt,
  32628. invocationLocalIndex: invocationLocalIndex,
  32629. invocationSubgroupIndex: invocationSubgroupIndex,
  32630. ior: ior,
  32631. iridescence: iridescence,
  32632. iridescenceIOR: iridescenceIOR,
  32633. iridescenceThickness: iridescenceThickness,
  32634. isolate: isolate,
  32635. ivec2: ivec2,
  32636. ivec3: ivec3,
  32637. ivec4: ivec4,
  32638. js: js,
  32639. label: label,
  32640. length: length,
  32641. lengthSq: lengthSq,
  32642. lessThan: lessThan,
  32643. lessThanEqual: lessThanEqual,
  32644. lightPosition: lightPosition,
  32645. lightProjectionUV: lightProjectionUV,
  32646. lightShadowMatrix: lightShadowMatrix,
  32647. lightTargetDirection: lightTargetDirection,
  32648. lightTargetPosition: lightTargetPosition,
  32649. lightViewPosition: lightViewPosition,
  32650. lightingContext: lightingContext,
  32651. lights: lights,
  32652. linearDepth: linearDepth,
  32653. linearToneMapping: linearToneMapping,
  32654. localId: localId,
  32655. log: log,
  32656. log2: log2,
  32657. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  32658. luminance: luminance,
  32659. mat2: mat2,
  32660. mat3: mat3,
  32661. mat4: mat4,
  32662. matcapUV: matcapUV,
  32663. materialAO: materialAO,
  32664. materialAlphaTest: materialAlphaTest,
  32665. materialAnisotropy: materialAnisotropy,
  32666. materialAnisotropyVector: materialAnisotropyVector,
  32667. materialAttenuationColor: materialAttenuationColor,
  32668. materialAttenuationDistance: materialAttenuationDistance,
  32669. materialClearcoat: materialClearcoat,
  32670. materialClearcoatNormal: materialClearcoatNormal,
  32671. materialClearcoatRoughness: materialClearcoatRoughness,
  32672. materialColor: materialColor,
  32673. materialDispersion: materialDispersion,
  32674. materialEmissive: materialEmissive,
  32675. materialEnvIntensity: materialEnvIntensity,
  32676. materialEnvRotation: materialEnvRotation,
  32677. materialIOR: materialIOR,
  32678. materialIridescence: materialIridescence,
  32679. materialIridescenceIOR: materialIridescenceIOR,
  32680. materialIridescenceThickness: materialIridescenceThickness,
  32681. materialLightMap: materialLightMap,
  32682. materialLineDashOffset: materialLineDashOffset,
  32683. materialLineDashSize: materialLineDashSize,
  32684. materialLineGapSize: materialLineGapSize,
  32685. materialLineScale: materialLineScale,
  32686. materialLineWidth: materialLineWidth,
  32687. materialMetalness: materialMetalness,
  32688. materialNormal: materialNormal,
  32689. materialOpacity: materialOpacity,
  32690. materialPointSize: materialPointSize,
  32691. materialReference: materialReference,
  32692. materialReflectivity: materialReflectivity,
  32693. materialRefractionRatio: materialRefractionRatio,
  32694. materialRotation: materialRotation,
  32695. materialRoughness: materialRoughness,
  32696. materialSheen: materialSheen,
  32697. materialSheenRoughness: materialSheenRoughness,
  32698. materialShininess: materialShininess,
  32699. materialSpecular: materialSpecular,
  32700. materialSpecularColor: materialSpecularColor,
  32701. materialSpecularIntensity: materialSpecularIntensity,
  32702. materialSpecularStrength: materialSpecularStrength,
  32703. materialThickness: materialThickness,
  32704. materialTransmission: materialTransmission,
  32705. max: max$1,
  32706. maxMipLevel: maxMipLevel,
  32707. mediumpModelViewMatrix: mediumpModelViewMatrix,
  32708. metalness: metalness,
  32709. min: min$1,
  32710. mix: mix,
  32711. mixElement: mixElement,
  32712. mod: mod,
  32713. modInt: modInt,
  32714. modelDirection: modelDirection,
  32715. modelNormalMatrix: modelNormalMatrix,
  32716. modelPosition: modelPosition,
  32717. modelRadius: modelRadius,
  32718. modelScale: modelScale,
  32719. modelViewMatrix: modelViewMatrix,
  32720. modelViewPosition: modelViewPosition,
  32721. modelViewProjection: modelViewProjection,
  32722. modelWorldMatrix: modelWorldMatrix,
  32723. modelWorldMatrixInverse: modelWorldMatrixInverse,
  32724. morphReference: morphReference,
  32725. mrt: mrt,
  32726. mul: mul,
  32727. mx_aastep: mx_aastep,
  32728. mx_add: mx_add,
  32729. mx_atan2: mx_atan2,
  32730. mx_cell_noise_float: mx_cell_noise_float,
  32731. mx_contrast: mx_contrast,
  32732. mx_divide: mx_divide,
  32733. mx_fractal_noise_float: mx_fractal_noise_float,
  32734. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  32735. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  32736. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  32737. mx_frame: mx_frame,
  32738. mx_heighttonormal: mx_heighttonormal,
  32739. mx_hsvtorgb: mx_hsvtorgb,
  32740. mx_ifequal: mx_ifequal,
  32741. mx_ifgreater: mx_ifgreater,
  32742. mx_ifgreatereq: mx_ifgreatereq,
  32743. mx_invert: mx_invert,
  32744. mx_modulo: mx_modulo,
  32745. mx_multiply: mx_multiply,
  32746. mx_noise_float: mx_noise_float,
  32747. mx_noise_vec3: mx_noise_vec3,
  32748. mx_noise_vec4: mx_noise_vec4,
  32749. mx_place2d: mx_place2d,
  32750. mx_power: mx_power,
  32751. mx_ramp4: mx_ramp4,
  32752. mx_ramplr: mx_ramplr,
  32753. mx_ramptb: mx_ramptb,
  32754. mx_rgbtohsv: mx_rgbtohsv,
  32755. mx_rotate2d: mx_rotate2d,
  32756. mx_rotate3d: mx_rotate3d,
  32757. mx_safepower: mx_safepower,
  32758. mx_separate: mx_separate,
  32759. mx_splitlr: mx_splitlr,
  32760. mx_splittb: mx_splittb,
  32761. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  32762. mx_subtract: mx_subtract,
  32763. mx_timer: mx_timer,
  32764. mx_transform_uv: mx_transform_uv,
  32765. mx_unifiednoise2d: mx_unifiednoise2d,
  32766. mx_unifiednoise3d: mx_unifiednoise3d,
  32767. mx_worley_noise_float: mx_worley_noise_float,
  32768. mx_worley_noise_vec2: mx_worley_noise_vec2,
  32769. mx_worley_noise_vec3: mx_worley_noise_vec3,
  32770. negate: negate,
  32771. neutralToneMapping: neutralToneMapping,
  32772. nodeArray: nodeArray,
  32773. nodeImmutable: nodeImmutable,
  32774. nodeObject: nodeObject,
  32775. nodeObjectIntent: nodeObjectIntent,
  32776. nodeObjects: nodeObjects,
  32777. nodeProxy: nodeProxy,
  32778. nodeProxyIntent: nodeProxyIntent,
  32779. normalFlat: normalFlat,
  32780. normalGeometry: normalGeometry,
  32781. normalLocal: normalLocal,
  32782. normalMap: normalMap,
  32783. normalView: normalView,
  32784. normalViewGeometry: normalViewGeometry,
  32785. normalWorld: normalWorld,
  32786. normalWorldGeometry: normalWorldGeometry,
  32787. normalize: normalize,
  32788. not: not,
  32789. notEqual: notEqual,
  32790. numWorkgroups: numWorkgroups,
  32791. objectDirection: objectDirection,
  32792. objectGroup: objectGroup,
  32793. objectPosition: objectPosition,
  32794. objectRadius: objectRadius,
  32795. objectScale: objectScale,
  32796. objectViewPosition: objectViewPosition,
  32797. objectWorldMatrix: objectWorldMatrix,
  32798. oneMinus: oneMinus,
  32799. or: or,
  32800. orthographicDepthToViewZ: orthographicDepthToViewZ,
  32801. oscSawtooth: oscSawtooth,
  32802. oscSine: oscSine,
  32803. oscSquare: oscSquare,
  32804. oscTriangle: oscTriangle,
  32805. output: output,
  32806. outputStruct: outputStruct,
  32807. overlay: overlay,
  32808. overloadingFn: overloadingFn,
  32809. parabola: parabola,
  32810. parallaxDirection: parallaxDirection,
  32811. parallaxUV: parallaxUV,
  32812. parameter: parameter,
  32813. pass: pass,
  32814. passTexture: passTexture,
  32815. pcurve: pcurve,
  32816. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  32817. pmremTexture: pmremTexture,
  32818. pointShadow: pointShadow,
  32819. pointUV: pointUV,
  32820. pointWidth: pointWidth,
  32821. positionGeometry: positionGeometry,
  32822. positionLocal: positionLocal,
  32823. positionPrevious: positionPrevious,
  32824. positionView: positionView,
  32825. positionViewDirection: positionViewDirection,
  32826. positionWorld: positionWorld,
  32827. positionWorldDirection: positionWorldDirection,
  32828. posterize: posterize,
  32829. pow: pow,
  32830. pow2: pow2,
  32831. pow3: pow3,
  32832. pow4: pow4,
  32833. premultiplyAlpha: premultiplyAlpha,
  32834. property: property,
  32835. quadBroadcast: quadBroadcast,
  32836. quadSwapDiagonal: quadSwapDiagonal,
  32837. quadSwapX: quadSwapX,
  32838. quadSwapY: quadSwapY,
  32839. radians: radians,
  32840. rand: rand,
  32841. range: range,
  32842. rangeFog: rangeFog,
  32843. rangeFogFactor: rangeFogFactor,
  32844. reciprocal: reciprocal,
  32845. reference: reference,
  32846. referenceBuffer: referenceBuffer,
  32847. reflect: reflect,
  32848. reflectVector: reflectVector,
  32849. reflectView: reflectView,
  32850. reflector: reflector,
  32851. refract: refract,
  32852. refractVector: refractVector,
  32853. refractView: refractView,
  32854. reinhardToneMapping: reinhardToneMapping,
  32855. remap: remap,
  32856. remapClamp: remapClamp,
  32857. renderGroup: renderGroup,
  32858. renderOutput: renderOutput,
  32859. rendererReference: rendererReference,
  32860. rotate: rotate,
  32861. rotateUV: rotateUV,
  32862. roughness: roughness,
  32863. round: round,
  32864. rtt: rtt,
  32865. sRGBTransferEOTF: sRGBTransferEOTF,
  32866. sRGBTransferOETF: sRGBTransferOETF,
  32867. sample: sample,
  32868. sampler: sampler,
  32869. samplerComparison: samplerComparison,
  32870. saturate: saturate,
  32871. saturation: saturation,
  32872. screen: screen,
  32873. screenCoordinate: screenCoordinate,
  32874. screenDPR: screenDPR,
  32875. screenSize: screenSize,
  32876. screenUV: screenUV,
  32877. scriptable: scriptable,
  32878. scriptableValue: scriptableValue,
  32879. select: select,
  32880. setCurrentStack: setCurrentStack,
  32881. setName: setName,
  32882. shaderStages: shaderStages,
  32883. shadow: shadow,
  32884. shadowPositionWorld: shadowPositionWorld,
  32885. shapeCircle: shapeCircle,
  32886. sharedUniformGroup: sharedUniformGroup,
  32887. sheen: sheen,
  32888. sheenRoughness: sheenRoughness,
  32889. shiftLeft: shiftLeft,
  32890. shiftRight: shiftRight,
  32891. shininess: shininess,
  32892. sign: sign,
  32893. sin: sin,
  32894. sinc: sinc,
  32895. skinning: skinning,
  32896. smoothstep: smoothstep,
  32897. smoothstepElement: smoothstepElement,
  32898. specularColor: specularColor,
  32899. specularF90: specularF90,
  32900. spherizeUV: spherizeUV,
  32901. split: split,
  32902. spritesheetUV: spritesheetUV,
  32903. sqrt: sqrt,
  32904. stack: stack,
  32905. step: step,
  32906. stepElement: stepElement,
  32907. storage: storage,
  32908. storageBarrier: storageBarrier,
  32909. storageObject: storageObject,
  32910. storageTexture: storageTexture,
  32911. string: string,
  32912. struct: struct,
  32913. sub: sub,
  32914. subBuild: subBuild,
  32915. subgroupAdd: subgroupAdd,
  32916. subgroupAll: subgroupAll,
  32917. subgroupAnd: subgroupAnd,
  32918. subgroupAny: subgroupAny,
  32919. subgroupBallot: subgroupBallot,
  32920. subgroupBroadcast: subgroupBroadcast,
  32921. subgroupBroadcastFirst: subgroupBroadcastFirst,
  32922. subgroupElect: subgroupElect,
  32923. subgroupExclusiveAdd: subgroupExclusiveAdd,
  32924. subgroupExclusiveMul: subgroupExclusiveMul,
  32925. subgroupInclusiveAdd: subgroupInclusiveAdd,
  32926. subgroupInclusiveMul: subgroupInclusiveMul,
  32927. subgroupIndex: subgroupIndex,
  32928. subgroupMax: subgroupMax,
  32929. subgroupMin: subgroupMin,
  32930. subgroupMul: subgroupMul,
  32931. subgroupOr: subgroupOr,
  32932. subgroupShuffle: subgroupShuffle,
  32933. subgroupShuffleDown: subgroupShuffleDown,
  32934. subgroupShuffleUp: subgroupShuffleUp,
  32935. subgroupShuffleXor: subgroupShuffleXor,
  32936. subgroupSize: subgroupSize,
  32937. subgroupXor: subgroupXor,
  32938. tan: tan,
  32939. tangentGeometry: tangentGeometry,
  32940. tangentLocal: tangentLocal,
  32941. tangentView: tangentView,
  32942. tangentWorld: tangentWorld,
  32943. texture: texture,
  32944. texture3D: texture3D,
  32945. textureBarrier: textureBarrier,
  32946. textureBicubic: textureBicubic,
  32947. textureBicubicLevel: textureBicubicLevel,
  32948. textureCubeUV: textureCubeUV,
  32949. textureLevel: textureLevel,
  32950. textureLoad: textureLoad,
  32951. textureSize: textureSize,
  32952. textureStore: textureStore,
  32953. thickness: thickness,
  32954. time: time,
  32955. toneMapping: toneMapping,
  32956. toneMappingExposure: toneMappingExposure,
  32957. toonOutlinePass: toonOutlinePass,
  32958. transformDirection: transformDirection,
  32959. transformNormal: transformNormal,
  32960. transformNormalToView: transformNormalToView,
  32961. transformedClearcoatNormalView: transformedClearcoatNormalView,
  32962. transformedNormalView: transformedNormalView,
  32963. transformedNormalWorld: transformedNormalWorld,
  32964. transmission: transmission,
  32965. transpose: transpose,
  32966. triNoise3D: triNoise3D,
  32967. triplanarTexture: triplanarTexture,
  32968. triplanarTextures: triplanarTextures,
  32969. trunc: trunc,
  32970. uint: uint,
  32971. uintBitsToFloat: uintBitsToFloat,
  32972. uniform: uniform,
  32973. uniformArray: uniformArray,
  32974. uniformCubeTexture: uniformCubeTexture,
  32975. uniformFlow: uniformFlow,
  32976. uniformGroup: uniformGroup,
  32977. uniformTexture: uniformTexture,
  32978. unpremultiplyAlpha: unpremultiplyAlpha,
  32979. userData: userData,
  32980. uv: uv$1,
  32981. uvec2: uvec2,
  32982. uvec3: uvec3,
  32983. uvec4: uvec4,
  32984. varying: varying,
  32985. varyingProperty: varyingProperty,
  32986. vec2: vec2,
  32987. vec3: vec3,
  32988. vec4: vec4,
  32989. vectorComponents: vectorComponents,
  32990. velocity: velocity,
  32991. vertexColor: vertexColor,
  32992. vertexIndex: vertexIndex,
  32993. vertexStage: vertexStage,
  32994. vibrance: vibrance,
  32995. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  32996. viewZToOrthographicDepth: viewZToOrthographicDepth,
  32997. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  32998. viewport: viewport,
  32999. viewportCoordinate: viewportCoordinate,
  33000. viewportDepthTexture: viewportDepthTexture,
  33001. viewportLinearDepth: viewportLinearDepth,
  33002. viewportMipTexture: viewportMipTexture,
  33003. viewportResolution: viewportResolution,
  33004. viewportSafeUV: viewportSafeUV,
  33005. viewportSharedTexture: viewportSharedTexture,
  33006. viewportSize: viewportSize,
  33007. viewportTexture: viewportTexture,
  33008. viewportUV: viewportUV,
  33009. wgsl: wgsl,
  33010. wgslFn: wgslFn,
  33011. workgroupArray: workgroupArray,
  33012. workgroupBarrier: workgroupBarrier,
  33013. workgroupId: workgroupId,
  33014. workingToColorSpace: workingToColorSpace,
  33015. xor: xor
  33016. });
  33017. const _clearColor = /*@__PURE__*/ new Color4();
  33018. /**
  33019. * This renderer module manages the background.
  33020. *
  33021. * @private
  33022. * @augments DataMap
  33023. */
  33024. class Background extends DataMap {
  33025. /**
  33026. * Constructs a new background management component.
  33027. *
  33028. * @param {Renderer} renderer - The renderer.
  33029. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  33030. */
  33031. constructor( renderer, nodes ) {
  33032. super();
  33033. /**
  33034. * The renderer.
  33035. *
  33036. * @type {Renderer}
  33037. */
  33038. this.renderer = renderer;
  33039. /**
  33040. * Renderer component for managing nodes related logic.
  33041. *
  33042. * @type {Nodes}
  33043. */
  33044. this.nodes = nodes;
  33045. }
  33046. /**
  33047. * Updates the background for the given scene. Depending on how `Scene.background`
  33048. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  33049. * or add a mesh to the render list for rendering the background as a textured plane
  33050. * or skybox.
  33051. *
  33052. * @param {Scene} scene - The scene.
  33053. * @param {RenderList} renderList - The current render list.
  33054. * @param {RenderContext} renderContext - The current render context.
  33055. */
  33056. update( scene, renderList, renderContext ) {
  33057. const renderer = this.renderer;
  33058. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  33059. let forceClear = false;
  33060. if ( background === null ) {
  33061. // no background settings, use clear color configuration from the renderer
  33062. renderer._clearColor.getRGB( _clearColor );
  33063. _clearColor.a = renderer._clearColor.a;
  33064. } else if ( background.isColor === true ) {
  33065. // background is an opaque color
  33066. background.getRGB( _clearColor );
  33067. _clearColor.a = 1;
  33068. forceClear = true;
  33069. } else if ( background.isNode === true ) {
  33070. const sceneData = this.get( scene );
  33071. const backgroundNode = background;
  33072. _clearColor.copy( renderer._clearColor );
  33073. let backgroundMesh = sceneData.backgroundMesh;
  33074. if ( backgroundMesh === undefined ) {
  33075. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  33076. // @TODO: Add Texture2D support using node context
  33077. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  33078. getTextureLevel: () => backgroundBlurriness
  33079. } );
  33080. let viewProj = modelViewProjection;
  33081. viewProj = viewProj.setZ( viewProj.w );
  33082. const nodeMaterial = new NodeMaterial();
  33083. nodeMaterial.name = 'Background.material';
  33084. nodeMaterial.side = BackSide;
  33085. nodeMaterial.depthTest = false;
  33086. nodeMaterial.depthWrite = false;
  33087. nodeMaterial.allowOverride = false;
  33088. nodeMaterial.fog = false;
  33089. nodeMaterial.lights = false;
  33090. nodeMaterial.vertexNode = viewProj;
  33091. nodeMaterial.colorNode = backgroundMeshNode;
  33092. sceneData.backgroundMeshNode = backgroundMeshNode;
  33093. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  33094. backgroundMesh.frustumCulled = false;
  33095. backgroundMesh.name = 'Background.mesh';
  33096. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  33097. this.matrixWorld.copyPosition( camera.matrixWorld );
  33098. };
  33099. function onBackgroundDispose() {
  33100. background.removeEventListener( 'dispose', onBackgroundDispose );
  33101. backgroundMesh.material.dispose();
  33102. backgroundMesh.geometry.dispose();
  33103. }
  33104. background.addEventListener( 'dispose', onBackgroundDispose );
  33105. }
  33106. const backgroundCacheKey = backgroundNode.getCacheKey();
  33107. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  33108. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  33109. sceneData.backgroundMeshNode.needsUpdate = true;
  33110. backgroundMesh.material.needsUpdate = true;
  33111. sceneData.backgroundCacheKey = backgroundCacheKey;
  33112. }
  33113. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  33114. } else {
  33115. error( 'Renderer: Unsupported background configuration.', background );
  33116. }
  33117. //
  33118. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  33119. if ( environmentBlendMode === 'additive' ) {
  33120. _clearColor.set( 0, 0, 0, 1 );
  33121. } else if ( environmentBlendMode === 'alpha-blend' ) {
  33122. _clearColor.set( 0, 0, 0, 0 );
  33123. }
  33124. //
  33125. if ( renderer.autoClear === true || forceClear === true ) {
  33126. const clearColorValue = renderContext.clearColorValue;
  33127. clearColorValue.r = _clearColor.r;
  33128. clearColorValue.g = _clearColor.g;
  33129. clearColorValue.b = _clearColor.b;
  33130. clearColorValue.a = _clearColor.a;
  33131. // premultiply alpha
  33132. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  33133. clearColorValue.r *= clearColorValue.a;
  33134. clearColorValue.g *= clearColorValue.a;
  33135. clearColorValue.b *= clearColorValue.a;
  33136. }
  33137. //
  33138. renderContext.depthClearValue = renderer._clearDepth;
  33139. renderContext.stencilClearValue = renderer._clearStencil;
  33140. renderContext.clearColor = renderer.autoClearColor === true;
  33141. renderContext.clearDepth = renderer.autoClearDepth === true;
  33142. renderContext.clearStencil = renderer.autoClearStencil === true;
  33143. } else {
  33144. renderContext.clearColor = false;
  33145. renderContext.clearDepth = false;
  33146. renderContext.clearStencil = false;
  33147. }
  33148. }
  33149. }
  33150. let _id$7 = 0;
  33151. /**
  33152. * A bind group represents a collection of bindings and thus a collection
  33153. * or resources. Bind groups are assigned to pipelines to provide them
  33154. * with the required resources (like uniform buffers or textures).
  33155. *
  33156. * @private
  33157. */
  33158. class BindGroup {
  33159. /**
  33160. * Constructs a new bind group.
  33161. *
  33162. * @param {string} name - The bind group's name.
  33163. * @param {Array<Binding>} bindings - An array of bindings.
  33164. * @param {number} index - The group index.
  33165. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  33166. */
  33167. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  33168. /**
  33169. * The bind group's name.
  33170. *
  33171. * @type {string}
  33172. */
  33173. this.name = name;
  33174. /**
  33175. * An array of bindings.
  33176. *
  33177. * @type {Array<Binding>}
  33178. */
  33179. this.bindings = bindings;
  33180. /**
  33181. * The group index.
  33182. *
  33183. * @type {number}
  33184. */
  33185. this.index = index;
  33186. /**
  33187. * An array of reference bindings.
  33188. *
  33189. * @type {Array<Binding>}
  33190. */
  33191. this.bindingsReference = bindingsReference;
  33192. /**
  33193. * The group's ID.
  33194. *
  33195. * @type {number}
  33196. */
  33197. this.id = _id$7 ++;
  33198. }
  33199. }
  33200. /**
  33201. * This module represents the state of a node builder after it was
  33202. * used to build the nodes for a render object. The state holds the
  33203. * results of the build for further processing in the renderer.
  33204. *
  33205. * Render objects with identical cache keys share the same node builder state.
  33206. *
  33207. * @private
  33208. */
  33209. class NodeBuilderState {
  33210. /**
  33211. * Constructs a new node builder state.
  33212. *
  33213. * @param {string} vertexShader - The native vertex shader code.
  33214. * @param {string} fragmentShader - The native fragment shader code.
  33215. * @param {string} computeShader - The native compute shader code.
  33216. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  33217. * @param {Array<BindGroup>} bindings - An array of bind groups.
  33218. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  33219. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  33220. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  33221. * @param {NodeMaterialObserver} observer - A node material observer.
  33222. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  33223. */
  33224. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  33225. /**
  33226. * The native vertex shader code.
  33227. *
  33228. * @type {string}
  33229. */
  33230. this.vertexShader = vertexShader;
  33231. /**
  33232. * The native fragment shader code.
  33233. *
  33234. * @type {string}
  33235. */
  33236. this.fragmentShader = fragmentShader;
  33237. /**
  33238. * The native compute shader code.
  33239. *
  33240. * @type {string}
  33241. */
  33242. this.computeShader = computeShader;
  33243. /**
  33244. * An array with transform attribute objects.
  33245. * Only relevant when using compute shaders with WebGL 2.
  33246. *
  33247. * @type {Array<Object>}
  33248. */
  33249. this.transforms = transforms;
  33250. /**
  33251. * An array of node attributes representing
  33252. * the attributes of the shaders.
  33253. *
  33254. * @type {Array<NodeAttribute>}
  33255. */
  33256. this.nodeAttributes = nodeAttributes;
  33257. /**
  33258. * An array of bind groups representing the uniform or storage
  33259. * buffers, texture or samplers of the shader.
  33260. *
  33261. * @type {Array<BindGroup>}
  33262. */
  33263. this.bindings = bindings;
  33264. /**
  33265. * An array of nodes that implement their `update()` method.
  33266. *
  33267. * @type {Array<Node>}
  33268. */
  33269. this.updateNodes = updateNodes;
  33270. /**
  33271. * An array of nodes that implement their `updateBefore()` method.
  33272. *
  33273. * @type {Array<Node>}
  33274. */
  33275. this.updateBeforeNodes = updateBeforeNodes;
  33276. /**
  33277. * An array of nodes that implement their `updateAfter()` method.
  33278. *
  33279. * @type {Array<Node>}
  33280. */
  33281. this.updateAfterNodes = updateAfterNodes;
  33282. /**
  33283. * A node material observer.
  33284. *
  33285. * @type {NodeMaterialObserver}
  33286. */
  33287. this.observer = observer;
  33288. /**
  33289. * How often this state is used by render objects.
  33290. *
  33291. * @type {number}
  33292. */
  33293. this.usedTimes = 0;
  33294. }
  33295. /**
  33296. * This method is used to create a array of bind groups based
  33297. * on the existing bind groups of this state. Shared groups are
  33298. * not cloned.
  33299. *
  33300. * @return {Array<BindGroup>} A array of bind groups.
  33301. */
  33302. createBindings() {
  33303. const bindings = [];
  33304. for ( const instanceGroup of this.bindings ) {
  33305. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  33306. if ( shared !== true ) {
  33307. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup.bindingsReference );
  33308. bindings.push( bindingsGroup );
  33309. for ( const instanceBinding of instanceGroup.bindings ) {
  33310. bindingsGroup.bindings.push( instanceBinding.clone() );
  33311. }
  33312. } else {
  33313. bindings.push( instanceGroup );
  33314. }
  33315. }
  33316. return bindings;
  33317. }
  33318. }
  33319. /**
  33320. * {@link NodeBuilder} is going to create instances of this class during the build process
  33321. * of nodes. They represent the final shader attributes that are going to be generated
  33322. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  33323. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  33324. */
  33325. class NodeAttribute {
  33326. /**
  33327. * Constructs a new node attribute.
  33328. *
  33329. * @param {string} name - The name of the attribute.
  33330. * @param {string} type - The type of the attribute.
  33331. * @param {?Node} node - An optional reference to the node.
  33332. */
  33333. constructor( name, type, node = null ) {
  33334. /**
  33335. * This flag can be used for type testing.
  33336. *
  33337. * @type {boolean}
  33338. * @readonly
  33339. * @default true
  33340. */
  33341. this.isNodeAttribute = true;
  33342. /**
  33343. * The name of the attribute.
  33344. *
  33345. * @type {string}
  33346. */
  33347. this.name = name;
  33348. /**
  33349. * The type of the attribute.
  33350. *
  33351. * @type {string}
  33352. */
  33353. this.type = type;
  33354. /**
  33355. * An optional reference to the node.
  33356. *
  33357. * @type {?Node}
  33358. * @default null
  33359. */
  33360. this.node = node;
  33361. }
  33362. }
  33363. /**
  33364. * {@link NodeBuilder} is going to create instances of this class during the build process
  33365. * of nodes. They represent the final shader uniforms that are going to be generated
  33366. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  33367. * for this purpose.
  33368. */
  33369. class NodeUniform {
  33370. /**
  33371. * Constructs a new node uniform.
  33372. *
  33373. * @param {string} name - The name of the uniform.
  33374. * @param {string} type - The type of the uniform.
  33375. * @param {UniformNode} node - An reference to the node.
  33376. */
  33377. constructor( name, type, node ) {
  33378. /**
  33379. * This flag can be used for type testing.
  33380. *
  33381. * @type {boolean}
  33382. * @readonly
  33383. * @default true
  33384. */
  33385. this.isNodeUniform = true;
  33386. /**
  33387. * The name of the uniform.
  33388. *
  33389. * @type {string}
  33390. */
  33391. this.name = name;
  33392. /**
  33393. * The type of the uniform.
  33394. *
  33395. * @type {string}
  33396. */
  33397. this.type = type;
  33398. /**
  33399. * An reference to the node.
  33400. *
  33401. * @type {UniformNode}
  33402. */
  33403. this.node = node;
  33404. }
  33405. /**
  33406. * The value of the uniform node.
  33407. *
  33408. * @type {any}
  33409. */
  33410. get value() {
  33411. return this.node.value;
  33412. }
  33413. set value( val ) {
  33414. this.node.value = val;
  33415. }
  33416. /**
  33417. * The id of the uniform node.
  33418. *
  33419. * @type {number}
  33420. */
  33421. get id() {
  33422. return this.node.id;
  33423. }
  33424. /**
  33425. * The uniform node's group.
  33426. *
  33427. * @type {UniformGroupNode}
  33428. */
  33429. get groupNode() {
  33430. return this.node.groupNode;
  33431. }
  33432. }
  33433. /**
  33434. * {@link NodeBuilder} is going to create instances of this class during the build process
  33435. * of nodes. They represent the final shader variables that are going to be generated
  33436. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  33437. * this purpose.
  33438. */
  33439. class NodeVar {
  33440. /**
  33441. * Constructs a new node variable.
  33442. *
  33443. * @param {string} name - The name of the variable.
  33444. * @param {string} type - The type of the variable.
  33445. * @param {boolean} [readOnly=false] - The read-only flag.
  33446. * @param {?number} [count=null] - The size.
  33447. */
  33448. constructor( name, type, readOnly = false, count = null ) {
  33449. /**
  33450. * This flag can be used for type testing.
  33451. *
  33452. * @type {boolean}
  33453. * @readonly
  33454. * @default true
  33455. */
  33456. this.isNodeVar = true;
  33457. /**
  33458. * The name of the variable.
  33459. *
  33460. * @type {string}
  33461. */
  33462. this.name = name;
  33463. /**
  33464. * The type of the variable.
  33465. *
  33466. * @type {string}
  33467. */
  33468. this.type = type;
  33469. /**
  33470. * The read-only flag.
  33471. *
  33472. * @type {boolean}
  33473. */
  33474. this.readOnly = readOnly;
  33475. /**
  33476. * The size.
  33477. *
  33478. * @type {?number}
  33479. */
  33480. this.count = count;
  33481. }
  33482. }
  33483. /**
  33484. * {@link NodeBuilder} is going to create instances of this class during the build process
  33485. * of nodes. They represent the final shader varyings that are going to be generated
  33486. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  33487. * this purpose.
  33488. *
  33489. * @augments NodeVar
  33490. */
  33491. class NodeVarying extends NodeVar {
  33492. /**
  33493. * Constructs a new node varying.
  33494. *
  33495. * @param {string} name - The name of the varying.
  33496. * @param {string} type - The type of the varying.
  33497. * @param {?string} interpolationType - The interpolation type of the varying.
  33498. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  33499. */
  33500. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  33501. super( name, type );
  33502. /**
  33503. * Whether this varying requires interpolation or not. This property can be used
  33504. * to check if the varying can be optimized for a variable.
  33505. *
  33506. * @type {boolean}
  33507. * @default false
  33508. */
  33509. this.needsInterpolation = false;
  33510. /**
  33511. * This flag can be used for type testing.
  33512. *
  33513. * @type {boolean}
  33514. * @readonly
  33515. * @default true
  33516. */
  33517. this.isNodeVarying = true;
  33518. /**
  33519. * The interpolation type of the varying data.
  33520. *
  33521. * @type {?string}
  33522. * @default null
  33523. */
  33524. this.interpolationType = interpolationType;
  33525. /**
  33526. * The interpolation sampling type of varying data.
  33527. *
  33528. * @type {?string}
  33529. * @default null
  33530. */
  33531. this.interpolationSampling = interpolationSampling;
  33532. }
  33533. }
  33534. /**
  33535. * {@link NodeBuilder} is going to create instances of this class during the build process
  33536. * of nodes. They represent user-defined, native shader code portions that are going to be
  33537. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  33538. * for this purpose.
  33539. */
  33540. class NodeCode {
  33541. /**
  33542. * Constructs a new code node.
  33543. *
  33544. * @param {string} name - The name of the code.
  33545. * @param {string} type - The node type.
  33546. * @param {string} [code=''] - The native shader code.
  33547. */
  33548. constructor( name, type, code = '' ) {
  33549. /**
  33550. * The name of the code.
  33551. *
  33552. * @type {string}
  33553. */
  33554. this.name = name;
  33555. /**
  33556. * The node type.
  33557. *
  33558. * @type {string}
  33559. */
  33560. this.type = type;
  33561. /**
  33562. * The native shader code.
  33563. *
  33564. * @type {string}
  33565. * @default ''
  33566. */
  33567. this.code = code;
  33568. Object.defineProperty( this, 'isNodeCode', { value: true } );
  33569. }
  33570. }
  33571. let _id$6 = 0;
  33572. /**
  33573. * This utility class is used in {@link NodeBuilder} as an internal
  33574. * cache data structure for node data.
  33575. */
  33576. class NodeCache {
  33577. /**
  33578. * Constructs a new node cache.
  33579. *
  33580. * @param {?NodeCache} parent - A reference to a parent cache.
  33581. */
  33582. constructor( parent = null ) {
  33583. /**
  33584. * The id of the cache.
  33585. *
  33586. * @type {number}
  33587. * @readonly
  33588. */
  33589. this.id = _id$6 ++;
  33590. /**
  33591. * A weak map for managing node data.
  33592. *
  33593. * @type {WeakMap<Node, Object>}
  33594. */
  33595. this.nodesData = new WeakMap();
  33596. /**
  33597. * Reference to a parent node cache.
  33598. *
  33599. * @type {?NodeCache}
  33600. * @default null
  33601. */
  33602. this.parent = parent;
  33603. }
  33604. /**
  33605. * Returns the data for the given node.
  33606. *
  33607. * @param {Node} node - The node.
  33608. * @return {?Object} The data for the node.
  33609. */
  33610. getData( node ) {
  33611. let data = this.nodesData.get( node );
  33612. if ( data === undefined && this.parent !== null ) {
  33613. data = this.parent.getData( node );
  33614. }
  33615. return data;
  33616. }
  33617. /**
  33618. * Sets the data for a given node.
  33619. *
  33620. * @param {Node} node - The node.
  33621. * @param {Object} data - The data that should be cached.
  33622. */
  33623. setData( node, data ) {
  33624. this.nodesData.set( node, data );
  33625. }
  33626. }
  33627. class StructType {
  33628. constructor( name, members ) {
  33629. this.name = name;
  33630. this.members = members;
  33631. this.output = false;
  33632. }
  33633. }
  33634. /**
  33635. * Abstract base class for uniforms.
  33636. *
  33637. * @abstract
  33638. * @private
  33639. */
  33640. class Uniform {
  33641. /**
  33642. * Constructs a new uniform.
  33643. *
  33644. * @param {string} name - The uniform's name.
  33645. * @param {any} value - The uniform's value.
  33646. */
  33647. constructor( name, value ) {
  33648. /**
  33649. * The uniform's name.
  33650. *
  33651. * @type {string}
  33652. */
  33653. this.name = name;
  33654. /**
  33655. * The uniform's value.
  33656. *
  33657. * @type {any}
  33658. */
  33659. this.value = value;
  33660. /**
  33661. * Used to build the uniform buffer according to the STD140 layout.
  33662. * Derived uniforms will set this property to a data type specific
  33663. * value.
  33664. *
  33665. * @type {number}
  33666. */
  33667. this.boundary = 0;
  33668. /**
  33669. * The item size. Derived uniforms will set this property to a data
  33670. * type specific value.
  33671. *
  33672. * @type {number}
  33673. */
  33674. this.itemSize = 0;
  33675. /**
  33676. * This property is set by {@link UniformsGroup} and marks
  33677. * the start position in the uniform buffer.
  33678. *
  33679. * @type {number}
  33680. */
  33681. this.offset = 0;
  33682. }
  33683. /**
  33684. * Sets the uniform's value.
  33685. *
  33686. * @param {any} value - The value to set.
  33687. */
  33688. setValue( value ) {
  33689. this.value = value;
  33690. }
  33691. /**
  33692. * Returns the uniform's value.
  33693. *
  33694. * @return {any} The value.
  33695. */
  33696. getValue() {
  33697. return this.value;
  33698. }
  33699. }
  33700. /**
  33701. * Represents a Number uniform.
  33702. *
  33703. * @private
  33704. * @augments Uniform
  33705. */
  33706. class NumberUniform extends Uniform {
  33707. /**
  33708. * Constructs a new Number uniform.
  33709. *
  33710. * @param {string} name - The uniform's name.
  33711. * @param {number} value - The uniform's value.
  33712. */
  33713. constructor( name, value = 0 ) {
  33714. super( name, value );
  33715. /**
  33716. * This flag can be used for type testing.
  33717. *
  33718. * @type {boolean}
  33719. * @readonly
  33720. * @default true
  33721. */
  33722. this.isNumberUniform = true;
  33723. this.boundary = 4;
  33724. this.itemSize = 1;
  33725. }
  33726. }
  33727. /**
  33728. * Represents a Vector2 uniform.
  33729. *
  33730. * @private
  33731. * @augments Uniform
  33732. */
  33733. class Vector2Uniform extends Uniform {
  33734. /**
  33735. * Constructs a new Number uniform.
  33736. *
  33737. * @param {string} name - The uniform's name.
  33738. * @param {Vector2} value - The uniform's value.
  33739. */
  33740. constructor( name, value = new Vector2() ) {
  33741. super( name, value );
  33742. /**
  33743. * This flag can be used for type testing.
  33744. *
  33745. * @type {boolean}
  33746. * @readonly
  33747. * @default true
  33748. */
  33749. this.isVector2Uniform = true;
  33750. this.boundary = 8;
  33751. this.itemSize = 2;
  33752. }
  33753. }
  33754. /**
  33755. * Represents a Vector3 uniform.
  33756. *
  33757. * @private
  33758. * @augments Uniform
  33759. */
  33760. class Vector3Uniform extends Uniform {
  33761. /**
  33762. * Constructs a new Number uniform.
  33763. *
  33764. * @param {string} name - The uniform's name.
  33765. * @param {Vector3} value - The uniform's value.
  33766. */
  33767. constructor( name, value = new Vector3() ) {
  33768. super( name, value );
  33769. /**
  33770. * This flag can be used for type testing.
  33771. *
  33772. * @type {boolean}
  33773. * @readonly
  33774. * @default true
  33775. */
  33776. this.isVector3Uniform = true;
  33777. this.boundary = 16;
  33778. this.itemSize = 3;
  33779. }
  33780. }
  33781. /**
  33782. * Represents a Vector4 uniform.
  33783. *
  33784. * @private
  33785. * @augments Uniform
  33786. */
  33787. class Vector4Uniform extends Uniform {
  33788. /**
  33789. * Constructs a new Number uniform.
  33790. *
  33791. * @param {string} name - The uniform's name.
  33792. * @param {Vector4} value - The uniform's value.
  33793. */
  33794. constructor( name, value = new Vector4() ) {
  33795. super( name, value );
  33796. /**
  33797. * This flag can be used for type testing.
  33798. *
  33799. * @type {boolean}
  33800. * @readonly
  33801. * @default true
  33802. */
  33803. this.isVector4Uniform = true;
  33804. this.boundary = 16;
  33805. this.itemSize = 4;
  33806. }
  33807. }
  33808. /**
  33809. * Represents a Color uniform.
  33810. *
  33811. * @private
  33812. * @augments Uniform
  33813. */
  33814. class ColorUniform extends Uniform {
  33815. /**
  33816. * Constructs a new Number uniform.
  33817. *
  33818. * @param {string} name - The uniform's name.
  33819. * @param {Color} value - The uniform's value.
  33820. */
  33821. constructor( name, value = new Color() ) {
  33822. super( name, value );
  33823. /**
  33824. * This flag can be used for type testing.
  33825. *
  33826. * @type {boolean}
  33827. * @readonly
  33828. * @default true
  33829. */
  33830. this.isColorUniform = true;
  33831. this.boundary = 16;
  33832. this.itemSize = 3;
  33833. }
  33834. }
  33835. /**
  33836. * Represents a Matrix2 uniform.
  33837. *
  33838. * @private
  33839. * @augments Uniform
  33840. */
  33841. class Matrix2Uniform extends Uniform {
  33842. /**
  33843. * Constructs a new Number uniform.
  33844. *
  33845. * @param {string} name - The uniform's name.
  33846. * @param {Matrix2} value - The uniform's value.
  33847. */
  33848. constructor( name, value = new Matrix2() ) {
  33849. super( name, value );
  33850. /**
  33851. * This flag can be used for type testing.
  33852. *
  33853. * @type {boolean}
  33854. * @readonly
  33855. * @default true
  33856. */
  33857. this.isMatrix2Uniform = true;
  33858. this.boundary = 8;
  33859. this.itemSize = 4;
  33860. }
  33861. }
  33862. /**
  33863. * Represents a Matrix3 uniform.
  33864. *
  33865. * @private
  33866. * @augments Uniform
  33867. */
  33868. class Matrix3Uniform extends Uniform {
  33869. /**
  33870. * Constructs a new Number uniform.
  33871. *
  33872. * @param {string} name - The uniform's name.
  33873. * @param {Matrix3} value - The uniform's value.
  33874. */
  33875. constructor( name, value = new Matrix3() ) {
  33876. super( name, value );
  33877. /**
  33878. * This flag can be used for type testing.
  33879. *
  33880. * @type {boolean}
  33881. * @readonly
  33882. * @default true
  33883. */
  33884. this.isMatrix3Uniform = true;
  33885. this.boundary = 48;
  33886. this.itemSize = 12;
  33887. }
  33888. }
  33889. /**
  33890. * Represents a Matrix4 uniform.
  33891. *
  33892. * @private
  33893. * @augments Uniform
  33894. */
  33895. class Matrix4Uniform extends Uniform {
  33896. /**
  33897. * Constructs a new Number uniform.
  33898. *
  33899. * @param {string} name - The uniform's name.
  33900. * @param {Matrix4} value - The uniform's value.
  33901. */
  33902. constructor( name, value = new Matrix4() ) {
  33903. super( name, value );
  33904. /**
  33905. * This flag can be used for type testing.
  33906. *
  33907. * @type {boolean}
  33908. * @readonly
  33909. * @default true
  33910. */
  33911. this.isMatrix4Uniform = true;
  33912. this.boundary = 64;
  33913. this.itemSize = 16;
  33914. }
  33915. }
  33916. /**
  33917. * A special form of Number uniform binding type.
  33918. * It's value is managed by a node object.
  33919. *
  33920. * @private
  33921. * @augments NumberUniform
  33922. */
  33923. class NumberNodeUniform extends NumberUniform {
  33924. /**
  33925. * Constructs a new node-based Number uniform.
  33926. *
  33927. * @param {NodeUniform} nodeUniform - The node uniform.
  33928. */
  33929. constructor( nodeUniform ) {
  33930. super( nodeUniform.name, nodeUniform.value );
  33931. /**
  33932. * The node uniform.
  33933. *
  33934. * @type {NodeUniform}
  33935. */
  33936. this.nodeUniform = nodeUniform;
  33937. }
  33938. /**
  33939. * Overwritten to return the value of the node uniform.
  33940. *
  33941. * @return {number} The value.
  33942. */
  33943. getValue() {
  33944. return this.nodeUniform.value;
  33945. }
  33946. /**
  33947. * Returns the node uniform data type.
  33948. *
  33949. * @return {string} The data type.
  33950. */
  33951. getType() {
  33952. return this.nodeUniform.type;
  33953. }
  33954. }
  33955. /**
  33956. * A special form of Vector2 uniform binding type.
  33957. * It's value is managed by a node object.
  33958. *
  33959. * @private
  33960. * @augments Vector2Uniform
  33961. */
  33962. class Vector2NodeUniform extends Vector2Uniform {
  33963. /**
  33964. * Constructs a new node-based Vector2 uniform.
  33965. *
  33966. * @param {NodeUniform} nodeUniform - The node uniform.
  33967. */
  33968. constructor( nodeUniform ) {
  33969. super( nodeUniform.name, nodeUniform.value );
  33970. /**
  33971. * The node uniform.
  33972. *
  33973. * @type {NodeUniform}
  33974. */
  33975. this.nodeUniform = nodeUniform;
  33976. }
  33977. /**
  33978. * Overwritten to return the value of the node uniform.
  33979. *
  33980. * @return {Vector2} The value.
  33981. */
  33982. getValue() {
  33983. return this.nodeUniform.value;
  33984. }
  33985. /**
  33986. * Returns the node uniform data type.
  33987. *
  33988. * @return {string} The data type.
  33989. */
  33990. getType() {
  33991. return this.nodeUniform.type;
  33992. }
  33993. }
  33994. /**
  33995. * A special form of Vector3 uniform binding type.
  33996. * It's value is managed by a node object.
  33997. *
  33998. * @private
  33999. * @augments Vector3Uniform
  34000. */
  34001. class Vector3NodeUniform extends Vector3Uniform {
  34002. /**
  34003. * Constructs a new node-based Vector3 uniform.
  34004. *
  34005. * @param {NodeUniform} nodeUniform - The node uniform.
  34006. */
  34007. constructor( nodeUniform ) {
  34008. super( nodeUniform.name, nodeUniform.value );
  34009. /**
  34010. * The node uniform.
  34011. *
  34012. * @type {NodeUniform}
  34013. */
  34014. this.nodeUniform = nodeUniform;
  34015. }
  34016. /**
  34017. * Overwritten to return the value of the node uniform.
  34018. *
  34019. * @return {Vector3} The value.
  34020. */
  34021. getValue() {
  34022. return this.nodeUniform.value;
  34023. }
  34024. /**
  34025. * Returns the node uniform data type.
  34026. *
  34027. * @return {string} The data type.
  34028. */
  34029. getType() {
  34030. return this.nodeUniform.type;
  34031. }
  34032. }
  34033. /**
  34034. * A special form of Vector4 uniform binding type.
  34035. * It's value is managed by a node object.
  34036. *
  34037. * @private
  34038. * @augments Vector4Uniform
  34039. */
  34040. class Vector4NodeUniform extends Vector4Uniform {
  34041. /**
  34042. * Constructs a new node-based Vector4 uniform.
  34043. *
  34044. * @param {NodeUniform} nodeUniform - The node uniform.
  34045. */
  34046. constructor( nodeUniform ) {
  34047. super( nodeUniform.name, nodeUniform.value );
  34048. /**
  34049. * The node uniform.
  34050. *
  34051. * @type {NodeUniform}
  34052. */
  34053. this.nodeUniform = nodeUniform;
  34054. }
  34055. /**
  34056. * Overwritten to return the value of the node uniform.
  34057. *
  34058. * @return {Vector4} The value.
  34059. */
  34060. getValue() {
  34061. return this.nodeUniform.value;
  34062. }
  34063. /**
  34064. * Returns the node uniform data type.
  34065. *
  34066. * @return {string} The data type.
  34067. */
  34068. getType() {
  34069. return this.nodeUniform.type;
  34070. }
  34071. }
  34072. /**
  34073. * A special form of Color uniform binding type.
  34074. * It's value is managed by a node object.
  34075. *
  34076. * @private
  34077. * @augments ColorUniform
  34078. */
  34079. class ColorNodeUniform extends ColorUniform {
  34080. /**
  34081. * Constructs a new node-based Color uniform.
  34082. *
  34083. * @param {NodeUniform} nodeUniform - The node uniform.
  34084. */
  34085. constructor( nodeUniform ) {
  34086. super( nodeUniform.name, nodeUniform.value );
  34087. /**
  34088. * The node uniform.
  34089. *
  34090. * @type {NodeUniform}
  34091. */
  34092. this.nodeUniform = nodeUniform;
  34093. }
  34094. /**
  34095. * Overwritten to return the value of the node uniform.
  34096. *
  34097. * @return {Color} The value.
  34098. */
  34099. getValue() {
  34100. return this.nodeUniform.value;
  34101. }
  34102. /**
  34103. * Returns the node uniform data type.
  34104. *
  34105. * @return {string} The data type.
  34106. */
  34107. getType() {
  34108. return this.nodeUniform.type;
  34109. }
  34110. }
  34111. /**
  34112. * A special form of Matrix2 uniform binding type.
  34113. * It's value is managed by a node object.
  34114. *
  34115. * @private
  34116. * @augments Matrix2Uniform
  34117. */
  34118. class Matrix2NodeUniform extends Matrix2Uniform {
  34119. /**
  34120. * Constructs a new node-based Matrix2 uniform.
  34121. *
  34122. * @param {NodeUniform} nodeUniform - The node uniform.
  34123. */
  34124. constructor( nodeUniform ) {
  34125. super( nodeUniform.name, nodeUniform.value );
  34126. /**
  34127. * The node uniform.
  34128. *
  34129. * @type {NodeUniform}
  34130. */
  34131. this.nodeUniform = nodeUniform;
  34132. }
  34133. /**
  34134. * Overwritten to return the value of the node uniform.
  34135. *
  34136. * @return {Matrix2} The value.
  34137. */
  34138. getValue() {
  34139. return this.nodeUniform.value;
  34140. }
  34141. /**
  34142. * Returns the node uniform data type.
  34143. *
  34144. * @return {string} The data type.
  34145. */
  34146. getType() {
  34147. return this.nodeUniform.type;
  34148. }
  34149. }
  34150. /**
  34151. * A special form of Matrix3 uniform binding type.
  34152. * It's value is managed by a node object.
  34153. *
  34154. * @private
  34155. * @augments Matrix3Uniform
  34156. */
  34157. class Matrix3NodeUniform extends Matrix3Uniform {
  34158. /**
  34159. * Constructs a new node-based Matrix3 uniform.
  34160. *
  34161. * @param {NodeUniform} nodeUniform - The node uniform.
  34162. */
  34163. constructor( nodeUniform ) {
  34164. super( nodeUniform.name, nodeUniform.value );
  34165. /**
  34166. * The node uniform.
  34167. *
  34168. * @type {NodeUniform}
  34169. */
  34170. this.nodeUniform = nodeUniform;
  34171. }
  34172. /**
  34173. * Overwritten to return the value of the node uniform.
  34174. *
  34175. * @return {Matrix3} The value.
  34176. */
  34177. getValue() {
  34178. return this.nodeUniform.value;
  34179. }
  34180. /**
  34181. * Returns the node uniform data type.
  34182. *
  34183. * @return {string} The data type.
  34184. */
  34185. getType() {
  34186. return this.nodeUniform.type;
  34187. }
  34188. }
  34189. /**
  34190. * A special form of Matrix4 uniform binding type.
  34191. * It's value is managed by a node object.
  34192. *
  34193. * @private
  34194. * @augments Matrix4Uniform
  34195. */
  34196. class Matrix4NodeUniform extends Matrix4Uniform {
  34197. /**
  34198. * Constructs a new node-based Matrix4 uniform.
  34199. *
  34200. * @param {NodeUniform} nodeUniform - The node uniform.
  34201. */
  34202. constructor( nodeUniform ) {
  34203. super( nodeUniform.name, nodeUniform.value );
  34204. /**
  34205. * The node uniform.
  34206. *
  34207. * @type {NodeUniform}
  34208. */
  34209. this.nodeUniform = nodeUniform;
  34210. }
  34211. /**
  34212. * Overwritten to return the value of the node uniform.
  34213. *
  34214. * @return {Matrix4} The value.
  34215. */
  34216. getValue() {
  34217. return this.nodeUniform.value;
  34218. }
  34219. /**
  34220. * Returns the node uniform data type.
  34221. *
  34222. * @return {string} The data type.
  34223. */
  34224. getType() {
  34225. return this.nodeUniform.type;
  34226. }
  34227. }
  34228. let _id$5 = 0;
  34229. const rendererCache = new WeakMap();
  34230. const typeFromArray = new Map( [
  34231. [ Int8Array, 'int' ],
  34232. [ Int16Array, 'int' ],
  34233. [ Int32Array, 'int' ],
  34234. [ Uint8Array, 'uint' ],
  34235. [ Uint16Array, 'uint' ],
  34236. [ Uint32Array, 'uint' ],
  34237. [ Float32Array, 'float' ]
  34238. ] );
  34239. const toFloat = ( value ) => {
  34240. if ( /e/g.test( value ) ) {
  34241. return String( value ).replace( /\+/g, '' );
  34242. } else {
  34243. value = Number( value );
  34244. return value + ( value % 1 ? '' : '.0' );
  34245. }
  34246. };
  34247. /**
  34248. * Base class for builders which generate a shader program based
  34249. * on a 3D object and its node material definition.
  34250. */
  34251. class NodeBuilder {
  34252. /**
  34253. * Constructs a new node builder.
  34254. *
  34255. * @param {Object3D} object - The 3D object.
  34256. * @param {Renderer} renderer - The current renderer.
  34257. * @param {NodeParser} parser - A reference to a node parser.
  34258. */
  34259. constructor( object, renderer, parser ) {
  34260. /**
  34261. * The 3D object.
  34262. *
  34263. * @type {Object3D}
  34264. */
  34265. this.object = object;
  34266. /**
  34267. * The material of the 3D object.
  34268. *
  34269. * @type {?Material}
  34270. */
  34271. this.material = ( object && object.material ) || null;
  34272. /**
  34273. * The geometry of the 3D object.
  34274. *
  34275. * @type {?BufferGeometry}
  34276. */
  34277. this.geometry = ( object && object.geometry ) || null;
  34278. /**
  34279. * The current renderer.
  34280. *
  34281. * @type {Renderer}
  34282. */
  34283. this.renderer = renderer;
  34284. /**
  34285. * A reference to a node parser.
  34286. *
  34287. * @type {NodeParser}
  34288. */
  34289. this.parser = parser;
  34290. /**
  34291. * The scene the 3D object belongs to.
  34292. *
  34293. * @type {?Scene}
  34294. * @default null
  34295. */
  34296. this.scene = null;
  34297. /**
  34298. * The camera the 3D object is rendered with.
  34299. *
  34300. * @type {?Camera}
  34301. * @default null
  34302. */
  34303. this.camera = null;
  34304. /**
  34305. * A list of all nodes the builder is processing
  34306. * for this 3D object.
  34307. *
  34308. * @type {Array<Node>}
  34309. */
  34310. this.nodes = [];
  34311. /**
  34312. * A list of all sequential nodes.
  34313. *
  34314. * @type {Array<Node>}
  34315. */
  34316. this.sequentialNodes = [];
  34317. /**
  34318. * A list of all nodes which {@link Node#update} method should be executed.
  34319. *
  34320. * @type {Array<Node>}
  34321. */
  34322. this.updateNodes = [];
  34323. /**
  34324. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  34325. *
  34326. * @type {Array<Node>}
  34327. */
  34328. this.updateBeforeNodes = [];
  34329. /**
  34330. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  34331. *
  34332. * @type {Array<Node>}
  34333. */
  34334. this.updateAfterNodes = [];
  34335. /**
  34336. * A dictionary that assigns each node to a unique hash.
  34337. *
  34338. * @type {Object<number,Node>}
  34339. */
  34340. this.hashNodes = {};
  34341. /**
  34342. * A reference to a node material observer.
  34343. *
  34344. * @type {?NodeMaterialObserver}
  34345. * @default null
  34346. */
  34347. this.observer = null;
  34348. /**
  34349. * A reference to the current lights node.
  34350. *
  34351. * @type {?LightsNode}
  34352. * @default null
  34353. */
  34354. this.lightsNode = null;
  34355. /**
  34356. * A reference to the current environment node.
  34357. *
  34358. * @type {?Node}
  34359. * @default null
  34360. */
  34361. this.environmentNode = null;
  34362. /**
  34363. * A reference to the current fog node.
  34364. *
  34365. * @type {?Node}
  34366. * @default null
  34367. */
  34368. this.fogNode = null;
  34369. /**
  34370. * The current clipping context.
  34371. *
  34372. * @type {?ClippingContext}
  34373. */
  34374. this.clippingContext = null;
  34375. /**
  34376. * The generated vertex shader.
  34377. *
  34378. * @type {?string}
  34379. */
  34380. this.vertexShader = null;
  34381. /**
  34382. * The generated fragment shader.
  34383. *
  34384. * @type {?string}
  34385. */
  34386. this.fragmentShader = null;
  34387. /**
  34388. * The generated compute shader.
  34389. *
  34390. * @type {?string}
  34391. */
  34392. this.computeShader = null;
  34393. /**
  34394. * Nodes used in the primary flow of code generation.
  34395. *
  34396. * @type {Object<string,Array<Node>>}
  34397. */
  34398. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  34399. /**
  34400. * Nodes code from `.flowNodes`.
  34401. *
  34402. * @type {Object<string,string>}
  34403. */
  34404. this.flowCode = { vertex: '', fragment: '', compute: '' };
  34405. /**
  34406. * This dictionary holds the node uniforms of the builder.
  34407. * The uniforms are maintained in an array for each shader stage.
  34408. *
  34409. * @type {Object}
  34410. */
  34411. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  34412. /**
  34413. * This dictionary holds the output structs of the builder.
  34414. * The structs are maintained in an array for each shader stage.
  34415. *
  34416. * @type {Object}
  34417. */
  34418. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  34419. /**
  34420. * This dictionary holds the types of the builder.
  34421. *
  34422. * @type {Object}
  34423. */
  34424. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  34425. /**
  34426. * This dictionary holds the bindings for each shader stage.
  34427. *
  34428. * @type {Object}
  34429. */
  34430. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  34431. /**
  34432. * This dictionary maintains the binding indices per bind group.
  34433. *
  34434. * @type {Object}
  34435. */
  34436. this.bindingsIndexes = {};
  34437. /**
  34438. * Reference to the array of bind groups.
  34439. *
  34440. * @type {?Array<BindGroup>}
  34441. */
  34442. this.bindGroups = null;
  34443. /**
  34444. * This array holds the node attributes of this builder
  34445. * created via {@link AttributeNode}.
  34446. *
  34447. * @type {Array<NodeAttribute>}
  34448. */
  34449. this.attributes = [];
  34450. /**
  34451. * This array holds the node attributes of this builder
  34452. * created via {@link BufferAttributeNode}.
  34453. *
  34454. * @type {Array<NodeAttribute>}
  34455. */
  34456. this.bufferAttributes = [];
  34457. /**
  34458. * This array holds the node varyings of this builder.
  34459. *
  34460. * @type {Array<NodeVarying>}
  34461. */
  34462. this.varyings = [];
  34463. /**
  34464. * This dictionary holds the (native) node codes of this builder.
  34465. * The codes are maintained in an array for each shader stage.
  34466. *
  34467. * @type {Object<string,Array<NodeCode>>}
  34468. */
  34469. this.codes = {};
  34470. /**
  34471. * This dictionary holds the node variables of this builder.
  34472. * The variables are maintained in an array for each shader stage.
  34473. * This dictionary is also used to count the number of variables
  34474. * according to their type (const, vars).
  34475. *
  34476. * @type {Object<string,Array<NodeVar>|number>}
  34477. */
  34478. this.vars = {};
  34479. /**
  34480. * This dictionary holds the declarations for each shader stage.
  34481. *
  34482. * @type {Object}
  34483. */
  34484. this.declarations = {};
  34485. /**
  34486. * Current code flow.
  34487. * All code generated in this stack will be stored in `.flow`.
  34488. *
  34489. * @type {{code: string}}
  34490. */
  34491. this.flow = { code: '' };
  34492. /**
  34493. * A chain of nodes.
  34494. * Used to check recursive calls in node-graph.
  34495. *
  34496. * @type {Array<Node>}
  34497. */
  34498. this.chaining = [];
  34499. /**
  34500. * The current stack.
  34501. * This reflects the current process in the code block hierarchy,
  34502. * it is useful to know if the current process is inside a conditional for example.
  34503. *
  34504. * @type {StackNode}
  34505. */
  34506. this.stack = stack();
  34507. /**
  34508. * List of stack nodes.
  34509. * The current stack hierarchy is stored in an array.
  34510. *
  34511. * @type {Array<StackNode>}
  34512. */
  34513. this.stacks = [];
  34514. /**
  34515. * A tab value. Used for shader string generation.
  34516. *
  34517. * @type {string}
  34518. * @default '\t'
  34519. */
  34520. this.tab = '\t';
  34521. /**
  34522. * Reference to the current function node.
  34523. *
  34524. * @type {?FunctionNode}
  34525. * @default null
  34526. */
  34527. this.currentFunctionNode = null;
  34528. /**
  34529. * The builder's context.
  34530. *
  34531. * @type {Object}
  34532. */
  34533. this.context = {
  34534. material: this.material
  34535. };
  34536. /**
  34537. * The builder's cache.
  34538. *
  34539. * @type {NodeCache}
  34540. */
  34541. this.cache = new NodeCache();
  34542. /**
  34543. * Since the {@link NodeBuilder#cache} might be temporarily
  34544. * overwritten by other caches, this member retains the reference
  34545. * to the builder's own cache.
  34546. *
  34547. * @type {NodeCache}
  34548. * @default this.cache
  34549. */
  34550. this.globalCache = this.cache;
  34551. this.flowsData = new WeakMap();
  34552. /**
  34553. * The current shader stage.
  34554. *
  34555. * @type {?('vertex'|'fragment'|'compute'|'any')}
  34556. */
  34557. this.shaderStage = null;
  34558. /**
  34559. * The current build stage.
  34560. *
  34561. * @type {?('setup'|'analyze'|'generate')}
  34562. */
  34563. this.buildStage = null;
  34564. /**
  34565. * The sub-build layers.
  34566. *
  34567. * @type {Array<SubBuildNode>}
  34568. * @default []
  34569. */
  34570. this.subBuildLayers = [];
  34571. /**
  34572. * The active stack nodes.
  34573. *
  34574. * @type {Array<StackNode>}
  34575. */
  34576. this.activeStacks = [];
  34577. /**
  34578. * The current sub-build TSL function(Fn).
  34579. *
  34580. * @type {?string}
  34581. * @default null
  34582. */
  34583. this.subBuildFn = null;
  34584. /**
  34585. * The current TSL function(Fn) call node.
  34586. *
  34587. * @type {?Node}
  34588. * @default null
  34589. */
  34590. this.fnCall = null;
  34591. Object.defineProperty( this, 'id', { value: _id$5 ++ } );
  34592. }
  34593. /**
  34594. * Whether the material is opaque or not.
  34595. *
  34596. * @return {boolean} Whether the material is opaque or not.
  34597. */
  34598. isOpaque() {
  34599. const material = this.material;
  34600. return material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false;
  34601. }
  34602. /**
  34603. * Returns the bind groups of the current renderer.
  34604. *
  34605. * @return {ChainMap} The cache.
  34606. */
  34607. getBindGroupsCache() {
  34608. let bindGroupsCache = rendererCache.get( this.renderer );
  34609. if ( bindGroupsCache === undefined ) {
  34610. bindGroupsCache = new ChainMap();
  34611. rendererCache.set( this.renderer, bindGroupsCache );
  34612. }
  34613. return bindGroupsCache;
  34614. }
  34615. /**
  34616. * Factory method for creating an instance of {@link RenderTarget} with the given
  34617. * dimensions and options.
  34618. *
  34619. * @param {number} width - The width of the render target.
  34620. * @param {number} height - The height of the render target.
  34621. * @param {Object} options - The options of the render target.
  34622. * @return {RenderTarget} The render target.
  34623. */
  34624. createRenderTarget( width, height, options ) {
  34625. return new RenderTarget( width, height, options );
  34626. }
  34627. /**
  34628. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  34629. * dimensions and options.
  34630. *
  34631. * @param {number} size - The size of the cube render target.
  34632. * @param {Object} options - The options of the cube render target.
  34633. * @return {CubeRenderTarget} The cube render target.
  34634. */
  34635. createCubeRenderTarget( size, options ) {
  34636. return new CubeRenderTarget( size, options );
  34637. }
  34638. /**
  34639. * Whether the given node is included in the internal array of nodes or not.
  34640. *
  34641. * @param {Node} node - The node to test.
  34642. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  34643. */
  34644. includes( node ) {
  34645. return this.nodes.includes( node );
  34646. }
  34647. /**
  34648. * Returns the output struct name which is required by
  34649. * {@link OutputStructNode}.
  34650. *
  34651. * @abstract
  34652. * @return {string} The name of the output struct.
  34653. */
  34654. getOutputStructName() {}
  34655. /**
  34656. * Returns a bind group for the given group name and binding.
  34657. *
  34658. * @private
  34659. * @param {string} groupName - The group name.
  34660. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  34661. * @return {BindGroup} The bind group
  34662. */
  34663. _getBindGroup( groupName, bindings ) {
  34664. const bindGroupsCache = this.getBindGroupsCache();
  34665. //
  34666. const bindingsArray = [];
  34667. let sharedGroup = true;
  34668. for ( const binding of bindings ) {
  34669. bindingsArray.push( binding );
  34670. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  34671. }
  34672. //
  34673. let bindGroup;
  34674. if ( sharedGroup ) {
  34675. bindGroup = bindGroupsCache.get( bindingsArray );
  34676. if ( bindGroup === undefined ) {
  34677. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  34678. bindGroupsCache.set( bindingsArray, bindGroup );
  34679. }
  34680. } else {
  34681. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  34682. }
  34683. return bindGroup;
  34684. }
  34685. /**
  34686. * Returns an array of node uniform groups for the given group name and shader stage.
  34687. *
  34688. * @param {string} groupName - The group name.
  34689. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34690. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  34691. */
  34692. getBindGroupArray( groupName, shaderStage ) {
  34693. const bindings = this.bindings[ shaderStage ];
  34694. let bindGroup = bindings[ groupName ];
  34695. if ( bindGroup === undefined ) {
  34696. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  34697. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  34698. }
  34699. bindings[ groupName ] = bindGroup = [];
  34700. }
  34701. return bindGroup;
  34702. }
  34703. /**
  34704. * Returns a list bindings of all shader stages separated by groups.
  34705. *
  34706. * @return {Array<BindGroup>} The list of bindings.
  34707. */
  34708. getBindings() {
  34709. let bindingsGroups = this.bindGroups;
  34710. if ( bindingsGroups === null ) {
  34711. const groups = {};
  34712. const bindings = this.bindings;
  34713. for ( const shaderStage of shaderStages ) {
  34714. for ( const groupName in bindings[ shaderStage ] ) {
  34715. const uniforms = bindings[ shaderStage ][ groupName ];
  34716. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  34717. groupUniforms.push( ...uniforms );
  34718. }
  34719. }
  34720. bindingsGroups = [];
  34721. for ( const groupName in groups ) {
  34722. const group = groups[ groupName ];
  34723. const bindingsGroup = this._getBindGroup( groupName, group );
  34724. bindingsGroups.push( bindingsGroup );
  34725. }
  34726. this.bindGroups = bindingsGroups;
  34727. }
  34728. return bindingsGroups;
  34729. }
  34730. /**
  34731. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  34732. */
  34733. sortBindingGroups() {
  34734. const bindingsGroups = this.getBindings();
  34735. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  34736. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  34737. const bindingGroup = bindingsGroups[ i ];
  34738. this.bindingsIndexes[ bindingGroup.name ].group = i;
  34739. bindingGroup.index = i;
  34740. }
  34741. }
  34742. /**
  34743. * The builder maintains each node in a hash-based dictionary.
  34744. * This method sets the given node (value) with the given hash (key) into this dictionary.
  34745. *
  34746. * @param {Node} node - The node to add.
  34747. * @param {number} hash - The hash of the node.
  34748. */
  34749. setHashNode( node, hash ) {
  34750. this.hashNodes[ hash ] = node;
  34751. }
  34752. /**
  34753. * Adds a node to this builder.
  34754. *
  34755. * @param {Node} node - The node to add.
  34756. */
  34757. addNode( node ) {
  34758. if ( this.nodes.includes( node ) === false ) {
  34759. this.nodes.push( node );
  34760. this.setHashNode( node, node.getHash( this ) );
  34761. }
  34762. }
  34763. /**
  34764. * It is used to add Nodes that will be used as FRAME and RENDER events,
  34765. * and need to follow a certain sequence in the calls to work correctly.
  34766. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  34767. *
  34768. * @param {Node} node - The node to add.
  34769. */
  34770. addSequentialNode( node ) {
  34771. if ( this.sequentialNodes.includes( node ) === false ) {
  34772. this.sequentialNodes.push( node );
  34773. }
  34774. }
  34775. /**
  34776. * Checks the update types of nodes
  34777. */
  34778. buildUpdateNodes() {
  34779. for ( const node of this.nodes ) {
  34780. const updateType = node.getUpdateType();
  34781. if ( updateType !== NodeUpdateType.NONE ) {
  34782. this.updateNodes.push( node );
  34783. }
  34784. }
  34785. for ( const node of this.sequentialNodes ) {
  34786. const updateBeforeType = node.getUpdateBeforeType();
  34787. const updateAfterType = node.getUpdateAfterType();
  34788. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  34789. this.updateBeforeNodes.push( node );
  34790. }
  34791. if ( updateAfterType !== NodeUpdateType.NONE ) {
  34792. this.updateAfterNodes.push( node );
  34793. }
  34794. }
  34795. }
  34796. /**
  34797. * A reference the current node which is the
  34798. * last node in the chain of nodes.
  34799. *
  34800. * @type {Node}
  34801. */
  34802. get currentNode() {
  34803. return this.chaining[ this.chaining.length - 1 ];
  34804. }
  34805. /**
  34806. * Whether the given texture is filtered or not.
  34807. *
  34808. * @param {Texture} texture - The texture to check.
  34809. * @return {boolean} Whether the given texture is filtered or not.
  34810. */
  34811. isFilteredTexture( texture ) {
  34812. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  34813. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  34814. }
  34815. /**
  34816. * Adds the given node to the internal node chain.
  34817. * This is used to check recursive calls in node-graph.
  34818. *
  34819. * @param {Node} node - The node to add.
  34820. */
  34821. addChain( node ) {
  34822. /*
  34823. if ( this.chaining.indexOf( node ) !== - 1 ) {
  34824. warn( 'Recursive node: ', node );
  34825. }
  34826. */
  34827. this.chaining.push( node );
  34828. }
  34829. /**
  34830. * Removes the given node from the internal node chain.
  34831. *
  34832. * @param {Node} node - The node to remove.
  34833. */
  34834. removeChain( node ) {
  34835. const lastChain = this.chaining.pop();
  34836. if ( lastChain !== node ) {
  34837. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  34838. }
  34839. }
  34840. /**
  34841. * Returns the native shader method name for a given generic name. E.g.
  34842. * the method name `textureDimensions` matches the WGSL name but must be
  34843. * resolved to `textureSize` in GLSL.
  34844. *
  34845. * @abstract
  34846. * @param {string} method - The method name to resolve.
  34847. * @return {string} The resolved method name.
  34848. */
  34849. getMethod( method ) {
  34850. return method;
  34851. }
  34852. /**
  34853. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  34854. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  34855. *
  34856. * @abstract
  34857. * @param {string} condSnippet - The condition determining which expression gets resolved.
  34858. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  34859. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  34860. * @return {string} The resolved method name.
  34861. */
  34862. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  34863. return null;
  34864. }
  34865. /**
  34866. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  34867. *
  34868. * @param {number} hash - The hash of the node.
  34869. * @return {Node} The found node.
  34870. */
  34871. getNodeFromHash( hash ) {
  34872. return this.hashNodes[ hash ];
  34873. }
  34874. /**
  34875. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  34876. *
  34877. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  34878. * @param {Node} node - The node to add.
  34879. * @return {Node} The node.
  34880. */
  34881. addFlow( shaderStage, node ) {
  34882. this.flowNodes[ shaderStage ].push( node );
  34883. return node;
  34884. }
  34885. /**
  34886. * Sets builder's context.
  34887. *
  34888. * @param {Object} context - The context to set.
  34889. */
  34890. setContext( context ) {
  34891. this.context = context;
  34892. }
  34893. /**
  34894. * Returns the builder's current context.
  34895. *
  34896. * @return {Object} The builder's current context.
  34897. */
  34898. getContext() {
  34899. return this.context;
  34900. }
  34901. /**
  34902. * Adds context data to the builder's current context.
  34903. *
  34904. * @param {Object} context - The context to add.
  34905. * @return {Object} The previous context.
  34906. */
  34907. addContext( context ) {
  34908. const previousContext = this.getContext();
  34909. this.setContext( { ...this.context, ...context } );
  34910. return previousContext;
  34911. }
  34912. /**
  34913. * Gets a context used in shader construction that can be shared across different materials.
  34914. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  34915. *
  34916. * @return {Object} The builder's current context without material.
  34917. */
  34918. getSharedContext() {
  34919. ({ ...this.context });
  34920. return this.context;
  34921. }
  34922. /**
  34923. * Sets builder's cache.
  34924. *
  34925. * @param {NodeCache} cache - The cache to set.
  34926. */
  34927. setCache( cache ) {
  34928. this.cache = cache;
  34929. }
  34930. /**
  34931. * Returns the builder's current cache.
  34932. *
  34933. * @return {NodeCache} The builder's current cache.
  34934. */
  34935. getCache() {
  34936. return this.cache;
  34937. }
  34938. /**
  34939. * Returns a cache for the given node.
  34940. *
  34941. * @param {Node} node - The node.
  34942. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  34943. * @return {NodeCache} The cache.
  34944. */
  34945. getCacheFromNode( node, parent = true ) {
  34946. const data = this.getDataFromNode( node );
  34947. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  34948. return data.cache;
  34949. }
  34950. /**
  34951. * Whether the requested feature is available or not.
  34952. *
  34953. * @abstract
  34954. * @param {string} name - The requested feature.
  34955. * @return {boolean} Whether the requested feature is supported or not.
  34956. */
  34957. isAvailable( /*name*/ ) {
  34958. return false;
  34959. }
  34960. /**
  34961. * Returns the vertexIndex input variable as a native shader string.
  34962. *
  34963. * @abstract
  34964. * @return {string} The instanceIndex shader string.
  34965. */
  34966. getVertexIndex() {
  34967. warn( 'Abstract function.' );
  34968. }
  34969. /**
  34970. * Contextually returns either the vertex stage instance index builtin
  34971. * or the linearized index of an compute invocation within a grid of workgroups.
  34972. *
  34973. * @abstract
  34974. * @return {string} The instanceIndex shader string.
  34975. */
  34976. getInstanceIndex() {
  34977. warn( 'Abstract function.' );
  34978. }
  34979. /**
  34980. * Returns the drawIndex input variable as a native shader string.
  34981. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  34982. *
  34983. * @abstract
  34984. * @return {?string} The drawIndex shader string.
  34985. */
  34986. getDrawIndex() {
  34987. warn( 'Abstract function.' );
  34988. }
  34989. /**
  34990. * Returns the frontFacing input variable as a native shader string.
  34991. *
  34992. * @abstract
  34993. * @return {string} The frontFacing shader string.
  34994. */
  34995. getFrontFacing() {
  34996. warn( 'Abstract function.' );
  34997. }
  34998. /**
  34999. * Returns the fragCoord input variable as a native shader string.
  35000. *
  35001. * @abstract
  35002. * @return {string} The fragCoord shader string.
  35003. */
  35004. getFragCoord() {
  35005. warn( 'Abstract function.' );
  35006. }
  35007. /**
  35008. * Whether to flip texture data along its vertical axis or not. WebGL needs
  35009. * this method evaluate to `true`, WebGPU to `false`.
  35010. *
  35011. * @abstract
  35012. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  35013. */
  35014. isFlipY() {
  35015. return false;
  35016. }
  35017. /**
  35018. * Calling this method increases the usage count for the given node by one.
  35019. *
  35020. * @param {Node} node - The node to increase the usage count for.
  35021. * @return {number} The updated usage count.
  35022. */
  35023. increaseUsage( node ) {
  35024. const nodeData = this.getDataFromNode( node );
  35025. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  35026. return nodeData.usageCount;
  35027. }
  35028. /**
  35029. * Generates a texture sample shader string for the given texture data.
  35030. *
  35031. * @abstract
  35032. * @param {Texture} texture - The texture.
  35033. * @param {string} textureProperty - The texture property name.
  35034. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  35035. * @return {string} The generated shader string.
  35036. */
  35037. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  35038. warn( 'Abstract function.' );
  35039. }
  35040. /**
  35041. * Generates a texture LOD shader string for the given texture data.
  35042. *
  35043. * @abstract
  35044. * @param {Texture} texture - The texture.
  35045. * @param {string} textureProperty - The texture property name.
  35046. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  35047. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  35048. * @param {string} levelSnippet - Snippet defining the mip level.
  35049. * @return {string} The generated shader string.
  35050. */
  35051. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  35052. warn( 'Abstract function.' );
  35053. }
  35054. /**
  35055. * Generates the array declaration string.
  35056. *
  35057. * @param {string} type - The type.
  35058. * @param {?number} [count] - The count.
  35059. * @return {string} The generated value as a shader string.
  35060. */
  35061. generateArrayDeclaration( type, count ) {
  35062. return this.getType( type ) + '[ ' + count + ' ]';
  35063. }
  35064. /**
  35065. * Generates the array shader string for the given type and value.
  35066. *
  35067. * @param {string} type - The type.
  35068. * @param {?number} [count] - The count.
  35069. * @param {?Array<Node>} [values=null] - The default values.
  35070. * @return {string} The generated value as a shader string.
  35071. */
  35072. generateArray( type, count, values = null ) {
  35073. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  35074. for ( let i = 0; i < count; i ++ ) {
  35075. const value = values ? values[ i ] : null;
  35076. if ( value !== null ) {
  35077. snippet += value.build( this, type );
  35078. } else {
  35079. snippet += this.generateConst( type );
  35080. }
  35081. if ( i < count - 1 ) snippet += ', ';
  35082. }
  35083. snippet += ' )';
  35084. return snippet;
  35085. }
  35086. /**
  35087. * Generates the struct shader string.
  35088. *
  35089. * @param {string} type - The type.
  35090. * @param {Array<Object>} [membersLayout] - The count.
  35091. * @param {?Array<Node>} [values=null] - The default values.
  35092. * @return {string} The generated value as a shader string.
  35093. */
  35094. generateStruct( type, membersLayout, values = null ) {
  35095. const snippets = [];
  35096. for ( const member of membersLayout ) {
  35097. const { name, type } = member;
  35098. if ( values && values[ name ] && values[ name ].isNode ) {
  35099. snippets.push( values[ name ].build( this, type ) );
  35100. } else {
  35101. snippets.push( this.generateConst( type ) );
  35102. }
  35103. }
  35104. return type + '( ' + snippets.join( ', ' ) + ' )';
  35105. }
  35106. /**
  35107. * Generates the shader string for the given type and value.
  35108. *
  35109. * @param {string} type - The type.
  35110. * @param {?any} [value=null] - The value.
  35111. * @return {string} The generated value as a shader string.
  35112. */
  35113. generateConst( type, value = null ) {
  35114. if ( value === null ) {
  35115. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  35116. else if ( type === 'bool' ) value = false;
  35117. else if ( type === 'color' ) value = new Color();
  35118. else if ( type === 'vec2' ) value = new Vector2();
  35119. else if ( type === 'vec3' ) value = new Vector3();
  35120. else if ( type === 'vec4' ) value = new Vector4();
  35121. }
  35122. if ( type === 'float' ) return toFloat( value );
  35123. if ( type === 'int' ) return `${ Math.round( value ) }`;
  35124. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  35125. if ( type === 'bool' ) return value ? 'true' : 'false';
  35126. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  35127. const typeLength = this.getTypeLength( type );
  35128. const componentType = this.getComponentType( type );
  35129. const generateConst = value => this.generateConst( componentType, value );
  35130. if ( typeLength === 2 ) {
  35131. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  35132. } else if ( typeLength === 3 ) {
  35133. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  35134. } else if ( typeLength === 4 && type !== 'mat2' ) {
  35135. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  35136. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  35137. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  35138. } else if ( typeLength > 4 ) {
  35139. return `${ this.getType( type ) }()`;
  35140. }
  35141. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  35142. }
  35143. /**
  35144. * It might be necessary to convert certain data types to different ones
  35145. * so this method can be used to hide the conversion.
  35146. *
  35147. * @param {string} type - The type.
  35148. * @return {string} The updated type.
  35149. */
  35150. getType( type ) {
  35151. if ( type === 'color' ) return 'vec3';
  35152. return type;
  35153. }
  35154. /**
  35155. * Whether the given attribute name is defined in the geometry or not.
  35156. *
  35157. * @param {string} name - The attribute name.
  35158. * @return {boolean} Whether the given attribute name is defined in the geometry.
  35159. */
  35160. hasGeometryAttribute( name ) {
  35161. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  35162. }
  35163. /**
  35164. * Returns a node attribute for the given name and type.
  35165. *
  35166. * @param {string} name - The attribute's name.
  35167. * @param {string} type - The attribute's type.
  35168. * @return {NodeAttribute} The node attribute.
  35169. */
  35170. getAttribute( name, type ) {
  35171. const attributes = this.attributes;
  35172. // find attribute
  35173. for ( const attribute of attributes ) {
  35174. if ( attribute.name === name ) {
  35175. return attribute;
  35176. }
  35177. }
  35178. // create a new if no exist
  35179. const attribute = new NodeAttribute( name, type );
  35180. this.registerDeclaration( attribute );
  35181. attributes.push( attribute );
  35182. return attribute;
  35183. }
  35184. /**
  35185. * Returns for the given node and shader stage the property name for the shader.
  35186. *
  35187. * @param {Node} node - The node.
  35188. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35189. * @return {string} The property name.
  35190. */
  35191. getPropertyName( node/*, shaderStage*/ ) {
  35192. return node.name;
  35193. }
  35194. /**
  35195. * Whether the given type is a vector type or not.
  35196. *
  35197. * @param {string} type - The type to check.
  35198. * @return {boolean} Whether the given type is a vector type or not.
  35199. */
  35200. isVector( type ) {
  35201. return /vec\d/.test( type );
  35202. }
  35203. /**
  35204. * Whether the given type is a matrix type or not.
  35205. *
  35206. * @param {string} type - The type to check.
  35207. * @return {boolean} Whether the given type is a matrix type or not.
  35208. */
  35209. isMatrix( type ) {
  35210. return /mat\d/.test( type );
  35211. }
  35212. /**
  35213. * Whether the given type is a reference type or not.
  35214. *
  35215. * @param {string} type - The type to check.
  35216. * @return {boolean} Whether the given type is a reference type or not.
  35217. */
  35218. isReference( type ) {
  35219. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  35220. }
  35221. /**
  35222. * Checks if the given texture requires a manual conversion to the working color space.
  35223. *
  35224. * @abstract
  35225. * @param {Texture} texture - The texture to check.
  35226. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  35227. */
  35228. needsToWorkingColorSpace( /*texture*/ ) {
  35229. return false;
  35230. }
  35231. /**
  35232. * Returns the component type of a given texture.
  35233. *
  35234. * @param {Texture} texture - The texture.
  35235. * @return {string} The component type.
  35236. */
  35237. getComponentTypeFromTexture( texture ) {
  35238. const type = texture.type;
  35239. if ( texture.isDataTexture ) {
  35240. if ( type === IntType ) return 'int';
  35241. if ( type === UnsignedIntType ) return 'uint';
  35242. }
  35243. return 'float';
  35244. }
  35245. /**
  35246. * Returns the element type for a given type.
  35247. *
  35248. * @param {string} type - The type.
  35249. * @return {string} The element type.
  35250. */
  35251. getElementType( type ) {
  35252. if ( type === 'mat2' ) return 'vec2';
  35253. if ( type === 'mat3' ) return 'vec3';
  35254. if ( type === 'mat4' ) return 'vec4';
  35255. return this.getComponentType( type );
  35256. }
  35257. /**
  35258. * Returns the component type for a given type.
  35259. *
  35260. * @param {string} type - The type.
  35261. * @return {string} The component type.
  35262. */
  35263. getComponentType( type ) {
  35264. type = this.getVectorType( type );
  35265. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  35266. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  35267. if ( componentType === null ) return null;
  35268. if ( componentType[ 1 ] === 'b' ) return 'bool';
  35269. if ( componentType[ 1 ] === 'i' ) return 'int';
  35270. if ( componentType[ 1 ] === 'u' ) return 'uint';
  35271. return 'float';
  35272. }
  35273. /**
  35274. * Returns the vector type for a given type.
  35275. *
  35276. * @param {string} type - The type.
  35277. * @return {string} The vector type.
  35278. */
  35279. getVectorType( type ) {
  35280. if ( type === 'color' ) return 'vec3';
  35281. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  35282. return type;
  35283. }
  35284. /**
  35285. * Returns the data type for the given the length and component type.
  35286. *
  35287. * @param {number} length - The length.
  35288. * @param {string} [componentType='float'] - The component type.
  35289. * @return {string} The type.
  35290. */
  35291. getTypeFromLength( length, componentType = 'float' ) {
  35292. if ( length === 1 ) return componentType;
  35293. let baseType = getTypeFromLength( length );
  35294. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  35295. // fix edge case for mat2x2 being same size as vec4
  35296. if ( /mat2/.test( componentType ) === true ) {
  35297. baseType = baseType.replace( 'vec', 'mat' );
  35298. }
  35299. return prefix + baseType;
  35300. }
  35301. /**
  35302. * Returns the type for a given typed array.
  35303. *
  35304. * @param {TypedArray} array - The typed array.
  35305. * @return {string} The type.
  35306. */
  35307. getTypeFromArray( array ) {
  35308. return typeFromArray.get( array.constructor );
  35309. }
  35310. /**
  35311. * Returns the type is an integer type.
  35312. *
  35313. * @param {string} type - The type.
  35314. * @return {boolean} Whether the type is an integer type or not.
  35315. */
  35316. isInteger( type ) {
  35317. return /int|uint|(i|u)vec/.test( type );
  35318. }
  35319. /**
  35320. * Returns the type for a given buffer attribute.
  35321. *
  35322. * @param {BufferAttribute} attribute - The buffer attribute.
  35323. * @return {string} The type.
  35324. */
  35325. getTypeFromAttribute( attribute ) {
  35326. let dataAttribute = attribute;
  35327. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  35328. const array = dataAttribute.array;
  35329. const itemSize = attribute.itemSize;
  35330. const normalized = attribute.normalized;
  35331. let arrayType;
  35332. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  35333. arrayType = this.getTypeFromArray( array );
  35334. }
  35335. return this.getTypeFromLength( itemSize, arrayType );
  35336. }
  35337. /**
  35338. * Returns the length for the given data type.
  35339. *
  35340. * @param {string} type - The data type.
  35341. * @return {number} The length.
  35342. */
  35343. getTypeLength( type ) {
  35344. const vecType = this.getVectorType( type );
  35345. const vecNum = /vec([2-4])/.exec( vecType );
  35346. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  35347. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  35348. if ( /mat2/.test( type ) === true ) return 4;
  35349. if ( /mat3/.test( type ) === true ) return 9;
  35350. if ( /mat4/.test( type ) === true ) return 16;
  35351. return 0;
  35352. }
  35353. /**
  35354. * Returns the vector type for a given matrix type.
  35355. *
  35356. * @param {string} type - The matrix type.
  35357. * @return {string} The vector type.
  35358. */
  35359. getVectorFromMatrix( type ) {
  35360. return type.replace( 'mat', 'vec' );
  35361. }
  35362. /**
  35363. * For a given type this method changes the component type to the
  35364. * given value. E.g. `vec4` should be changed to the new component type
  35365. * `uint` which results in `uvec4`.
  35366. *
  35367. * @param {string} type - The type.
  35368. * @param {string} newComponentType - The new component type.
  35369. * @return {string} The new type.
  35370. */
  35371. changeComponentType( type, newComponentType ) {
  35372. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  35373. }
  35374. /**
  35375. * Returns the integer type pendant for the given type.
  35376. *
  35377. * @param {string} type - The type.
  35378. * @return {string} The integer type.
  35379. */
  35380. getIntegerType( type ) {
  35381. const componentType = this.getComponentType( type );
  35382. if ( componentType === 'int' || componentType === 'uint' ) return type;
  35383. return this.changeComponentType( type, 'int' );
  35384. }
  35385. /**
  35386. * Adds an active stack to the internal stack.
  35387. *
  35388. * @param {StackNode} stack - The stack node to add.
  35389. */
  35390. setActiveStack( stack ) {
  35391. this.activeStacks.push( stack );
  35392. }
  35393. /**
  35394. * Removes the active stack from the internal stack.
  35395. *
  35396. * @param {StackNode} stack - The stack node to remove.
  35397. */
  35398. removeActiveStack( stack ) {
  35399. if ( this.activeStacks[ this.activeStacks.length - 1 ] === stack ) {
  35400. this.activeStacks.pop();
  35401. } else {
  35402. throw new Error( 'NodeBuilder: Invalid active stack removal.' );
  35403. }
  35404. }
  35405. /**
  35406. * Returns the active stack.
  35407. *
  35408. * @return {StackNode} The active stack.
  35409. */
  35410. getActiveStack() {
  35411. return this.activeStacks[ this.activeStacks.length - 1 ];
  35412. }
  35413. /**
  35414. * Returns the base stack.
  35415. *
  35416. * @return {StackNode} The base stack.
  35417. */
  35418. getBaseStack() {
  35419. return this.activeStacks[ 0 ];
  35420. }
  35421. /**
  35422. * Adds a stack node to the internal stack.
  35423. *
  35424. * @return {StackNode} The added stack node.
  35425. */
  35426. addStack() {
  35427. this.stack = stack( this.stack );
  35428. const previousStack = getCurrentStack();
  35429. this.stacks.push( previousStack );
  35430. setCurrentStack( this.stack );
  35431. return this.stack;
  35432. }
  35433. /**
  35434. * Removes the last stack node from the internal stack.
  35435. *
  35436. * @return {StackNode} The removed stack node.
  35437. */
  35438. removeStack() {
  35439. const lastStack = this.stack;
  35440. for ( const node of lastStack.nodes ) {
  35441. const nodeData = this.getDataFromNode( node );
  35442. nodeData.stack = lastStack;
  35443. }
  35444. this.stack = lastStack.parent;
  35445. setCurrentStack( this.stacks.pop() );
  35446. return lastStack;
  35447. }
  35448. /**
  35449. * The builder maintains (cached) data for each node during the building process. This method
  35450. * can be used to get these data for a specific shader stage and cache.
  35451. *
  35452. * @param {Node} node - The node to get the data for.
  35453. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35454. * @param {?NodeCache} cache - An optional cache.
  35455. * @return {Object} The node data.
  35456. */
  35457. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  35458. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  35459. let nodeData = cache.getData( node );
  35460. if ( nodeData === undefined ) {
  35461. nodeData = {};
  35462. cache.setData( node, nodeData );
  35463. }
  35464. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  35465. //
  35466. let data = nodeData[ shaderStage ];
  35467. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  35468. const subBuild = this.getClosestSubBuild( subBuilds );
  35469. if ( subBuild ) {
  35470. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  35471. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  35472. data.subBuilds = subBuilds;
  35473. }
  35474. return data;
  35475. }
  35476. /**
  35477. * Returns the properties for the given node and shader stage.
  35478. *
  35479. * Properties are typically used within a build stage to reference a node's
  35480. * child node or nodes manually assigned to the properties in a separate build stage.
  35481. * A typical usage pattern for defining nodes manually would be assigning dependency nodes
  35482. * to the current node's properties in the setup stage and building those properties in the generate stage.
  35483. *
  35484. * @param {Node} node - The node to get the properties for.
  35485. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  35486. * @return {Object} The node properties.
  35487. */
  35488. getNodeProperties( node, shaderStage = 'any' ) {
  35489. const nodeData = this.getDataFromNode( node, shaderStage );
  35490. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  35491. }
  35492. /**
  35493. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  35494. *
  35495. * @param {BufferAttributeNode} node - The buffer attribute node.
  35496. * @param {string} type - The node type.
  35497. * @return {NodeAttribute} The node attribute.
  35498. */
  35499. getBufferAttributeFromNode( node, type ) {
  35500. const nodeData = this.getDataFromNode( node );
  35501. let bufferAttribute = nodeData.bufferAttribute;
  35502. if ( bufferAttribute === undefined ) {
  35503. const index = this.uniforms.index ++;
  35504. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  35505. this.bufferAttributes.push( bufferAttribute );
  35506. nodeData.bufferAttribute = bufferAttribute;
  35507. }
  35508. return bufferAttribute;
  35509. }
  35510. /**
  35511. * Returns an instance of {@link StructType} for the given struct name and shader stage
  35512. * or null if not found.
  35513. *
  35514. * @param {string} name - The name of the struct.
  35515. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35516. * @return {?StructType} The struct type or null if not found.
  35517. */
  35518. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  35519. return this.types[ shaderStage ][ name ] || null;
  35520. }
  35521. /**
  35522. * Returns an instance of {@link StructType} for the given output struct node.
  35523. *
  35524. * @param {OutputStructNode} node - The output struct node.
  35525. * @param {Array<Object>} membersLayout - The output struct types.
  35526. * @param {?string} [name=null] - The name of the struct.
  35527. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35528. * @return {StructType} The struct type attribute.
  35529. */
  35530. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  35531. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  35532. let structType = nodeData.structType;
  35533. if ( structType === undefined ) {
  35534. const index = this.structs.index ++;
  35535. if ( name === null ) name = 'StructType' + index;
  35536. structType = new StructType( name, membersLayout );
  35537. this.structs[ shaderStage ].push( structType );
  35538. this.types[ shaderStage ][ name ] = node;
  35539. nodeData.structType = structType;
  35540. }
  35541. return structType;
  35542. }
  35543. /**
  35544. * Returns an instance of {@link StructType} for the given output struct node.
  35545. *
  35546. * @param {OutputStructNode} node - The output struct node.
  35547. * @param {Array<Object>} membersLayout - The output struct types.
  35548. * @return {StructType} The struct type attribute.
  35549. */
  35550. getOutputStructTypeFromNode( node, membersLayout ) {
  35551. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  35552. structType.output = true;
  35553. return structType;
  35554. }
  35555. /**
  35556. * Returns an instance of {@link NodeUniform} for the given uniform node.
  35557. *
  35558. * @param {UniformNode} node - The uniform node.
  35559. * @param {string} type - The uniform type.
  35560. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35561. * @param {?string} name - The name of the uniform.
  35562. * @return {NodeUniform} The node uniform.
  35563. */
  35564. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  35565. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  35566. let nodeUniform = nodeData.uniform;
  35567. if ( nodeUniform === undefined ) {
  35568. const index = this.uniforms.index ++;
  35569. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  35570. this.uniforms[ shaderStage ].push( nodeUniform );
  35571. this.registerDeclaration( nodeUniform );
  35572. nodeData.uniform = nodeUniform;
  35573. }
  35574. return nodeUniform;
  35575. }
  35576. /**
  35577. * Returns an instance of {@link NodeVar} for the given variable node.
  35578. *
  35579. * @param {VarNode} node - The variable node.
  35580. * @param {?string} name - The variable's name.
  35581. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  35582. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35583. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  35584. *
  35585. * @return {NodeVar} The node variable.
  35586. */
  35587. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  35588. const nodeData = this.getDataFromNode( node, shaderStage );
  35589. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  35590. let nodeVar = nodeData[ subBuildVariable ];
  35591. if ( nodeVar === undefined ) {
  35592. const idNS = readOnly ? '_const' : '_var';
  35593. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  35594. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  35595. if ( name === null ) {
  35596. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  35597. this.vars[ idNS ] ++;
  35598. }
  35599. //
  35600. if ( subBuildVariable !== 'variable' ) {
  35601. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  35602. }
  35603. //
  35604. const count = node.getArrayCount( this );
  35605. nodeVar = new NodeVar( name, type, readOnly, count );
  35606. if ( ! readOnly ) {
  35607. vars.push( nodeVar );
  35608. }
  35609. this.registerDeclaration( nodeVar );
  35610. nodeData[ subBuildVariable ] = nodeVar;
  35611. }
  35612. return nodeVar;
  35613. }
  35614. /**
  35615. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  35616. *
  35617. * @param {Node} node - The varying node.
  35618. * @return {boolean} Returns true if deterministic.
  35619. */
  35620. isDeterministic( node ) {
  35621. if ( node.isMathNode ) {
  35622. return this.isDeterministic( node.aNode ) &&
  35623. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  35624. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  35625. } else if ( node.isOperatorNode ) {
  35626. return this.isDeterministic( node.aNode ) &&
  35627. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  35628. } else if ( node.isArrayNode ) {
  35629. if ( node.values !== null ) {
  35630. for ( const n of node.values ) {
  35631. if ( ! this.isDeterministic( n ) ) {
  35632. return false;
  35633. }
  35634. }
  35635. }
  35636. return true;
  35637. } else if ( node.isConstNode ) {
  35638. return true;
  35639. }
  35640. return false;
  35641. }
  35642. /**
  35643. * Returns an instance of {@link NodeVarying} for the given varying node.
  35644. *
  35645. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  35646. * @param {?string} name - The varying's name.
  35647. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  35648. * @param {?string} interpolationType - The interpolation type of the varying.
  35649. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  35650. * @return {NodeVar} The node varying.
  35651. */
  35652. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  35653. const nodeData = this.getDataFromNode( node, 'any' );
  35654. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  35655. let nodeVarying = nodeData[ subBuildVarying ];
  35656. if ( nodeVarying === undefined ) {
  35657. const varyings = this.varyings;
  35658. const index = varyings.length;
  35659. if ( name === null ) name = 'nodeVarying' + index;
  35660. //
  35661. if ( subBuildVarying !== 'varying' ) {
  35662. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  35663. }
  35664. //
  35665. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  35666. varyings.push( nodeVarying );
  35667. this.registerDeclaration( nodeVarying );
  35668. nodeData[ subBuildVarying ] = nodeVarying;
  35669. }
  35670. return nodeVarying;
  35671. }
  35672. /**
  35673. * Registers a node declaration in the current shader stage.
  35674. *
  35675. * @param {Object} node - The node to be registered.
  35676. */
  35677. registerDeclaration( node ) {
  35678. const shaderStage = this.shaderStage;
  35679. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  35680. const property = this.getPropertyName( node );
  35681. let index = 1;
  35682. let name = property;
  35683. // Automatically renames the property if the name is already in use.
  35684. while ( declarations[ name ] !== undefined ) {
  35685. name = property + '_' + index ++;
  35686. }
  35687. if ( index > 1 ) {
  35688. node.name = name;
  35689. warn( `TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  35690. }
  35691. declarations[ name ] = node;
  35692. }
  35693. /**
  35694. * Returns an instance of {@link NodeCode} for the given code node.
  35695. *
  35696. * @param {CodeNode} node - The code node.
  35697. * @param {string} type - The node type.
  35698. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35699. * @return {NodeCode} The node code.
  35700. */
  35701. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  35702. const nodeData = this.getDataFromNode( node );
  35703. let nodeCode = nodeData.code;
  35704. if ( nodeCode === undefined ) {
  35705. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  35706. const index = codes.length;
  35707. nodeCode = new NodeCode( 'nodeCode' + index, type );
  35708. codes.push( nodeCode );
  35709. nodeData.code = nodeCode;
  35710. }
  35711. return nodeCode;
  35712. }
  35713. /**
  35714. * Adds a code flow based on the code-block hierarchy.
  35715. * This is used so that code-blocks like If,Else create their variables locally if the Node
  35716. * is only used inside one of these conditionals in the current shader stage.
  35717. *
  35718. * @param {Node} node - The node to add.
  35719. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  35720. */
  35721. addFlowCodeHierarchy( node, nodeBlock ) {
  35722. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  35723. let needsFlowCode = true;
  35724. let nodeBlockHierarchy = nodeBlock;
  35725. while ( nodeBlockHierarchy ) {
  35726. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  35727. needsFlowCode = false;
  35728. break;
  35729. }
  35730. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  35731. }
  35732. if ( needsFlowCode ) {
  35733. for ( const flowCode of flowCodes ) {
  35734. this.addLineFlowCode( flowCode );
  35735. }
  35736. }
  35737. }
  35738. /**
  35739. * Add a inline-code to the current flow code-block.
  35740. *
  35741. * @param {Node} node - The node to add.
  35742. * @param {string} code - The code to add.
  35743. * @param {Node} nodeBlock - Current ConditionalNode
  35744. */
  35745. addLineFlowCodeBlock( node, code, nodeBlock ) {
  35746. const nodeData = this.getDataFromNode( node );
  35747. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  35748. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  35749. flowCodes.push( code );
  35750. codeBlock.set( nodeBlock, true );
  35751. }
  35752. /**
  35753. * Add a inline-code to the current flow.
  35754. *
  35755. * @param {string} code - The code to add.
  35756. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  35757. * @return {NodeBuilder} A reference to this node builder.
  35758. */
  35759. addLineFlowCode( code, node = null ) {
  35760. if ( code === '' ) return this;
  35761. if ( node !== null && this.context.nodeBlock ) {
  35762. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  35763. }
  35764. code = this.tab + code;
  35765. if ( ! /;\s*$/.test( code ) ) {
  35766. code = code + ';\n';
  35767. }
  35768. this.flow.code += code;
  35769. return this;
  35770. }
  35771. /**
  35772. * Adds a code to the current code flow.
  35773. *
  35774. * @param {string} code - Shader code.
  35775. * @return {NodeBuilder} A reference to this node builder.
  35776. */
  35777. addFlowCode( code ) {
  35778. this.flow.code += code;
  35779. return this;
  35780. }
  35781. /**
  35782. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  35783. * Typically used in codes with If,Else.
  35784. *
  35785. * @return {NodeBuilder} A reference to this node builder.
  35786. */
  35787. addFlowTab() {
  35788. this.tab += '\t';
  35789. return this;
  35790. }
  35791. /**
  35792. * Removes a tab.
  35793. *
  35794. * @return {NodeBuilder} A reference to this node builder.
  35795. */
  35796. removeFlowTab() {
  35797. this.tab = this.tab.slice( 0, -1 );
  35798. return this;
  35799. }
  35800. /**
  35801. * Gets the current flow data based on a Node.
  35802. *
  35803. * @param {Node} node - Node that the flow was started.
  35804. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35805. * @return {Object} The flow data.
  35806. */
  35807. getFlowData( node/*, shaderStage*/ ) {
  35808. return this.flowsData.get( node );
  35809. }
  35810. /**
  35811. * Executes the node flow based on a root node to generate the final shader code.
  35812. *
  35813. * @param {Node} node - The node to execute.
  35814. * @return {Object} The code flow.
  35815. */
  35816. flowNode( node ) {
  35817. const output = node.getNodeType( this );
  35818. const flowData = this.flowChildNode( node, output );
  35819. this.flowsData.set( node, flowData );
  35820. return flowData;
  35821. }
  35822. /**
  35823. * Includes a node in the current function node.
  35824. *
  35825. * @param {Node} node - The node to include.
  35826. * @returns {void}
  35827. */
  35828. addInclude( node ) {
  35829. if ( this.currentFunctionNode !== null ) {
  35830. this.currentFunctionNode.includes.push( node );
  35831. }
  35832. }
  35833. /**
  35834. * Returns the native shader operator name for a given generic name.
  35835. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  35836. *
  35837. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  35838. * @return {FunctionNode} The build function node.
  35839. */
  35840. buildFunctionNode( shaderNode ) {
  35841. const fn = new FunctionNode();
  35842. const previous = this.currentFunctionNode;
  35843. this.currentFunctionNode = fn;
  35844. fn.code = this.buildFunctionCode( shaderNode );
  35845. this.currentFunctionNode = previous;
  35846. return fn;
  35847. }
  35848. /**
  35849. * Generates a code flow based on a TSL function: Fn().
  35850. *
  35851. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  35852. * @return {Object}
  35853. */
  35854. flowShaderNode( shaderNode ) {
  35855. const layout = shaderNode.layout;
  35856. const inputs = {
  35857. [ Symbol.iterator ]() {
  35858. let index = 0;
  35859. const values = Object.values( this );
  35860. return {
  35861. next: () => ( {
  35862. value: values[ index ],
  35863. done: index ++ >= values.length
  35864. } )
  35865. };
  35866. }
  35867. };
  35868. for ( const input of layout.inputs ) {
  35869. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  35870. }
  35871. //
  35872. shaderNode.layout = null;
  35873. const callNode = shaderNode.call( inputs );
  35874. const flowData = this.flowStagesNode( callNode, layout.type );
  35875. shaderNode.layout = layout;
  35876. return flowData;
  35877. }
  35878. /**
  35879. * Executes the node in a specific build stage.
  35880. *
  35881. * This function can be used to arbitrarily execute the specified build stage
  35882. * outside of the standard build process. For instance, if a node's type depends
  35883. * on properties created by the 'setup' stage, then flowBuildStage(node, 'setup')
  35884. * can be used to execute the setup build stage and access its generated nodes
  35885. * before the standard build process begins.
  35886. *
  35887. * @param {Node} node - The node to execute.
  35888. * @param {string} buildStage - The build stage to execute the node in.
  35889. * @param {?(Node|string)} [output=null] - Expected output type. For example 'vec3'.
  35890. * @return {?(Node|string)} The result of the node build.
  35891. */
  35892. flowBuildStage( node, buildStage, output = null ) {
  35893. const previousBuildStage = this.getBuildStage();
  35894. this.setBuildStage( buildStage );
  35895. const result = node.build( this, output );
  35896. this.setBuildStage( previousBuildStage );
  35897. return result;
  35898. }
  35899. /**
  35900. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  35901. *
  35902. * @param {Node} node - The node to execute.
  35903. * @param {?string} output - Expected output type. For example 'vec3'.
  35904. * @return {Object}
  35905. */
  35906. flowStagesNode( node, output = null ) {
  35907. const previousFlow = this.flow;
  35908. const previousVars = this.vars;
  35909. const previousDeclarations = this.declarations;
  35910. const previousCache = this.cache;
  35911. const previousBuildStage = this.buildStage;
  35912. const previousStack = this.stack;
  35913. const flow = {
  35914. code: ''
  35915. };
  35916. this.flow = flow;
  35917. this.vars = {};
  35918. this.declarations = {};
  35919. this.cache = new NodeCache();
  35920. this.stack = stack();
  35921. for ( const buildStage of defaultBuildStages ) {
  35922. this.setBuildStage( buildStage );
  35923. flow.result = node.build( this, output );
  35924. }
  35925. flow.vars = this.getVars( this.shaderStage );
  35926. this.flow = previousFlow;
  35927. this.vars = previousVars;
  35928. this.declarations = previousDeclarations;
  35929. this.cache = previousCache;
  35930. this.stack = previousStack;
  35931. this.setBuildStage( previousBuildStage );
  35932. return flow;
  35933. }
  35934. /**
  35935. * Returns the native shader operator name for a given generic name.
  35936. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  35937. *
  35938. * @abstract
  35939. * @param {string} op - The operator name to resolve.
  35940. * @return {?string} The resolved operator name.
  35941. */
  35942. getFunctionOperator( /* op */ ) {
  35943. return null;
  35944. }
  35945. /**
  35946. * Builds the given shader node.
  35947. *
  35948. * @abstract
  35949. * @param {ShaderNodeInternal} shaderNode - The shader node.
  35950. * @return {string} The function code.
  35951. */
  35952. buildFunctionCode( /* shaderNode */ ) {
  35953. warn( 'Abstract function.' );
  35954. }
  35955. /**
  35956. * Generates a code flow based on a child Node.
  35957. *
  35958. * @param {Node} node - The node to execute.
  35959. * @param {?string} output - Expected output type. For example 'vec3'.
  35960. * @return {Object} The code flow.
  35961. */
  35962. flowChildNode( node, output = null ) {
  35963. const previousFlow = this.flow;
  35964. const flow = {
  35965. code: ''
  35966. };
  35967. this.flow = flow;
  35968. flow.result = node.build( this, output );
  35969. this.flow = previousFlow;
  35970. return flow;
  35971. }
  35972. /**
  35973. * Executes a flow of code in a different stage.
  35974. *
  35975. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  35976. * return the value in fragment-stage even if it is being executed in an input fragment.
  35977. *
  35978. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35979. * @param {Node} node - The node to execute.
  35980. * @param {?string} output - Expected output type. For example 'vec3'.
  35981. * @param {?string} propertyName - The property name to assign the result.
  35982. * @return {?(Object|Node)} The code flow or node.build() result.
  35983. */
  35984. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  35985. const previousTab = this.tab;
  35986. const previousCache = this.cache;
  35987. const previousShaderStage = this.shaderStage;
  35988. const previousContext = this.context;
  35989. this.setShaderStage( shaderStage );
  35990. const context = { ...this.context };
  35991. delete context.nodeBlock;
  35992. this.cache = this.globalCache;
  35993. this.tab = '\t';
  35994. this.context = context;
  35995. let result = null;
  35996. if ( this.buildStage === 'generate' ) {
  35997. const flowData = this.flowChildNode( node, output );
  35998. if ( propertyName !== null ) {
  35999. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  36000. }
  36001. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  36002. result = flowData;
  36003. } else {
  36004. result = node.build( this );
  36005. }
  36006. this.setShaderStage( previousShaderStage );
  36007. this.cache = previousCache;
  36008. this.tab = previousTab;
  36009. this.context = previousContext;
  36010. return result;
  36011. }
  36012. /**
  36013. * Returns an array holding all node attributes of this node builder.
  36014. *
  36015. * @return {Array<NodeAttribute>} The node attributes of this builder.
  36016. */
  36017. getAttributesArray() {
  36018. return this.attributes.concat( this.bufferAttributes );
  36019. }
  36020. /**
  36021. * Returns the attribute definitions as a shader string for the given shader stage.
  36022. *
  36023. * @abstract
  36024. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36025. * @return {string} The attribute code section.
  36026. */
  36027. getAttributes( /*shaderStage*/ ) {
  36028. warn( 'Abstract function.' );
  36029. }
  36030. /**
  36031. * Returns the varying definitions as a shader string for the given shader stage.
  36032. *
  36033. * @abstract
  36034. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36035. * @return {string} The varying code section.
  36036. */
  36037. getVaryings( /*shaderStage*/ ) {
  36038. warn( 'Abstract function.' );
  36039. }
  36040. /**
  36041. * Returns a single variable definition as a shader string for the given variable type and name.
  36042. *
  36043. * @param {string} type - The variable's type.
  36044. * @param {string} name - The variable's name.
  36045. * @param {?number} [count=null] - The array length.
  36046. * @return {string} The shader string.
  36047. */
  36048. getVar( type, name, count = null ) {
  36049. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  36050. }
  36051. /**
  36052. * Returns the variable definitions as a shader string for the given shader stage.
  36053. *
  36054. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36055. * @return {string} The variable code section.
  36056. */
  36057. getVars( shaderStage ) {
  36058. let snippet = '';
  36059. const vars = this.vars[ shaderStage ];
  36060. if ( vars !== undefined ) {
  36061. for ( const variable of vars ) {
  36062. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  36063. }
  36064. }
  36065. return snippet;
  36066. }
  36067. /**
  36068. * Returns the uniform definitions as a shader string for the given shader stage.
  36069. *
  36070. * @abstract
  36071. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36072. * @return {string} The uniform code section.
  36073. */
  36074. getUniforms( /*shaderStage*/ ) {
  36075. warn( 'Abstract function.' );
  36076. }
  36077. /**
  36078. * Returns the native code definitions as a shader string for the given shader stage.
  36079. *
  36080. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36081. * @return {string} The native code section.
  36082. */
  36083. getCodes( shaderStage ) {
  36084. const codes = this.codes[ shaderStage ];
  36085. let code = '';
  36086. if ( codes !== undefined ) {
  36087. for ( const nodeCode of codes ) {
  36088. code += nodeCode.code + '\n';
  36089. }
  36090. }
  36091. return code;
  36092. }
  36093. /**
  36094. * Returns the hash of this node builder.
  36095. *
  36096. * @return {string} The hash.
  36097. */
  36098. getHash() {
  36099. return this.vertexShader + this.fragmentShader + this.computeShader;
  36100. }
  36101. /**
  36102. * Sets the current shader stage.
  36103. *
  36104. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  36105. */
  36106. setShaderStage( shaderStage ) {
  36107. this.shaderStage = shaderStage;
  36108. }
  36109. /**
  36110. * Returns the current shader stage.
  36111. *
  36112. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  36113. */
  36114. getShaderStage() {
  36115. return this.shaderStage;
  36116. }
  36117. /**
  36118. * Sets the current build stage.
  36119. *
  36120. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  36121. */
  36122. setBuildStage( buildStage ) {
  36123. this.buildStage = buildStage;
  36124. }
  36125. /**
  36126. * Returns the current build stage.
  36127. *
  36128. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  36129. */
  36130. getBuildStage() {
  36131. return this.buildStage;
  36132. }
  36133. /**
  36134. * Controls the code build of the shader stages.
  36135. *
  36136. * @abstract
  36137. */
  36138. buildCode() {
  36139. warn( 'Abstract function.' );
  36140. }
  36141. /**
  36142. * Returns the current sub-build layer.
  36143. *
  36144. * @return {SubBuildNode} The current sub-build layers.
  36145. */
  36146. get subBuild() {
  36147. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  36148. }
  36149. /**
  36150. * Adds a sub-build layer to the node builder.
  36151. *
  36152. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  36153. */
  36154. addSubBuild( subBuild ) {
  36155. this.subBuildLayers.push( subBuild );
  36156. }
  36157. /**
  36158. * Removes the last sub-build layer from the node builder.
  36159. *
  36160. * @return {SubBuildNode} The removed sub-build layer.
  36161. */
  36162. removeSubBuild() {
  36163. return this.subBuildLayers.pop();
  36164. }
  36165. /**
  36166. * Returns the closest sub-build layer for the given data.
  36167. *
  36168. * @param {Node|Set<string>|Array<string>} data - The data to get the closest sub-build layer from.
  36169. * @return {?string} The closest sub-build name or null if none found.
  36170. */
  36171. getClosestSubBuild( data ) {
  36172. let subBuilds;
  36173. if ( data && data.isNode ) {
  36174. if ( data.isShaderCallNodeInternal ) {
  36175. subBuilds = data.shaderNode.subBuilds;
  36176. } else if ( data.isStackNode ) {
  36177. subBuilds = [ data.subBuild ];
  36178. } else {
  36179. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  36180. }
  36181. } else if ( data instanceof Set ) {
  36182. subBuilds = [ ...data ];
  36183. } else {
  36184. subBuilds = data;
  36185. }
  36186. if ( ! subBuilds ) return null;
  36187. const subBuildLayers = this.subBuildLayers;
  36188. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  36189. const subBuild = subBuilds[ i ];
  36190. if ( subBuildLayers.includes( subBuild ) ) {
  36191. return subBuild;
  36192. }
  36193. }
  36194. return null;
  36195. }
  36196. /**
  36197. * Returns the output node of a sub-build layer.
  36198. *
  36199. * @param {Node} node - The node to get the output from.
  36200. * @return {string} The output node name.
  36201. */
  36202. getSubBuildOutput( node ) {
  36203. return this.getSubBuildProperty( 'outputNode', node );
  36204. }
  36205. /**
  36206. * Returns the sub-build property name for the given property and node.
  36207. *
  36208. * @param {string} [property=''] - The property name.
  36209. * @param {?Node} [node=null] - The node to get the sub-build from.
  36210. * @return {string} The sub-build property name.
  36211. */
  36212. getSubBuildProperty( property = '', node = null ) {
  36213. let subBuild;
  36214. if ( node !== null ) {
  36215. subBuild = this.getClosestSubBuild( node );
  36216. } else {
  36217. subBuild = this.subBuildFn;
  36218. }
  36219. let result;
  36220. if ( subBuild ) {
  36221. result = property ? ( subBuild + '_' + property ) : subBuild;
  36222. } else {
  36223. result = property;
  36224. }
  36225. return result;
  36226. }
  36227. /**
  36228. * Central build method which controls the build for the given object.
  36229. *
  36230. * @return {NodeBuilder} A reference to this node builder.
  36231. */
  36232. build() {
  36233. const { object, material, renderer } = this;
  36234. if ( material !== null ) {
  36235. let nodeMaterial = renderer.library.fromMaterial( material );
  36236. if ( nodeMaterial === null ) {
  36237. error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  36238. nodeMaterial = new NodeMaterial();
  36239. }
  36240. nodeMaterial.build( this );
  36241. } else {
  36242. this.addFlow( 'compute', object );
  36243. }
  36244. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  36245. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  36246. // generate() -> stage 3: generate shader
  36247. for ( const buildStage of defaultBuildStages ) {
  36248. this.setBuildStage( buildStage );
  36249. if ( this.context.vertex && this.context.vertex.isNode ) {
  36250. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  36251. }
  36252. for ( const shaderStage of shaderStages ) {
  36253. this.setShaderStage( shaderStage );
  36254. const flowNodes = this.flowNodes[ shaderStage ];
  36255. for ( const node of flowNodes ) {
  36256. if ( buildStage === 'generate' ) {
  36257. this.flowNode( node );
  36258. } else {
  36259. node.build( this );
  36260. }
  36261. }
  36262. }
  36263. }
  36264. this.setBuildStage( null );
  36265. this.setShaderStage( null );
  36266. // stage 4: build code for a specific output
  36267. this.buildCode();
  36268. this.buildUpdateNodes();
  36269. return this;
  36270. }
  36271. /**
  36272. * Returns a uniform representation which is later used for UBO generation and rendering.
  36273. *
  36274. * @param {NodeUniform} uniformNode - The uniform node.
  36275. * @param {string} type - The requested type.
  36276. * @return {Uniform} The uniform.
  36277. */
  36278. getNodeUniform( uniformNode, type ) {
  36279. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  36280. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  36281. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  36282. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  36283. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  36284. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  36285. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  36286. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  36287. throw new Error( `Uniform "${type}" not declared.` );
  36288. }
  36289. /**
  36290. * Formats the given shader snippet from a given type into another one. E.g.
  36291. * this method might be used to convert a simple float string `"1.0"` into a
  36292. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  36293. *
  36294. * @param {string} snippet - The shader snippet.
  36295. * @param {string} fromType - The source type.
  36296. * @param {string} toType - The target type.
  36297. * @return {string} The updated shader string.
  36298. */
  36299. format( snippet, fromType, toType ) {
  36300. fromType = this.getVectorType( fromType );
  36301. toType = this.getVectorType( toType );
  36302. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  36303. return snippet;
  36304. }
  36305. const fromTypeLength = this.getTypeLength( fromType );
  36306. const toTypeLength = this.getTypeLength( toType );
  36307. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  36308. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  36309. }
  36310. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  36311. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  36312. }
  36313. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  36314. // @TODO: ignore for now
  36315. return snippet;
  36316. }
  36317. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  36318. // @TODO: ignore for now
  36319. return snippet;
  36320. }
  36321. if ( fromTypeLength === toTypeLength ) {
  36322. return `${ this.getType( toType ) }( ${ snippet } )`;
  36323. }
  36324. if ( fromTypeLength > toTypeLength ) {
  36325. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  36326. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  36327. }
  36328. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  36329. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  36330. }
  36331. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  36332. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  36333. }
  36334. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  36335. // convert a number value to vector type, e.g:
  36336. // vec3( 1u ) -> vec3( float( 1u ) )
  36337. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  36338. }
  36339. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  36340. }
  36341. /**
  36342. * Returns a signature with the engine's current revision.
  36343. *
  36344. * @return {string} The signature.
  36345. */
  36346. getSignature() {
  36347. return `// Three.js r${ REVISION } - Node System\n`;
  36348. }
  36349. }
  36350. /**
  36351. * Management class for updating nodes. The module tracks metrics like
  36352. * the elapsed time, delta time, the render and frame ID to correctly
  36353. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  36354. * and {@link Node#updateAfter} depending on the node's configuration.
  36355. */
  36356. class NodeFrame {
  36357. /**
  36358. * Constructs a new node fame.
  36359. */
  36360. constructor() {
  36361. /**
  36362. * The elapsed time in seconds.
  36363. *
  36364. * @type {number}
  36365. * @default 0
  36366. */
  36367. this.time = 0;
  36368. /**
  36369. * The delta time in seconds.
  36370. *
  36371. * @type {number}
  36372. * @default 0
  36373. */
  36374. this.deltaTime = 0;
  36375. /**
  36376. * The frame ID.
  36377. *
  36378. * @type {number}
  36379. * @default 0
  36380. */
  36381. this.frameId = 0;
  36382. /**
  36383. * The render ID.
  36384. *
  36385. * @type {number}
  36386. * @default 0
  36387. */
  36388. this.renderId = 0;
  36389. /**
  36390. * Used to control the {@link Node#update} call.
  36391. *
  36392. * @type {WeakMap<Node, Object>}
  36393. */
  36394. this.updateMap = new WeakMap();
  36395. /**
  36396. * Used to control the {@link Node#updateBefore} call.
  36397. *
  36398. * @type {WeakMap<Node, Object>}
  36399. */
  36400. this.updateBeforeMap = new WeakMap();
  36401. /**
  36402. * Used to control the {@link Node#updateAfter} call.
  36403. *
  36404. * @type {WeakMap<Node, Object>}
  36405. */
  36406. this.updateAfterMap = new WeakMap();
  36407. /**
  36408. * A reference to the current renderer.
  36409. *
  36410. * @type {?Renderer}
  36411. * @default null
  36412. */
  36413. this.renderer = null;
  36414. /**
  36415. * A reference to the current material.
  36416. *
  36417. * @type {?Material}
  36418. * @default null
  36419. */
  36420. this.material = null;
  36421. /**
  36422. * A reference to the current camera.
  36423. *
  36424. * @type {?Camera}
  36425. * @default null
  36426. */
  36427. this.camera = null;
  36428. /**
  36429. * A reference to the current 3D object.
  36430. *
  36431. * @type {?Object3D}
  36432. * @default null
  36433. */
  36434. this.object = null;
  36435. /**
  36436. * A reference to the current scene.
  36437. *
  36438. * @type {?Scene}
  36439. * @default null
  36440. */
  36441. this.scene = null;
  36442. }
  36443. /**
  36444. * Returns a dictionary for a given node and update map which
  36445. * is used to correctly call node update methods per frame or render.
  36446. *
  36447. * @private
  36448. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  36449. * @param {Node} nodeRef - The reference to the current node.
  36450. * @return {Object<string,WeakMap<Object, number>>} The dictionary.
  36451. */
  36452. _getMaps( referenceMap, nodeRef ) {
  36453. let maps = referenceMap.get( nodeRef );
  36454. if ( maps === undefined ) {
  36455. maps = {
  36456. renderId: 0,
  36457. frameId: 0,
  36458. };
  36459. referenceMap.set( nodeRef, maps );
  36460. }
  36461. return maps;
  36462. }
  36463. /**
  36464. * This method executes the {@link Node#updateBefore} for the given node.
  36465. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  36466. * is only executed once per frame, render or object depending on the update
  36467. * type.
  36468. *
  36469. * @param {Node} node - The node that should be updated.
  36470. */
  36471. updateBeforeNode( node ) {
  36472. const updateType = node.getUpdateBeforeType();
  36473. const reference = node.updateReference( this );
  36474. if ( updateType === NodeUpdateType.FRAME ) {
  36475. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  36476. if ( nodeUpdateBeforeMap.frameId !== this.frameId ) {
  36477. if ( node.updateBefore( this ) !== false ) {
  36478. nodeUpdateBeforeMap.frameId = this.frameId;
  36479. }
  36480. }
  36481. } else if ( updateType === NodeUpdateType.RENDER ) {
  36482. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  36483. if ( nodeUpdateBeforeMap.renderId !== this.renderId ) {
  36484. if ( node.updateBefore( this ) !== false ) {
  36485. nodeUpdateBeforeMap.renderId = this.renderId;
  36486. }
  36487. }
  36488. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36489. node.updateBefore( this );
  36490. }
  36491. }
  36492. /**
  36493. * This method executes the {@link Node#updateAfter} for the given node.
  36494. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  36495. * is only executed once per frame, render or object depending on the update
  36496. * type.
  36497. *
  36498. * @param {Node} node - The node that should be updated.
  36499. */
  36500. updateAfterNode( node ) {
  36501. const updateType = node.getUpdateAfterType();
  36502. const reference = node.updateReference( this );
  36503. if ( updateType === NodeUpdateType.FRAME ) {
  36504. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  36505. if ( nodeUpdateAfterMap.frameId !== this.frameId ) {
  36506. if ( node.updateAfter( this ) !== false ) {
  36507. nodeUpdateAfterMap.frameId = this.frameId;
  36508. }
  36509. }
  36510. } else if ( updateType === NodeUpdateType.RENDER ) {
  36511. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  36512. if ( nodeUpdateAfterMap.renderId !== this.renderId ) {
  36513. if ( node.updateAfter( this ) !== false ) {
  36514. nodeUpdateAfterMap.renderId = this.renderId;
  36515. }
  36516. }
  36517. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36518. node.updateAfter( this );
  36519. }
  36520. }
  36521. /**
  36522. * This method executes the {@link Node#update} for the given node.
  36523. * It makes sure {@link Node#updateType} is honored meaning the update
  36524. * is only executed once per frame, render or object depending on the update
  36525. * type.
  36526. *
  36527. * @param {Node} node - The node that should be updated.
  36528. */
  36529. updateNode( node ) {
  36530. const updateType = node.getUpdateType();
  36531. const reference = node.updateReference( this );
  36532. if ( updateType === NodeUpdateType.FRAME ) {
  36533. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  36534. if ( nodeUpdateMap.frameId !== this.frameId ) {
  36535. if ( node.update( this ) !== false ) {
  36536. nodeUpdateMap.frameId = this.frameId;
  36537. }
  36538. }
  36539. } else if ( updateType === NodeUpdateType.RENDER ) {
  36540. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  36541. if ( nodeUpdateMap.renderId !== this.renderId ) {
  36542. if ( node.update( this ) !== false ) {
  36543. nodeUpdateMap.renderId = this.renderId;
  36544. }
  36545. }
  36546. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36547. node.update( this );
  36548. }
  36549. }
  36550. /**
  36551. * Updates the internal state of the node frame. This method is
  36552. * called by the renderer in its internal animation loop.
  36553. */
  36554. update() {
  36555. this.frameId ++;
  36556. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  36557. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  36558. this.lastTime = performance.now();
  36559. this.time += this.deltaTime;
  36560. }
  36561. }
  36562. /**
  36563. * Describes the input of a {@link NodeFunction}.
  36564. */
  36565. class NodeFunctionInput {
  36566. /**
  36567. * Constructs a new node function input.
  36568. *
  36569. * @param {string} type - The input type.
  36570. * @param {string} name - The input name.
  36571. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  36572. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  36573. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  36574. */
  36575. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  36576. /**
  36577. * The input type.
  36578. *
  36579. * @type {string}
  36580. */
  36581. this.type = type;
  36582. /**
  36583. * The input name.
  36584. *
  36585. * @type {string}
  36586. */
  36587. this.name = name;
  36588. /**
  36589. * If the input is an Array, count will be the length.
  36590. *
  36591. * @type {?number}
  36592. * @default null
  36593. */
  36594. this.count = count;
  36595. /**
  36596. *The parameter qualifier (only relevant for GLSL).
  36597. *
  36598. * @type {('in'|'out'|'inout')}
  36599. * @default ''
  36600. */
  36601. this.qualifier = qualifier;
  36602. /**
  36603. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  36604. *
  36605. * @type {boolean}
  36606. * @default false
  36607. */
  36608. this.isConst = isConst;
  36609. }
  36610. }
  36611. NodeFunctionInput.isNodeFunctionInput = true;
  36612. /**
  36613. * Module for representing directional lights as nodes.
  36614. *
  36615. * @augments AnalyticLightNode
  36616. */
  36617. class DirectionalLightNode extends AnalyticLightNode {
  36618. static get type() {
  36619. return 'DirectionalLightNode';
  36620. }
  36621. /**
  36622. * Constructs a new directional light node.
  36623. *
  36624. * @param {?DirectionalLight} [light=null] - The directional light source.
  36625. */
  36626. constructor( light = null ) {
  36627. super( light );
  36628. }
  36629. setupDirect() {
  36630. const lightColor = this.colorNode;
  36631. const lightDirection = lightTargetDirection( this.light );
  36632. return { lightDirection, lightColor };
  36633. }
  36634. }
  36635. const _matrix41 = /*@__PURE__*/ new Matrix4();
  36636. const _matrix42 = /*@__PURE__*/ new Matrix4();
  36637. let _ltcLib = null;
  36638. /**
  36639. * Module for representing rect area lights as nodes.
  36640. *
  36641. * @augments AnalyticLightNode
  36642. */
  36643. class RectAreaLightNode extends AnalyticLightNode {
  36644. static get type() {
  36645. return 'RectAreaLightNode';
  36646. }
  36647. /**
  36648. * Constructs a new rect area light node.
  36649. *
  36650. * @param {?RectAreaLight} [light=null] - The rect area light source.
  36651. */
  36652. constructor( light = null ) {
  36653. super( light );
  36654. /**
  36655. * Uniform node representing the half height of the are light.
  36656. *
  36657. * @type {UniformNode<vec3>}
  36658. */
  36659. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  36660. /**
  36661. * Uniform node representing the half width of the are light.
  36662. *
  36663. * @type {UniformNode<vec3>}
  36664. */
  36665. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  36666. /**
  36667. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  36668. * relies on `viewMatrix` which might vary per render call.
  36669. *
  36670. * @type {string}
  36671. * @default 'render'
  36672. */
  36673. this.updateType = NodeUpdateType.RENDER;
  36674. }
  36675. /**
  36676. * Overwritten to updated rect area light specific uniforms.
  36677. *
  36678. * @param {NodeFrame} frame - A reference to the current node frame.
  36679. */
  36680. update( frame ) {
  36681. super.update( frame );
  36682. const { light } = this;
  36683. const viewMatrix = frame.camera.matrixWorldInverse;
  36684. _matrix42.identity();
  36685. _matrix41.copy( light.matrixWorld );
  36686. _matrix41.premultiply( viewMatrix );
  36687. _matrix42.extractRotation( _matrix41 );
  36688. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  36689. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  36690. this.halfWidth.value.applyMatrix4( _matrix42 );
  36691. this.halfHeight.value.applyMatrix4( _matrix42 );
  36692. }
  36693. setupDirectRectArea( builder ) {
  36694. let ltc_1, ltc_2;
  36695. if ( builder.isAvailable( 'float32Filterable' ) ) {
  36696. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  36697. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  36698. } else {
  36699. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  36700. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  36701. }
  36702. const { colorNode, light } = this;
  36703. const lightPosition = lightViewPosition( light );
  36704. return {
  36705. lightColor: colorNode,
  36706. lightPosition,
  36707. halfWidth: this.halfWidth,
  36708. halfHeight: this.halfHeight,
  36709. ltc_1,
  36710. ltc_2
  36711. };
  36712. }
  36713. /**
  36714. * Used to configure the internal BRDF approximation texture data.
  36715. *
  36716. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  36717. */
  36718. static setLTC( ltc ) {
  36719. _ltcLib = ltc;
  36720. }
  36721. }
  36722. /**
  36723. * Module for representing spot lights as nodes.
  36724. *
  36725. * @augments AnalyticLightNode
  36726. */
  36727. class SpotLightNode extends AnalyticLightNode {
  36728. static get type() {
  36729. return 'SpotLightNode';
  36730. }
  36731. /**
  36732. * Constructs a new spot light node.
  36733. *
  36734. * @param {?SpotLight} [light=null] - The spot light source.
  36735. */
  36736. constructor( light = null ) {
  36737. super( light );
  36738. /**
  36739. * Uniform node representing the cone cosine.
  36740. *
  36741. * @type {UniformNode<float>}
  36742. */
  36743. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  36744. /**
  36745. * Uniform node representing the penumbra cosine.
  36746. *
  36747. * @type {UniformNode<float>}
  36748. */
  36749. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  36750. /**
  36751. * Uniform node representing the cutoff distance.
  36752. *
  36753. * @type {UniformNode<float>}
  36754. */
  36755. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  36756. /**
  36757. * Uniform node representing the decay exponent.
  36758. *
  36759. * @type {UniformNode<float>}
  36760. */
  36761. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  36762. /**
  36763. * Uniform node representing the light color.
  36764. *
  36765. * @type {UniformNode<Color>}
  36766. */
  36767. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  36768. }
  36769. /**
  36770. * Overwritten to updated spot light specific uniforms.
  36771. *
  36772. * @param {NodeFrame} frame - A reference to the current node frame.
  36773. */
  36774. update( frame ) {
  36775. super.update( frame );
  36776. const { light } = this;
  36777. this.coneCosNode.value = Math.cos( light.angle );
  36778. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  36779. this.cutoffDistanceNode.value = light.distance;
  36780. this.decayExponentNode.value = light.decay;
  36781. }
  36782. /**
  36783. * Computes the spot attenuation for the given angle.
  36784. *
  36785. * @param {NodeBuilder} builder - The node builder.
  36786. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  36787. * @return {Node<float>} The spot attenuation.
  36788. */
  36789. getSpotAttenuation( builder, angleCosine ) {
  36790. const { coneCosNode, penumbraCosNode } = this;
  36791. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  36792. }
  36793. getLightCoord( builder ) {
  36794. const properties = builder.getNodeProperties( this );
  36795. let projectionUV = properties.projectionUV;
  36796. if ( projectionUV === undefined ) {
  36797. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  36798. properties.projectionUV = projectionUV;
  36799. }
  36800. return projectionUV;
  36801. }
  36802. setupDirect( builder ) {
  36803. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  36804. const lightVector = this.getLightVector( builder );
  36805. const lightDirection = lightVector.normalize();
  36806. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  36807. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  36808. const lightDistance = lightVector.length();
  36809. const lightAttenuation = getDistanceAttenuation( {
  36810. lightDistance,
  36811. cutoffDistance: cutoffDistanceNode,
  36812. decayExponent: decayExponentNode
  36813. } );
  36814. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  36815. let projected, lightCoord;
  36816. if ( light.colorNode ) {
  36817. lightCoord = this.getLightCoord( builder );
  36818. projected = light.colorNode( lightCoord );
  36819. } else if ( light.map ) {
  36820. lightCoord = this.getLightCoord( builder );
  36821. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  36822. }
  36823. if ( projected ) {
  36824. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  36825. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  36826. }
  36827. return { lightColor, lightDirection };
  36828. }
  36829. }
  36830. /**
  36831. * An IES version of the default spot light node.
  36832. *
  36833. * @augments SpotLightNode
  36834. */
  36835. class IESSpotLightNode extends SpotLightNode {
  36836. static get type() {
  36837. return 'IESSpotLightNode';
  36838. }
  36839. /**
  36840. * Overwrites the default implementation to compute an IES conform spot attenuation.
  36841. *
  36842. * @param {NodeBuilder} builder - The node builder.
  36843. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  36844. * @return {Node<float>} The spot attenuation.
  36845. */
  36846. getSpotAttenuation( builder, angleCosine ) {
  36847. const iesMap = this.light.iesMap;
  36848. let spotAttenuation = null;
  36849. if ( iesMap && iesMap.isTexture === true ) {
  36850. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  36851. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  36852. } else {
  36853. spotAttenuation = super.getSpotAttenuation( angleCosine );
  36854. }
  36855. return spotAttenuation;
  36856. }
  36857. }
  36858. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  36859. const d = p.abs().sub( b );
  36860. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  36861. } );
  36862. /**
  36863. * An implementation of a projector light node.
  36864. *
  36865. * @augments SpotLightNode
  36866. */
  36867. class ProjectorLightNode extends SpotLightNode {
  36868. static get type() {
  36869. return 'ProjectorLightNode';
  36870. }
  36871. update( frame ) {
  36872. super.update( frame );
  36873. const light = this.light;
  36874. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  36875. if ( light.aspect === null ) {
  36876. let aspect = 1;
  36877. if ( light.map !== null ) {
  36878. aspect = light.map.width / light.map.height;
  36879. }
  36880. light.shadow.aspect = aspect;
  36881. } else {
  36882. light.shadow.aspect = light.aspect;
  36883. }
  36884. }
  36885. /**
  36886. * Overwrites the default implementation to compute projection attenuation.
  36887. *
  36888. * @param {NodeBuilder} builder - The node builder.
  36889. * @return {Node<float>} The spot attenuation.
  36890. */
  36891. getSpotAttenuation( builder ) {
  36892. const attenuation = float( 0 );
  36893. const penumbraCos = this.penumbraCosNode;
  36894. // compute the fragment's position in the light's clip space
  36895. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  36896. // the sign of w determines whether the current fragment is in front or behind the light.
  36897. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  36898. If( spotLightCoord.w.greaterThan( 0 ), () => {
  36899. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  36900. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  36901. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  36902. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  36903. } );
  36904. return attenuation;
  36905. }
  36906. }
  36907. /**
  36908. * Module for representing ambient lights as nodes.
  36909. *
  36910. * @augments AnalyticLightNode
  36911. */
  36912. class AmbientLightNode extends AnalyticLightNode {
  36913. static get type() {
  36914. return 'AmbientLightNode';
  36915. }
  36916. /**
  36917. * Constructs a new ambient light node.
  36918. *
  36919. * @param {?AmbientLight} [light=null] - The ambient light source.
  36920. */
  36921. constructor( light = null ) {
  36922. super( light );
  36923. }
  36924. setup( { context } ) {
  36925. context.irradiance.addAssign( this.colorNode );
  36926. }
  36927. }
  36928. /**
  36929. * Module for representing hemisphere lights as nodes.
  36930. *
  36931. * @augments AnalyticLightNode
  36932. */
  36933. class HemisphereLightNode extends AnalyticLightNode {
  36934. static get type() {
  36935. return 'HemisphereLightNode';
  36936. }
  36937. /**
  36938. * Constructs a new hemisphere light node.
  36939. *
  36940. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  36941. */
  36942. constructor( light = null ) {
  36943. super( light );
  36944. /**
  36945. * Uniform node representing the light's position.
  36946. *
  36947. * @type {UniformNode<vec3>}
  36948. */
  36949. this.lightPositionNode = lightPosition( light );
  36950. /**
  36951. * A node representing the light's direction.
  36952. *
  36953. * @type {Node<vec3>}
  36954. */
  36955. this.lightDirectionNode = this.lightPositionNode.normalize();
  36956. /**
  36957. * Uniform node representing the light's ground color.
  36958. *
  36959. * @type {UniformNode<vec3>}
  36960. */
  36961. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  36962. }
  36963. /**
  36964. * Overwritten to updated hemisphere light specific uniforms.
  36965. *
  36966. * @param {NodeFrame} frame - A reference to the current node frame.
  36967. */
  36968. update( frame ) {
  36969. const { light } = this;
  36970. super.update( frame );
  36971. this.lightPositionNode.object3d = light;
  36972. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  36973. }
  36974. setup( builder ) {
  36975. const { colorNode, groundColorNode, lightDirectionNode } = this;
  36976. const dotNL = normalWorld.dot( lightDirectionNode );
  36977. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  36978. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  36979. builder.context.irradiance.addAssign( irradiance );
  36980. }
  36981. }
  36982. /**
  36983. * Module for representing light probes as nodes.
  36984. *
  36985. * @augments AnalyticLightNode
  36986. */
  36987. class LightProbeNode extends AnalyticLightNode {
  36988. static get type() {
  36989. return 'LightProbeNode';
  36990. }
  36991. /**
  36992. * Constructs a new light probe node.
  36993. *
  36994. * @param {?LightProbe} [light=null] - The light probe.
  36995. */
  36996. constructor( light = null ) {
  36997. super( light );
  36998. const array = [];
  36999. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  37000. /**
  37001. * Light probe represented as a uniform of spherical harmonics.
  37002. *
  37003. * @type {UniformArrayNode}
  37004. */
  37005. this.lightProbe = uniformArray( array );
  37006. }
  37007. /**
  37008. * Overwritten to updated light probe specific uniforms.
  37009. *
  37010. * @param {NodeFrame} frame - A reference to the current node frame.
  37011. */
  37012. update( frame ) {
  37013. const { light } = this;
  37014. super.update( frame );
  37015. //
  37016. for ( let i = 0; i < 9; i ++ ) {
  37017. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  37018. }
  37019. }
  37020. setup( builder ) {
  37021. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  37022. builder.context.irradiance.addAssign( irradiance );
  37023. }
  37024. }
  37025. /**
  37026. * Base class for node parsers. A derived parser must be implemented
  37027. * for each supported native shader language.
  37028. */
  37029. class NodeParser {
  37030. /**
  37031. * The method parses the given native code an returns a node function.
  37032. *
  37033. * @abstract
  37034. * @param {string} source - The native shader code.
  37035. * @return {NodeFunction} A node function.
  37036. */
  37037. parseFunction( /*source*/ ) {
  37038. warn( 'Abstract function.' );
  37039. }
  37040. }
  37041. /**
  37042. * Base class for node functions. A derived module must be implemented
  37043. * for each supported native shader language. Similar to other `Node*` modules,
  37044. * this class is only relevant during the building process and not used
  37045. * in user-level code.
  37046. */
  37047. class NodeFunction {
  37048. /**
  37049. * Constructs a new node function.
  37050. *
  37051. * @param {string} type - The node type. This type is the return type of the node function.
  37052. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  37053. * @param {string} [name=''] - The function's name.
  37054. * @param {string} [precision=''] - The precision qualifier.
  37055. */
  37056. constructor( type, inputs, name = '', precision = '' ) {
  37057. /**
  37058. * The node type. This type is the return type of the node function.
  37059. *
  37060. * @type {string}
  37061. */
  37062. this.type = type;
  37063. /**
  37064. * The function's inputs.
  37065. *
  37066. * @type {Array<NodeFunctionInput>}
  37067. */
  37068. this.inputs = inputs;
  37069. /**
  37070. * The name of the uniform.
  37071. *
  37072. * @type {string}
  37073. * @default ''
  37074. */
  37075. this.name = name;
  37076. /**
  37077. * The precision qualifier.
  37078. *
  37079. * @type {string}
  37080. * @default ''
  37081. */
  37082. this.precision = precision;
  37083. }
  37084. /**
  37085. * This method returns the native code of the node function.
  37086. *
  37087. * @abstract
  37088. * @param {string} name - The function's name.
  37089. * @return {string} A shader code.
  37090. */
  37091. getCode( /*name = this.name*/ ) {
  37092. warn( 'Abstract function.' );
  37093. }
  37094. }
  37095. NodeFunction.isNodeFunction = true;
  37096. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  37097. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  37098. const pragmaMain = '#pragma main';
  37099. const parse$1 = ( source ) => {
  37100. source = source.trim();
  37101. const pragmaMainIndex = source.indexOf( pragmaMain );
  37102. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  37103. const declaration = mainCode.match( declarationRegexp$1 );
  37104. if ( declaration !== null && declaration.length === 5 ) {
  37105. // tokenizer
  37106. const inputsCode = declaration[ 4 ];
  37107. const propsMatches = [];
  37108. let nameMatch = null;
  37109. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  37110. propsMatches.push( nameMatch );
  37111. }
  37112. // parser
  37113. const inputs = [];
  37114. let i = 0;
  37115. while ( i < propsMatches.length ) {
  37116. const isConst = propsMatches[ i ][ 0 ] === 'const';
  37117. if ( isConst === true ) {
  37118. i ++;
  37119. }
  37120. let qualifier = propsMatches[ i ][ 0 ];
  37121. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  37122. i ++;
  37123. } else {
  37124. qualifier = '';
  37125. }
  37126. const type = propsMatches[ i ++ ][ 0 ];
  37127. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  37128. if ( Number.isNaN( count ) === false ) i ++;
  37129. else count = null;
  37130. const name = propsMatches[ i ++ ][ 0 ];
  37131. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  37132. }
  37133. //
  37134. const blockCode = mainCode.substring( declaration[ 0 ].length );
  37135. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  37136. const type = declaration[ 2 ];
  37137. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  37138. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  37139. return {
  37140. type,
  37141. inputs,
  37142. name,
  37143. precision,
  37144. inputsCode,
  37145. blockCode,
  37146. headerCode
  37147. };
  37148. } else {
  37149. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  37150. }
  37151. };
  37152. /**
  37153. * This class represents a GLSL node function.
  37154. *
  37155. * @augments NodeFunction
  37156. */
  37157. class GLSLNodeFunction extends NodeFunction {
  37158. /**
  37159. * Constructs a new GLSL node function.
  37160. *
  37161. * @param {string} source - The GLSL source.
  37162. */
  37163. constructor( source ) {
  37164. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  37165. super( type, inputs, name, precision );
  37166. this.inputsCode = inputsCode;
  37167. this.blockCode = blockCode;
  37168. this.headerCode = headerCode;
  37169. }
  37170. /**
  37171. * This method returns the GLSL code of the node function.
  37172. *
  37173. * @param {string} [name=this.name] - The function's name.
  37174. * @return {string} The shader code.
  37175. */
  37176. getCode( name = this.name ) {
  37177. let code;
  37178. const blockCode = this.blockCode;
  37179. if ( blockCode !== '' ) {
  37180. const { type, inputsCode, headerCode, precision } = this;
  37181. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  37182. if ( precision !== '' ) {
  37183. declarationCode = `${ precision } ${ declarationCode }`;
  37184. }
  37185. code = headerCode + declarationCode + blockCode;
  37186. } else {
  37187. // interface function
  37188. code = '';
  37189. }
  37190. return code;
  37191. }
  37192. }
  37193. /**
  37194. * A GLSL node parser.
  37195. *
  37196. * @augments NodeParser
  37197. */
  37198. class GLSLNodeParser extends NodeParser {
  37199. /**
  37200. * The method parses the given GLSL code an returns a node function.
  37201. *
  37202. * @param {string} source - The GLSL code.
  37203. * @return {GLSLNodeFunction} A node function.
  37204. */
  37205. parseFunction( source ) {
  37206. return new GLSLNodeFunction( source );
  37207. }
  37208. }
  37209. const _outputNodeMap = new WeakMap();
  37210. const _chainKeys$2 = [];
  37211. const _cacheKeyValues = [];
  37212. /**
  37213. * This renderer module manages node-related objects and is the
  37214. * primary interface between the renderer and the node system.
  37215. *
  37216. * @private
  37217. * @augments DataMap
  37218. */
  37219. class Nodes extends DataMap {
  37220. /**
  37221. * Constructs a new nodes management component.
  37222. *
  37223. * @param {Renderer} renderer - The renderer.
  37224. * @param {Backend} backend - The renderer's backend.
  37225. */
  37226. constructor( renderer, backend ) {
  37227. super();
  37228. /**
  37229. * The renderer.
  37230. *
  37231. * @type {Renderer}
  37232. */
  37233. this.renderer = renderer;
  37234. /**
  37235. * The renderer's backend.
  37236. *
  37237. * @type {Backend}
  37238. */
  37239. this.backend = backend;
  37240. /**
  37241. * The node frame.
  37242. *
  37243. * @type {Renderer}
  37244. */
  37245. this.nodeFrame = new NodeFrame();
  37246. /**
  37247. * A cache for managing node builder states.
  37248. *
  37249. * @type {Map<number,NodeBuilderState>}
  37250. */
  37251. this.nodeBuilderCache = new Map();
  37252. /**
  37253. * A cache for managing data cache key data.
  37254. *
  37255. * @type {ChainMap}
  37256. */
  37257. this.callHashCache = new ChainMap();
  37258. /**
  37259. * A cache for managing node uniforms group data.
  37260. *
  37261. * @type {ChainMap}
  37262. */
  37263. this.groupsData = new ChainMap();
  37264. /**
  37265. * A cache for managing node objects of
  37266. * scene properties like fog or environments.
  37267. *
  37268. * @type {Object<string,WeakMap>}
  37269. */
  37270. this.cacheLib = {};
  37271. }
  37272. /**
  37273. * Returns `true` if the given node uniforms group must be updated or not.
  37274. *
  37275. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  37276. * @return {boolean} Whether the node uniforms group requires an update or not.
  37277. */
  37278. updateGroup( nodeUniformsGroup ) {
  37279. const groupNode = nodeUniformsGroup.groupNode;
  37280. const name = groupNode.name;
  37281. // objectGroup is always updated
  37282. if ( name === objectGroup.name ) return true;
  37283. // renderGroup is updated once per render/compute call
  37284. if ( name === renderGroup.name ) {
  37285. const uniformsGroupData = this.get( nodeUniformsGroup );
  37286. const renderId = this.nodeFrame.renderId;
  37287. if ( uniformsGroupData.renderId !== renderId ) {
  37288. uniformsGroupData.renderId = renderId;
  37289. return true;
  37290. }
  37291. return false;
  37292. }
  37293. // frameGroup is updated once per frame
  37294. if ( name === frameGroup.name ) {
  37295. const uniformsGroupData = this.get( nodeUniformsGroup );
  37296. const frameId = this.nodeFrame.frameId;
  37297. if ( uniformsGroupData.frameId !== frameId ) {
  37298. uniformsGroupData.frameId = frameId;
  37299. return true;
  37300. }
  37301. return false;
  37302. }
  37303. // other groups are updated just when groupNode.needsUpdate is true
  37304. _chainKeys$2[ 0 ] = groupNode;
  37305. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  37306. let groupData = this.groupsData.get( _chainKeys$2 );
  37307. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  37308. _chainKeys$2.length = 0;
  37309. if ( groupData.version !== groupNode.version ) {
  37310. groupData.version = groupNode.version;
  37311. return true;
  37312. }
  37313. return false;
  37314. }
  37315. /**
  37316. * Returns the cache key for the given render object.
  37317. *
  37318. * @param {RenderObject} renderObject - The render object.
  37319. * @return {number} The cache key.
  37320. */
  37321. getForRenderCacheKey( renderObject ) {
  37322. return renderObject.initialCacheKey;
  37323. }
  37324. /**
  37325. * Returns a node builder state for the given render object.
  37326. *
  37327. * @param {RenderObject} renderObject - The render object.
  37328. * @return {NodeBuilderState} The node builder state.
  37329. */
  37330. getForRender( renderObject ) {
  37331. const renderObjectData = this.get( renderObject );
  37332. let nodeBuilderState = renderObjectData.nodeBuilderState;
  37333. if ( nodeBuilderState === undefined ) {
  37334. const { nodeBuilderCache } = this;
  37335. const cacheKey = this.getForRenderCacheKey( renderObject );
  37336. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  37337. if ( nodeBuilderState === undefined ) {
  37338. const createNodeBuilder = ( material ) => {
  37339. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  37340. nodeBuilder.scene = renderObject.scene;
  37341. nodeBuilder.material = material;
  37342. nodeBuilder.camera = renderObject.camera;
  37343. nodeBuilder.context.material = material;
  37344. nodeBuilder.lightsNode = renderObject.lightsNode;
  37345. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  37346. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  37347. nodeBuilder.clippingContext = renderObject.clippingContext;
  37348. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  37349. nodeBuilder.enableMultiview();
  37350. }
  37351. return nodeBuilder;
  37352. };
  37353. let nodeBuilder = createNodeBuilder( renderObject.material );
  37354. try {
  37355. nodeBuilder.build();
  37356. } catch ( e ) {
  37357. nodeBuilder = createNodeBuilder( new NodeMaterial() );
  37358. nodeBuilder.build();
  37359. error( 'TSL: ' + e );
  37360. }
  37361. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37362. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  37363. }
  37364. nodeBuilderState.usedTimes ++;
  37365. renderObjectData.nodeBuilderState = nodeBuilderState;
  37366. }
  37367. return nodeBuilderState;
  37368. }
  37369. /**
  37370. * Deletes the given object from the internal data map
  37371. *
  37372. * @param {any} object - The object to delete.
  37373. * @return {?Object} The deleted dictionary.
  37374. */
  37375. delete( object ) {
  37376. if ( object.isRenderObject ) {
  37377. const nodeBuilderState = this.get( object ).nodeBuilderState;
  37378. nodeBuilderState.usedTimes --;
  37379. if ( nodeBuilderState.usedTimes === 0 ) {
  37380. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  37381. }
  37382. }
  37383. return super.delete( object );
  37384. }
  37385. /**
  37386. * Returns a node builder state for the given compute node.
  37387. *
  37388. * @param {Node} computeNode - The compute node.
  37389. * @return {NodeBuilderState} The node builder state.
  37390. */
  37391. getForCompute( computeNode ) {
  37392. const computeData = this.get( computeNode );
  37393. let nodeBuilderState = computeData.nodeBuilderState;
  37394. if ( nodeBuilderState === undefined ) {
  37395. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  37396. nodeBuilder.build();
  37397. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37398. computeData.nodeBuilderState = nodeBuilderState;
  37399. }
  37400. return nodeBuilderState;
  37401. }
  37402. /**
  37403. * Creates a node builder state for the given node builder.
  37404. *
  37405. * @private
  37406. * @param {NodeBuilder} nodeBuilder - The node builder.
  37407. * @return {NodeBuilderState} The node builder state.
  37408. */
  37409. _createNodeBuilderState( nodeBuilder ) {
  37410. return new NodeBuilderState(
  37411. nodeBuilder.vertexShader,
  37412. nodeBuilder.fragmentShader,
  37413. nodeBuilder.computeShader,
  37414. nodeBuilder.getAttributesArray(),
  37415. nodeBuilder.getBindings(),
  37416. nodeBuilder.updateNodes,
  37417. nodeBuilder.updateBeforeNodes,
  37418. nodeBuilder.updateAfterNodes,
  37419. nodeBuilder.observer,
  37420. nodeBuilder.transforms
  37421. );
  37422. }
  37423. /**
  37424. * Returns an environment node for the current configured
  37425. * scene environment.
  37426. *
  37427. * @param {Scene} scene - The scene.
  37428. * @return {Node} A node representing the current scene environment.
  37429. */
  37430. getEnvironmentNode( scene ) {
  37431. this.updateEnvironment( scene );
  37432. let environmentNode = null;
  37433. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  37434. environmentNode = scene.environmentNode;
  37435. } else {
  37436. const sceneData = this.get( scene );
  37437. if ( sceneData.environmentNode ) {
  37438. environmentNode = sceneData.environmentNode;
  37439. }
  37440. }
  37441. return environmentNode;
  37442. }
  37443. /**
  37444. * Returns a background node for the current configured
  37445. * scene background.
  37446. *
  37447. * @param {Scene} scene - The scene.
  37448. * @return {Node} A node representing the current scene background.
  37449. */
  37450. getBackgroundNode( scene ) {
  37451. this.updateBackground( scene );
  37452. let backgroundNode = null;
  37453. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  37454. backgroundNode = scene.backgroundNode;
  37455. } else {
  37456. const sceneData = this.get( scene );
  37457. if ( sceneData.backgroundNode ) {
  37458. backgroundNode = sceneData.backgroundNode;
  37459. }
  37460. }
  37461. return backgroundNode;
  37462. }
  37463. /**
  37464. * Returns a fog node for the current configured scene fog.
  37465. *
  37466. * @param {Scene} scene - The scene.
  37467. * @return {Node} A node representing the current scene fog.
  37468. */
  37469. getFogNode( scene ) {
  37470. this.updateFog( scene );
  37471. return scene.fogNode || this.get( scene ).fogNode || null;
  37472. }
  37473. /**
  37474. * Returns a cache key for the given scene and lights node.
  37475. * This key is used by `RenderObject` as a part of the dynamic
  37476. * cache key (a key that must be checked every time the render
  37477. * objects is drawn).
  37478. *
  37479. * @param {Scene} scene - The scene.
  37480. * @param {LightsNode} lightsNode - The lights node.
  37481. * @return {number} The cache key.
  37482. */
  37483. getCacheKey( scene, lightsNode ) {
  37484. _chainKeys$2[ 0 ] = scene;
  37485. _chainKeys$2[ 1 ] = lightsNode;
  37486. const callId = this.renderer.info.calls;
  37487. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  37488. if ( cacheKeyData.callId !== callId ) {
  37489. const environmentNode = this.getEnvironmentNode( scene );
  37490. const fogNode = this.getFogNode( scene );
  37491. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  37492. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  37493. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  37494. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  37495. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  37496. _cacheKeyValues.push( this.renderer.shadowMap.type );
  37497. cacheKeyData.callId = callId;
  37498. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  37499. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  37500. _cacheKeyValues.length = 0;
  37501. }
  37502. _chainKeys$2.length = 0;
  37503. return cacheKeyData.cacheKey;
  37504. }
  37505. /**
  37506. * A boolean that indicates whether tone mapping should be enabled
  37507. * or not.
  37508. *
  37509. * @type {boolean}
  37510. */
  37511. get isToneMappingState() {
  37512. return this.renderer.getRenderTarget() ? false : true;
  37513. }
  37514. /**
  37515. * If a scene background is configured, this method makes sure to
  37516. * represent the background with a corresponding node-based implementation.
  37517. *
  37518. * @param {Scene} scene - The scene.
  37519. */
  37520. updateBackground( scene ) {
  37521. const sceneData = this.get( scene );
  37522. const background = scene.background;
  37523. if ( background ) {
  37524. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  37525. if ( sceneData.background !== background || forceUpdate ) {
  37526. const backgroundNode = this.getCacheNode( 'background', background, () => {
  37527. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  37528. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  37529. return pmremTexture( background );
  37530. } else {
  37531. let envMap;
  37532. if ( background.isCubeTexture === true ) {
  37533. envMap = cubeTexture( background );
  37534. } else {
  37535. envMap = texture( background );
  37536. }
  37537. return cubeMapNode( envMap );
  37538. }
  37539. } else if ( background.isTexture === true ) {
  37540. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  37541. } else if ( background.isColor !== true ) {
  37542. error( 'WebGPUNodes: Unsupported background configuration.', background );
  37543. }
  37544. }, forceUpdate );
  37545. sceneData.backgroundNode = backgroundNode;
  37546. sceneData.background = background;
  37547. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  37548. }
  37549. } else if ( sceneData.backgroundNode ) {
  37550. delete sceneData.backgroundNode;
  37551. delete sceneData.background;
  37552. }
  37553. }
  37554. /**
  37555. * This method is part of the caching of nodes which are used to represents the
  37556. * scene's background, fog or environment.
  37557. *
  37558. * @param {string} type - The type of object to cache.
  37559. * @param {Object} object - The object.
  37560. * @param {Function} callback - A callback that produces a node representation for the given object.
  37561. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  37562. * @return {Node} The node representation.
  37563. */
  37564. getCacheNode( type, object, callback, forceUpdate = false ) {
  37565. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  37566. let node = nodeCache.get( object );
  37567. if ( node === undefined || forceUpdate ) {
  37568. node = callback();
  37569. nodeCache.set( object, node );
  37570. }
  37571. return node;
  37572. }
  37573. /**
  37574. * If a scene fog is configured, this method makes sure to
  37575. * represent the fog with a corresponding node-based implementation.
  37576. *
  37577. * @param {Scene} scene - The scene.
  37578. */
  37579. updateFog( scene ) {
  37580. const sceneData = this.get( scene );
  37581. const sceneFog = scene.fog;
  37582. if ( sceneFog ) {
  37583. if ( sceneData.fog !== sceneFog ) {
  37584. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  37585. if ( sceneFog.isFogExp2 ) {
  37586. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  37587. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  37588. return fog( color, densityFogFactor( density ) );
  37589. } else if ( sceneFog.isFog ) {
  37590. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  37591. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  37592. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  37593. return fog( color, rangeFogFactor( near, far ) );
  37594. } else {
  37595. error( 'Renderer: Unsupported fog configuration.', sceneFog );
  37596. }
  37597. } );
  37598. sceneData.fogNode = fogNode;
  37599. sceneData.fog = sceneFog;
  37600. }
  37601. } else {
  37602. delete sceneData.fogNode;
  37603. delete sceneData.fog;
  37604. }
  37605. }
  37606. /**
  37607. * If a scene environment is configured, this method makes sure to
  37608. * represent the environment with a corresponding node-based implementation.
  37609. *
  37610. * @param {Scene} scene - The scene.
  37611. */
  37612. updateEnvironment( scene ) {
  37613. const sceneData = this.get( scene );
  37614. const environment = scene.environment;
  37615. if ( environment ) {
  37616. if ( sceneData.environment !== environment ) {
  37617. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  37618. if ( environment.isCubeTexture === true ) {
  37619. return cubeTexture( environment );
  37620. } else if ( environment.isTexture === true ) {
  37621. return texture( environment );
  37622. } else {
  37623. error( 'Nodes: Unsupported environment configuration.', environment );
  37624. }
  37625. } );
  37626. sceneData.environmentNode = environmentNode;
  37627. sceneData.environment = environment;
  37628. }
  37629. } else if ( sceneData.environmentNode ) {
  37630. delete sceneData.environmentNode;
  37631. delete sceneData.environment;
  37632. }
  37633. }
  37634. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  37635. const nodeFrame = this.nodeFrame;
  37636. nodeFrame.renderer = renderer;
  37637. nodeFrame.scene = scene;
  37638. nodeFrame.object = object;
  37639. nodeFrame.camera = camera;
  37640. nodeFrame.material = material;
  37641. return nodeFrame;
  37642. }
  37643. getNodeFrameForRender( renderObject ) {
  37644. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  37645. }
  37646. /**
  37647. * Returns the current output cache key.
  37648. *
  37649. * @return {string} The output cache key.
  37650. */
  37651. getOutputCacheKey() {
  37652. const renderer = this.renderer;
  37653. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  37654. }
  37655. /**
  37656. * Checks if the output configuration (tone mapping and color space) for
  37657. * the given target has changed.
  37658. *
  37659. * @param {Texture} outputTarget - The output target.
  37660. * @return {boolean} Whether the output configuration has changed or not.
  37661. */
  37662. hasOutputChange( outputTarget ) {
  37663. const cacheKey = _outputNodeMap.get( outputTarget );
  37664. return cacheKey !== this.getOutputCacheKey();
  37665. }
  37666. /**
  37667. * Returns a node that represents the output configuration (tone mapping and
  37668. * color space) for the current target.
  37669. *
  37670. * @param {Texture} outputTarget - The output target.
  37671. * @return {Node} The output node.
  37672. */
  37673. getOutputNode( outputTarget ) {
  37674. const renderer = this.renderer;
  37675. const cacheKey = this.getOutputCacheKey();
  37676. const output = outputTarget.isArrayTexture ?
  37677. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  37678. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  37679. _outputNodeMap.set( outputTarget, cacheKey );
  37680. return output;
  37681. }
  37682. /**
  37683. * Triggers the call of `updateBefore()` methods
  37684. * for all nodes of the given render object.
  37685. *
  37686. * @param {RenderObject} renderObject - The render object.
  37687. */
  37688. updateBefore( renderObject ) {
  37689. const nodeBuilder = renderObject.getNodeBuilderState();
  37690. for ( const node of nodeBuilder.updateBeforeNodes ) {
  37691. // update frame state for each node
  37692. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  37693. }
  37694. }
  37695. /**
  37696. * Triggers the call of `updateAfter()` methods
  37697. * for all nodes of the given render object.
  37698. *
  37699. * @param {RenderObject} renderObject - The render object.
  37700. */
  37701. updateAfter( renderObject ) {
  37702. const nodeBuilder = renderObject.getNodeBuilderState();
  37703. for ( const node of nodeBuilder.updateAfterNodes ) {
  37704. // update frame state for each node
  37705. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  37706. }
  37707. }
  37708. /**
  37709. * Triggers the call of `update()` methods
  37710. * for all nodes of the given compute node.
  37711. *
  37712. * @param {Node} computeNode - The compute node.
  37713. */
  37714. updateForCompute( computeNode ) {
  37715. const nodeFrame = this.getNodeFrame();
  37716. const nodeBuilder = this.getForCompute( computeNode );
  37717. for ( const node of nodeBuilder.updateNodes ) {
  37718. nodeFrame.updateNode( node );
  37719. }
  37720. }
  37721. /**
  37722. * Triggers the call of `update()` methods
  37723. * for all nodes of the given compute node.
  37724. *
  37725. * @param {RenderObject} renderObject - The render object.
  37726. */
  37727. updateForRender( renderObject ) {
  37728. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37729. const nodeBuilder = renderObject.getNodeBuilderState();
  37730. for ( const node of nodeBuilder.updateNodes ) {
  37731. nodeFrame.updateNode( node );
  37732. }
  37733. }
  37734. /**
  37735. * Returns `true` if the given render object requires a refresh.
  37736. *
  37737. * @param {RenderObject} renderObject - The render object.
  37738. * @return {boolean} Whether the given render object requires a refresh or not.
  37739. */
  37740. needsRefresh( renderObject ) {
  37741. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37742. const monitor = renderObject.getMonitor();
  37743. return monitor.needsRefresh( renderObject, nodeFrame );
  37744. }
  37745. /**
  37746. * Frees the internal resources.
  37747. */
  37748. dispose() {
  37749. super.dispose();
  37750. this.nodeFrame = new NodeFrame();
  37751. this.nodeBuilderCache = new Map();
  37752. this.cacheLib = {};
  37753. }
  37754. }
  37755. const _plane = /*@__PURE__*/ new Plane();
  37756. /**
  37757. * Represents the state that is used to perform clipping via clipping planes.
  37758. * There is a default clipping context for each render context. When the
  37759. * scene holds instances of `ClippingGroup`, there will be a context for each
  37760. * group.
  37761. *
  37762. * @private
  37763. */
  37764. class ClippingContext {
  37765. /**
  37766. * Constructs a new clipping context.
  37767. *
  37768. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  37769. */
  37770. constructor( parentContext = null ) {
  37771. /**
  37772. * The clipping context's version.
  37773. *
  37774. * @type {number}
  37775. * @readonly
  37776. */
  37777. this.version = 0;
  37778. /**
  37779. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  37780. *
  37781. * @type {?boolean}
  37782. * @default null
  37783. */
  37784. this.clipIntersection = null;
  37785. /**
  37786. * The clipping context's cache key.
  37787. *
  37788. * @type {string}
  37789. */
  37790. this.cacheKey = '';
  37791. /**
  37792. * Whether the shadow pass is active or not.
  37793. *
  37794. * @type {boolean}
  37795. * @default false
  37796. */
  37797. this.shadowPass = false;
  37798. /**
  37799. * The view normal matrix.
  37800. *
  37801. * @type {Matrix3}
  37802. */
  37803. this.viewNormalMatrix = new Matrix3();
  37804. /**
  37805. * Internal cache for maintaining clipping contexts.
  37806. *
  37807. * @type {WeakMap<ClippingGroup,ClippingContext>}
  37808. */
  37809. this.clippingGroupContexts = new WeakMap();
  37810. /**
  37811. * The intersection planes.
  37812. *
  37813. * @type {Array<Vector4>}
  37814. */
  37815. this.intersectionPlanes = [];
  37816. /**
  37817. * The intersection planes.
  37818. *
  37819. * @type {Array<Vector4>}
  37820. */
  37821. this.unionPlanes = [];
  37822. /**
  37823. * The version of the clipping context's parent context.
  37824. *
  37825. * @type {?number}
  37826. * @readonly
  37827. */
  37828. this.parentVersion = null;
  37829. if ( parentContext !== null ) {
  37830. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  37831. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  37832. this.shadowPass = parentContext.shadowPass;
  37833. this.viewMatrix = parentContext.viewMatrix;
  37834. }
  37835. }
  37836. /**
  37837. * Projects the given source clipping planes and writes the result into the
  37838. * destination array.
  37839. *
  37840. * @param {Array<Plane>} source - The source clipping planes.
  37841. * @param {Array<Vector4>} destination - The destination.
  37842. * @param {number} offset - The offset.
  37843. */
  37844. projectPlanes( source, destination, offset ) {
  37845. const l = source.length;
  37846. for ( let i = 0; i < l; i ++ ) {
  37847. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  37848. const v = destination[ offset + i ];
  37849. const normal = _plane.normal;
  37850. v.x = - normal.x;
  37851. v.y = - normal.y;
  37852. v.z = - normal.z;
  37853. v.w = _plane.constant;
  37854. }
  37855. }
  37856. /**
  37857. * Updates the root clipping context of a scene.
  37858. *
  37859. * @param {Scene} scene - The scene.
  37860. * @param {Camera} camera - The camera that is used to render the scene.
  37861. */
  37862. updateGlobal( scene, camera ) {
  37863. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  37864. this.viewMatrix = camera.matrixWorldInverse;
  37865. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  37866. }
  37867. /**
  37868. * Updates the clipping context.
  37869. *
  37870. * @param {ClippingContext} parentContext - The parent context.
  37871. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  37872. */
  37873. update( parentContext, clippingGroup ) {
  37874. let update = false;
  37875. if ( parentContext.version !== this.parentVersion ) {
  37876. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  37877. this.unionPlanes = Array.from( parentContext.unionPlanes );
  37878. this.parentVersion = parentContext.version;
  37879. }
  37880. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  37881. this.clipIntersection = clippingGroup.clipIntersection;
  37882. if ( this.clipIntersection ) {
  37883. this.unionPlanes.length = parentContext.unionPlanes.length;
  37884. } else {
  37885. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  37886. }
  37887. }
  37888. const srcClippingPlanes = clippingGroup.clippingPlanes;
  37889. const l = srcClippingPlanes.length;
  37890. let dstClippingPlanes;
  37891. let offset;
  37892. if ( this.clipIntersection ) {
  37893. dstClippingPlanes = this.intersectionPlanes;
  37894. offset = parentContext.intersectionPlanes.length;
  37895. } else {
  37896. dstClippingPlanes = this.unionPlanes;
  37897. offset = parentContext.unionPlanes.length;
  37898. }
  37899. if ( dstClippingPlanes.length !== offset + l ) {
  37900. dstClippingPlanes.length = offset + l;
  37901. for ( let i = 0; i < l; i ++ ) {
  37902. dstClippingPlanes[ offset + i ] = new Vector4();
  37903. }
  37904. update = true;
  37905. }
  37906. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  37907. if ( update ) {
  37908. this.version ++;
  37909. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  37910. }
  37911. }
  37912. /**
  37913. * Returns a clipping context for the given clipping group.
  37914. *
  37915. * @param {ClippingGroup} clippingGroup - The clipping group.
  37916. * @return {ClippingContext} The clipping context.
  37917. */
  37918. getGroupContext( clippingGroup ) {
  37919. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  37920. let context = this.clippingGroupContexts.get( clippingGroup );
  37921. if ( context === undefined ) {
  37922. context = new ClippingContext( this );
  37923. this.clippingGroupContexts.set( clippingGroup, context );
  37924. }
  37925. context.update( this, clippingGroup );
  37926. return context;
  37927. }
  37928. /**
  37929. * The count of union clipping planes.
  37930. *
  37931. * @type {number}
  37932. * @readonly
  37933. */
  37934. get unionClippingCount() {
  37935. return this.unionPlanes.length;
  37936. }
  37937. }
  37938. /**
  37939. * This module is used to represent render bundles inside the renderer
  37940. * for further processing.
  37941. *
  37942. * @private
  37943. */
  37944. class RenderBundle {
  37945. /**
  37946. * Constructs a new bundle group.
  37947. *
  37948. * @param {BundleGroup} bundleGroup - The bundle group.
  37949. * @param {Camera} camera - The camera the bundle group is rendered with.
  37950. */
  37951. constructor( bundleGroup, camera ) {
  37952. this.bundleGroup = bundleGroup;
  37953. this.camera = camera;
  37954. }
  37955. }
  37956. const _chainKeys$1 = [];
  37957. /**
  37958. * This renderer module manages render bundles.
  37959. *
  37960. * @private
  37961. */
  37962. class RenderBundles {
  37963. /**
  37964. * Constructs a new render bundle management component.
  37965. */
  37966. constructor() {
  37967. /**
  37968. * A chain map for maintaining the render bundles.
  37969. *
  37970. * @type {ChainMap}
  37971. */
  37972. this.bundles = new ChainMap();
  37973. }
  37974. /**
  37975. * Returns a render bundle for the given bundle group and camera.
  37976. *
  37977. * @param {BundleGroup} bundleGroup - The bundle group.
  37978. * @param {Camera} camera - The camera the bundle group is rendered with.
  37979. * @return {RenderBundle} The render bundle.
  37980. */
  37981. get( bundleGroup, camera ) {
  37982. const bundles = this.bundles;
  37983. _chainKeys$1[ 0 ] = bundleGroup;
  37984. _chainKeys$1[ 1 ] = camera;
  37985. let bundle = bundles.get( _chainKeys$1 );
  37986. if ( bundle === undefined ) {
  37987. bundle = new RenderBundle( bundleGroup, camera );
  37988. bundles.set( _chainKeys$1, bundle );
  37989. }
  37990. _chainKeys$1.length = 0;
  37991. return bundle;
  37992. }
  37993. /**
  37994. * Frees all internal resources.
  37995. */
  37996. dispose() {
  37997. this.bundles = new ChainMap();
  37998. }
  37999. }
  38000. /**
  38001. * The purpose of a node library is to assign node implementations
  38002. * to existing library features. In `WebGPURenderer` lights, materials
  38003. * which are not based on `NodeMaterial` as well as tone mapping techniques
  38004. * are implemented with node-based modules.
  38005. *
  38006. * @private
  38007. */
  38008. class NodeLibrary {
  38009. /**
  38010. * Constructs a new node library.
  38011. */
  38012. constructor() {
  38013. /**
  38014. * A weak map that maps lights to light nodes.
  38015. *
  38016. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  38017. */
  38018. this.lightNodes = new WeakMap();
  38019. /**
  38020. * A map that maps materials to node materials.
  38021. *
  38022. * @type {Map<string,NodeMaterial.constructor>}
  38023. */
  38024. this.materialNodes = new Map();
  38025. /**
  38026. * A map that maps tone mapping techniques (constants)
  38027. * to tone mapping node functions.
  38028. *
  38029. * @type {Map<number,Function>}
  38030. */
  38031. this.toneMappingNodes = new Map();
  38032. }
  38033. /**
  38034. * Returns a matching node material instance for the given material object.
  38035. *
  38036. * This method also assigns/copies the properties of the given material object
  38037. * to the node material. This is done to make sure the current material
  38038. * configuration carries over to the node version.
  38039. *
  38040. * @param {Material} material - A material.
  38041. * @return {NodeMaterial} The corresponding node material.
  38042. */
  38043. fromMaterial( material ) {
  38044. if ( material.isNodeMaterial ) return material;
  38045. let nodeMaterial = null;
  38046. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  38047. if ( nodeMaterialClass !== null ) {
  38048. nodeMaterial = new nodeMaterialClass();
  38049. for ( const key in material ) {
  38050. nodeMaterial[ key ] = material[ key ];
  38051. }
  38052. }
  38053. return nodeMaterial;
  38054. }
  38055. /**
  38056. * Adds a tone mapping node function for a tone mapping technique (constant).
  38057. *
  38058. * @param {Function} toneMappingNode - The tone mapping node function.
  38059. * @param {number} toneMapping - The tone mapping.
  38060. */
  38061. addToneMapping( toneMappingNode, toneMapping ) {
  38062. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  38063. }
  38064. /**
  38065. * Returns a tone mapping node function for a tone mapping technique (constant).
  38066. *
  38067. * @param {number} toneMapping - The tone mapping.
  38068. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  38069. */
  38070. getToneMappingFunction( toneMapping ) {
  38071. return this.toneMappingNodes.get( toneMapping ) || null;
  38072. }
  38073. /**
  38074. * Returns a node material class definition for a material type.
  38075. *
  38076. * @param {string} materialType - The material type.
  38077. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  38078. */
  38079. getMaterialNodeClass( materialType ) {
  38080. return this.materialNodes.get( materialType ) || null;
  38081. }
  38082. /**
  38083. * Adds a node material class definition for a given material type.
  38084. *
  38085. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  38086. * @param {string} materialClassType - The material type.
  38087. */
  38088. addMaterial( materialNodeClass, materialClassType ) {
  38089. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  38090. }
  38091. /**
  38092. * Returns a light node class definition for a light class definition.
  38093. *
  38094. * @param {Light.constructor} light - The light class definition.
  38095. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  38096. */
  38097. getLightNodeClass( light ) {
  38098. return this.lightNodes.get( light ) || null;
  38099. }
  38100. /**
  38101. * Adds a light node class definition for a given light class definition.
  38102. *
  38103. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  38104. * @param {Light.constructor} lightClass - The light class definition.
  38105. */
  38106. addLight( lightNodeClass, lightClass ) {
  38107. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  38108. }
  38109. /**
  38110. * Adds a node class definition for the given type to the provided type library.
  38111. *
  38112. * @param {Node.constructor} nodeClass - The node class definition.
  38113. * @param {number|string} type - The object type.
  38114. * @param {Map<number|string,Node.constructor>} library - The type library.
  38115. */
  38116. addType( nodeClass, type, library ) {
  38117. if ( library.has( type ) ) {
  38118. warn( `Redefinition of node ${ type }` );
  38119. return;
  38120. }
  38121. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  38122. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  38123. library.set( type, nodeClass );
  38124. }
  38125. /**
  38126. * Adds a node class definition for the given class definition to the provided type library.
  38127. *
  38128. * @param {Node.constructor} nodeClass - The node class definition.
  38129. * @param {Node.constructor} baseClass - The class definition.
  38130. * @param {WeakMap<Node.constructor, Node.constructor>} library - The type library.
  38131. */
  38132. addClass( nodeClass, baseClass, library ) {
  38133. if ( library.has( baseClass ) ) {
  38134. warn( `Redefinition of node ${ baseClass.name }` );
  38135. return;
  38136. }
  38137. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  38138. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  38139. library.set( baseClass, nodeClass );
  38140. }
  38141. }
  38142. const _defaultLights = /*@__PURE__*/ new LightsNode();
  38143. const _chainKeys = [];
  38144. /**
  38145. * This renderer module manages the lights nodes which are unique
  38146. * per scene and camera combination.
  38147. *
  38148. * The lights node itself is later configured in the render list
  38149. * with the actual lights from the scene.
  38150. *
  38151. * @private
  38152. * @augments ChainMap
  38153. */
  38154. class Lighting extends ChainMap {
  38155. /**
  38156. * Constructs a lighting management component.
  38157. */
  38158. constructor() {
  38159. super();
  38160. }
  38161. /**
  38162. * Creates a new lights node for the given array of lights.
  38163. *
  38164. * @param {Array<Light>} lights - The render object.
  38165. * @return {LightsNode} The lights node.
  38166. */
  38167. createNode( lights = [] ) {
  38168. return new LightsNode().setLights( lights );
  38169. }
  38170. /**
  38171. * Returns a lights node for the given scene and camera.
  38172. *
  38173. * @param {Scene} scene - The scene.
  38174. * @param {Camera} camera - The camera.
  38175. * @return {LightsNode} The lights node.
  38176. */
  38177. getNode( scene, camera ) {
  38178. // ignore post-processing
  38179. if ( scene.isQuadMesh ) return _defaultLights;
  38180. _chainKeys[ 0 ] = scene;
  38181. _chainKeys[ 1 ] = camera;
  38182. let node = this.get( _chainKeys );
  38183. if ( node === undefined ) {
  38184. node = this.createNode();
  38185. this.set( _chainKeys, node );
  38186. }
  38187. _chainKeys.length = 0;
  38188. return node;
  38189. }
  38190. }
  38191. /**
  38192. * A special type of render target that is used when rendering
  38193. * with the WebXR Device API.
  38194. *
  38195. * @private
  38196. * @augments RenderTarget
  38197. */
  38198. class XRRenderTarget extends RenderTarget {
  38199. /**
  38200. * Constructs a new XR render target.
  38201. *
  38202. * @param {number} [width=1] - The width of the render target.
  38203. * @param {number} [height=1] - The height of the render target.
  38204. * @param {Object} [options={}] - The configuration options.
  38205. */
  38206. constructor( width = 1, height = 1, options = {} ) {
  38207. super( width, height, options );
  38208. /**
  38209. * This flag can be used for type testing.
  38210. *
  38211. * @type {boolean}
  38212. * @readonly
  38213. * @default true
  38214. */
  38215. this.isXRRenderTarget = true;
  38216. /**
  38217. * Whether the attachments of the render target
  38218. * are defined by external textures. This flag is
  38219. * set to `true` when using the WebXR Layers API.
  38220. *
  38221. * @private
  38222. * @type {boolean}
  38223. * @default false
  38224. */
  38225. this._hasExternalTextures = false;
  38226. /**
  38227. * Whether a depth buffer should automatically be allocated
  38228. * for this XR render target or not.
  38229. *
  38230. * Allocating a depth buffer is the default behavior of XR render
  38231. * targets. However, when using the WebXR Layers API, this flag
  38232. * must be set to `false` when the `ignoreDepthValues` property of
  38233. * the projection layers evaluates to `false`.
  38234. *
  38235. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  38236. *
  38237. * @private
  38238. * @type {boolean}
  38239. * @default true
  38240. */
  38241. this._autoAllocateDepthBuffer = true;
  38242. /**
  38243. * Whether this render target is associated with a XRWebGLLayer.
  38244. *
  38245. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  38246. * this means that you don't have access to its bound color,
  38247. * stencil and depth buffers. We need to handle this framebuffer
  38248. * differently since its textures are always bound.
  38249. *
  38250. * @private
  38251. * @type {boolean}
  38252. * @default false
  38253. * */
  38254. this._isOpaqueFramebuffer = false;
  38255. }
  38256. copy( source ) {
  38257. super.copy( source );
  38258. this._hasExternalTextures = source._hasExternalTextures;
  38259. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  38260. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  38261. return this;
  38262. }
  38263. }
  38264. const _cameraLPos = /*@__PURE__*/ new Vector3();
  38265. const _cameraRPos = /*@__PURE__*/ new Vector3();
  38266. /**
  38267. * The XR manager is built on top of the WebXR Device API to
  38268. * manage XR sessions with `WebGPURenderer`.
  38269. *
  38270. * XR is currently only supported with a WebGL 2 backend.
  38271. *
  38272. * @augments EventDispatcher
  38273. */
  38274. class XRManager extends EventDispatcher {
  38275. /**
  38276. * Constructs a new XR manager.
  38277. *
  38278. * @param {Renderer} renderer - The renderer.
  38279. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  38280. */
  38281. constructor( renderer, multiview = false ) {
  38282. super();
  38283. /**
  38284. * This flag globally enables XR rendering.
  38285. *
  38286. * @type {boolean}
  38287. * @default false
  38288. */
  38289. this.enabled = false;
  38290. /**
  38291. * Whether the XR device is currently presenting or not.
  38292. *
  38293. * @type {boolean}
  38294. * @default false
  38295. * @readonly
  38296. */
  38297. this.isPresenting = false;
  38298. /**
  38299. * Whether the XR camera should automatically be updated or not.
  38300. *
  38301. * @type {boolean}
  38302. * @default true
  38303. */
  38304. this.cameraAutoUpdate = true;
  38305. /**
  38306. * The renderer.
  38307. *
  38308. * @private
  38309. * @type {Renderer}
  38310. */
  38311. this._renderer = renderer;
  38312. // camera
  38313. /**
  38314. * Represents the camera for the left eye.
  38315. *
  38316. * @private
  38317. * @type {PerspectiveCamera}
  38318. */
  38319. this._cameraL = new PerspectiveCamera();
  38320. this._cameraL.viewport = new Vector4();
  38321. /**
  38322. * Represents the camera for the right eye.
  38323. *
  38324. * @private
  38325. * @type {PerspectiveCamera}
  38326. */
  38327. this._cameraR = new PerspectiveCamera();
  38328. this._cameraR.viewport = new Vector4();
  38329. /**
  38330. * A list of cameras used for rendering the XR views.
  38331. *
  38332. * @private
  38333. * @type {Array<Camera>}
  38334. */
  38335. this._cameras = [ this._cameraL, this._cameraR ];
  38336. /**
  38337. * The main XR camera.
  38338. *
  38339. * @private
  38340. * @type {ArrayCamera}
  38341. */
  38342. this._cameraXR = new ArrayCamera();
  38343. /**
  38344. * The current near value of the XR camera.
  38345. *
  38346. * @private
  38347. * @type {?number}
  38348. * @default null
  38349. */
  38350. this._currentDepthNear = null;
  38351. /**
  38352. * The current far value of the XR camera.
  38353. *
  38354. * @private
  38355. * @type {?number}
  38356. * @default null
  38357. */
  38358. this._currentDepthFar = null;
  38359. /**
  38360. * A list of WebXR controllers requested by the application.
  38361. *
  38362. * @private
  38363. * @type {Array<WebXRController>}
  38364. */
  38365. this._controllers = [];
  38366. /**
  38367. * A list of XR input source. Each input source belongs to
  38368. * an instance of WebXRController.
  38369. *
  38370. * @private
  38371. * @type {Array<XRInputSource?>}
  38372. */
  38373. this._controllerInputSources = [];
  38374. /**
  38375. * The XR render target that represents the rendering destination
  38376. * during an active XR session.
  38377. *
  38378. * @private
  38379. * @type {?RenderTarget}
  38380. * @default null
  38381. */
  38382. this._xrRenderTarget = null;
  38383. /**
  38384. * An array holding all the non-projection layers
  38385. *
  38386. * @private
  38387. * @type {Array<Object>}
  38388. * @default []
  38389. */
  38390. this._layers = [];
  38391. /**
  38392. * Whether the XR session uses layers.
  38393. *
  38394. * @type {boolean}
  38395. * @default false
  38396. */
  38397. this._sessionUsesLayers = false;
  38398. /**
  38399. * Whether the device supports binding gl objects.
  38400. *
  38401. * @private
  38402. * @type {boolean}
  38403. * @readonly
  38404. */
  38405. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  38406. this._frameBufferTargets = null;
  38407. /**
  38408. * Helper function to create native WebXR Layer.
  38409. *
  38410. * @private
  38411. * @type {Function}
  38412. */
  38413. this._createXRLayer = createXRLayer.bind( this );
  38414. /**
  38415. * The current WebGL context.
  38416. *
  38417. * @private
  38418. * @type {?WebGL2RenderingContext}
  38419. * @default null
  38420. */
  38421. this._gl = null;
  38422. /**
  38423. * The current animation context.
  38424. *
  38425. * @private
  38426. * @type {?Window}
  38427. * @default null
  38428. */
  38429. this._currentAnimationContext = null;
  38430. /**
  38431. * The current animation loop.
  38432. *
  38433. * @private
  38434. * @type {?Function}
  38435. * @default null
  38436. */
  38437. this._currentAnimationLoop = null;
  38438. /**
  38439. * The current pixel ratio.
  38440. *
  38441. * @private
  38442. * @type {?number}
  38443. * @default null
  38444. */
  38445. this._currentPixelRatio = null;
  38446. /**
  38447. * The current size of the renderer's canvas
  38448. * in logical pixel unit.
  38449. *
  38450. * @private
  38451. * @type {Vector2}
  38452. */
  38453. this._currentSize = new Vector2();
  38454. /**
  38455. * The default event listener for handling events inside a XR session.
  38456. *
  38457. * @private
  38458. * @type {Function}
  38459. */
  38460. this._onSessionEvent = onSessionEvent.bind( this );
  38461. /**
  38462. * The event listener for handling the end of a XR session.
  38463. *
  38464. * @private
  38465. * @type {Function}
  38466. */
  38467. this._onSessionEnd = onSessionEnd.bind( this );
  38468. /**
  38469. * The event listener for handling the `inputsourceschange` event.
  38470. *
  38471. * @private
  38472. * @type {Function}
  38473. */
  38474. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  38475. /**
  38476. * The animation loop which is used as a replacement for the default
  38477. * animation loop of the application. It is only used when a XR session
  38478. * is active.
  38479. *
  38480. * @private
  38481. * @type {Function}
  38482. */
  38483. this._onAnimationFrame = onAnimationFrame.bind( this );
  38484. /**
  38485. * The current XR reference space.
  38486. *
  38487. * @private
  38488. * @type {?XRReferenceSpace}
  38489. * @default null
  38490. */
  38491. this._referenceSpace = null;
  38492. /**
  38493. * The current XR reference space type.
  38494. *
  38495. * @private
  38496. * @type {XRReferenceSpaceType}
  38497. * @default 'local-floor'
  38498. */
  38499. this._referenceSpaceType = 'local-floor';
  38500. /**
  38501. * A custom reference space defined by the application.
  38502. *
  38503. * @private
  38504. * @type {?XRReferenceSpace}
  38505. * @default null
  38506. */
  38507. this._customReferenceSpace = null;
  38508. /**
  38509. * The framebuffer scale factor.
  38510. *
  38511. * @private
  38512. * @type {number}
  38513. * @default 1
  38514. */
  38515. this._framebufferScaleFactor = 1;
  38516. /**
  38517. * The foveation factor.
  38518. *
  38519. * @private
  38520. * @type {number}
  38521. * @default 1
  38522. */
  38523. this._foveation = 1.0;
  38524. /**
  38525. * A reference to the current XR session.
  38526. *
  38527. * @private
  38528. * @type {?XRSession}
  38529. * @default null
  38530. */
  38531. this._session = null;
  38532. /**
  38533. * A reference to the current XR base layer.
  38534. *
  38535. * @private
  38536. * @type {?XRWebGLLayer}
  38537. * @default null
  38538. */
  38539. this._glBaseLayer = null;
  38540. /**
  38541. * A reference to the current XR binding.
  38542. *
  38543. * @private
  38544. * @type {?XRWebGLBinding}
  38545. * @default null
  38546. */
  38547. this._glBinding = null;
  38548. /**
  38549. * A reference to the current XR projection layer.
  38550. *
  38551. * @private
  38552. * @type {?XRProjectionLayer}
  38553. * @default null
  38554. */
  38555. this._glProjLayer = null;
  38556. /**
  38557. * A reference to the current XR frame.
  38558. *
  38559. * @private
  38560. * @type {?XRFrame}
  38561. * @default null
  38562. */
  38563. this._xrFrame = null;
  38564. /**
  38565. * Whether the browser supports the APIs necessary to use XRProjectionLayers.
  38566. *
  38567. * Note: this does not represent XRSession explicitly requesting
  38568. * `'layers'` as a feature - see `_sessionUsesLayers` and #30112
  38569. *
  38570. * @private
  38571. * @type {boolean}
  38572. * @readonly
  38573. */
  38574. this._supportsLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  38575. /**
  38576. * Whether the usage of multiview has been requested by the application or not.
  38577. *
  38578. * @private
  38579. * @type {boolean}
  38580. * @default false
  38581. * @readonly
  38582. */
  38583. this._useMultiviewIfPossible = multiview;
  38584. /**
  38585. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  38586. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  38587. *
  38588. * @private
  38589. * @type {boolean}
  38590. * @readonly
  38591. */
  38592. this._useMultiview = false;
  38593. }
  38594. /**
  38595. * Returns an instance of `THREE.Group` that represents the transformation
  38596. * of a XR controller in target ray space. The requested controller is defined
  38597. * by the given index.
  38598. *
  38599. * @param {number} index - The index of the XR controller.
  38600. * @return {Group} A group that represents the controller's transformation.
  38601. */
  38602. getController( index ) {
  38603. const controller = this._getController( index );
  38604. return controller.getTargetRaySpace();
  38605. }
  38606. /**
  38607. * Returns an instance of `THREE.Group` that represents the transformation
  38608. * of a XR controller in grip space. The requested controller is defined
  38609. * by the given index.
  38610. *
  38611. * @param {number} index - The index of the XR controller.
  38612. * @return {Group} A group that represents the controller's transformation.
  38613. */
  38614. getControllerGrip( index ) {
  38615. const controller = this._getController( index );
  38616. return controller.getGripSpace();
  38617. }
  38618. /**
  38619. * Returns an instance of `THREE.Group` that represents the transformation
  38620. * of a XR controller in hand space. The requested controller is defined
  38621. * by the given index.
  38622. *
  38623. * @param {number} index - The index of the XR controller.
  38624. * @return {Group} A group that represents the controller's transformation.
  38625. */
  38626. getHand( index ) {
  38627. const controller = this._getController( index );
  38628. return controller.getHandSpace();
  38629. }
  38630. /**
  38631. * Returns the foveation value.
  38632. *
  38633. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  38634. */
  38635. getFoveation() {
  38636. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  38637. return undefined;
  38638. }
  38639. return this._foveation;
  38640. }
  38641. /**
  38642. * Sets the foveation value.
  38643. *
  38644. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  38645. * and `1` means maximum foveation (the edges render at lower resolution).
  38646. */
  38647. setFoveation( foveation ) {
  38648. this._foveation = foveation;
  38649. if ( this._glProjLayer !== null ) {
  38650. this._glProjLayer.fixedFoveation = foveation;
  38651. }
  38652. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  38653. this._glBaseLayer.fixedFoveation = foveation;
  38654. }
  38655. }
  38656. /**
  38657. * Returns the framebuffer scale factor.
  38658. *
  38659. * @return {number} The framebuffer scale factor.
  38660. */
  38661. getFramebufferScaleFactor() {
  38662. return this._framebufferScaleFactor;
  38663. }
  38664. /**
  38665. * Sets the framebuffer scale factor.
  38666. *
  38667. * This method can not be used during a XR session.
  38668. *
  38669. * @param {number} factor - The framebuffer scale factor.
  38670. */
  38671. setFramebufferScaleFactor( factor ) {
  38672. this._framebufferScaleFactor = factor;
  38673. if ( this.isPresenting === true ) {
  38674. warn( 'XRManager: Cannot change framebuffer scale while presenting.' );
  38675. }
  38676. }
  38677. /**
  38678. * Returns the reference space type.
  38679. *
  38680. * @return {XRReferenceSpaceType} The reference space type.
  38681. */
  38682. getReferenceSpaceType() {
  38683. return this._referenceSpaceType;
  38684. }
  38685. /**
  38686. * Sets the reference space type.
  38687. *
  38688. * This method can not be used during a XR session.
  38689. *
  38690. * @param {XRReferenceSpaceType} type - The reference space type.
  38691. */
  38692. setReferenceSpaceType( type ) {
  38693. this._referenceSpaceType = type;
  38694. if ( this.isPresenting === true ) {
  38695. warn( 'XRManager: Cannot change reference space type while presenting.' );
  38696. }
  38697. }
  38698. /**
  38699. * Returns the XR reference space.
  38700. *
  38701. * @return {XRReferenceSpace} The XR reference space.
  38702. */
  38703. getReferenceSpace() {
  38704. return this._customReferenceSpace || this._referenceSpace;
  38705. }
  38706. /**
  38707. * Sets a custom XR reference space.
  38708. *
  38709. * @param {XRReferenceSpace} space - The XR reference space.
  38710. */
  38711. setReferenceSpace( space ) {
  38712. this._customReferenceSpace = space;
  38713. }
  38714. /**
  38715. * Returns the XR camera.
  38716. *
  38717. * @return {ArrayCamera} The XR camera.
  38718. */
  38719. getCamera() {
  38720. return this._cameraXR;
  38721. }
  38722. /**
  38723. * Returns the environment blend mode from the current XR session.
  38724. *
  38725. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  38726. */
  38727. getEnvironmentBlendMode() {
  38728. if ( this._session !== null ) {
  38729. return this._session.environmentBlendMode;
  38730. }
  38731. }
  38732. /**
  38733. * Returns the current XR binding.
  38734. *
  38735. * Creates a new binding if needed and the browser is
  38736. * capable of doing so.
  38737. *
  38738. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  38739. */
  38740. getBinding() {
  38741. if ( this._glBinding === null && this._supportsGlBinding ) {
  38742. this._glBinding = new XRWebGLBinding( this._session, this._gl );
  38743. }
  38744. return this._glBinding;
  38745. }
  38746. /**
  38747. * Returns the current XR frame.
  38748. *
  38749. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  38750. */
  38751. getFrame() {
  38752. return this._xrFrame;
  38753. }
  38754. /**
  38755. * Returns `true` if the engine renders to a multiview target.
  38756. *
  38757. * @return {boolean} Whether the engine renders to a multiview render target or not.
  38758. */
  38759. useMultiview() {
  38760. return this._useMultiview;
  38761. }
  38762. /**
  38763. * This method can be used in XR applications to create a quadratic layer that presents a separate
  38764. * rendered scene.
  38765. *
  38766. * @param {number} width - The width of the layer plane in world units.
  38767. * @param {number} height - The height of the layer plane in world units.
  38768. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  38769. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  38770. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  38771. * @param {number} pixelheight - The height of the layer's render target in pixels.
  38772. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  38773. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  38774. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  38775. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  38776. */
  38777. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  38778. const geometry = new PlaneGeometry( width, height );
  38779. const renderTarget = new XRRenderTarget(
  38780. pixelwidth,
  38781. pixelheight,
  38782. {
  38783. format: RGBAFormat,
  38784. type: UnsignedByteType,
  38785. depthTexture: new DepthTexture(
  38786. pixelwidth,
  38787. pixelheight,
  38788. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  38789. undefined,
  38790. undefined,
  38791. undefined,
  38792. undefined,
  38793. undefined,
  38794. undefined,
  38795. attributes.stencil ? DepthStencilFormat : DepthFormat
  38796. ),
  38797. stencilBuffer: attributes.stencil,
  38798. resolveDepthBuffer: false,
  38799. resolveStencilBuffer: false
  38800. } );
  38801. renderTarget._autoAllocateDepthBuffer = true;
  38802. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  38803. material.map = renderTarget.texture;
  38804. material.map.offset.y = 1;
  38805. material.map.repeat.y = -1;
  38806. const plane = new Mesh( geometry, material );
  38807. plane.position.copy( translation );
  38808. plane.quaternion.copy( quaternion );
  38809. const layer = {
  38810. type: 'quad',
  38811. width: width,
  38812. height: height,
  38813. translation: translation,
  38814. quaternion: quaternion,
  38815. pixelwidth: pixelwidth,
  38816. pixelheight: pixelheight,
  38817. plane: plane,
  38818. material: material,
  38819. rendercall: rendercall,
  38820. renderTarget: renderTarget };
  38821. this._layers.push( layer );
  38822. if ( this._session !== null ) {
  38823. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  38824. layer.plane.material.blending = CustomBlending;
  38825. layer.plane.material.blendEquation = AddEquation;
  38826. layer.plane.material.blendSrc = ZeroFactor;
  38827. layer.plane.material.blendDst = ZeroFactor;
  38828. layer.xrlayer = this._createXRLayer( layer );
  38829. const xrlayers = this._session.renderState.layers;
  38830. xrlayers.unshift( layer.xrlayer );
  38831. this._session.updateRenderState( { layers: xrlayers } );
  38832. } else {
  38833. renderTarget.isXRRenderTarget = false;
  38834. }
  38835. return plane;
  38836. }
  38837. /**
  38838. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  38839. * rendered scene.
  38840. *
  38841. * @param {number} radius - The radius of the cylinder in world units.
  38842. * @param {number} centralAngle - The central angle of the cylinder in radians.
  38843. * @param {number} aspectratio - The aspect ratio.
  38844. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  38845. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  38846. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  38847. * @param {number} pixelheight - The height of the layer's render target in pixels.
  38848. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  38849. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  38850. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  38851. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  38852. */
  38853. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  38854. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  38855. const renderTarget = new XRRenderTarget(
  38856. pixelwidth,
  38857. pixelheight,
  38858. {
  38859. format: RGBAFormat,
  38860. type: UnsignedByteType,
  38861. depthTexture: new DepthTexture(
  38862. pixelwidth,
  38863. pixelheight,
  38864. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  38865. undefined,
  38866. undefined,
  38867. undefined,
  38868. undefined,
  38869. undefined,
  38870. undefined,
  38871. attributes.stencil ? DepthStencilFormat : DepthFormat
  38872. ),
  38873. stencilBuffer: attributes.stencil,
  38874. resolveDepthBuffer: false,
  38875. resolveStencilBuffer: false
  38876. } );
  38877. renderTarget._autoAllocateDepthBuffer = true;
  38878. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  38879. material.map = renderTarget.texture;
  38880. material.map.offset.y = 1;
  38881. material.map.repeat.y = -1;
  38882. const plane = new Mesh( geometry, material );
  38883. plane.position.copy( translation );
  38884. plane.quaternion.copy( quaternion );
  38885. const layer = {
  38886. type: 'cylinder',
  38887. radius: radius,
  38888. centralAngle: centralAngle,
  38889. aspectratio: aspectratio,
  38890. translation: translation,
  38891. quaternion: quaternion,
  38892. pixelwidth: pixelwidth,
  38893. pixelheight: pixelheight,
  38894. plane: plane,
  38895. material: material,
  38896. rendercall: rendercall,
  38897. renderTarget: renderTarget };
  38898. this._layers.push( layer );
  38899. if ( this._session !== null ) {
  38900. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  38901. layer.plane.material.blending = CustomBlending;
  38902. layer.plane.material.blendEquation = AddEquation;
  38903. layer.plane.material.blendSrc = ZeroFactor;
  38904. layer.plane.material.blendDst = ZeroFactor;
  38905. layer.xrlayer = this._createXRLayer( layer );
  38906. const xrlayers = this._session.renderState.layers;
  38907. xrlayers.unshift( layer.xrlayer );
  38908. this._session.updateRenderState( { layers: xrlayers } );
  38909. } else {
  38910. renderTarget.isXRRenderTarget = false;
  38911. }
  38912. return plane;
  38913. }
  38914. /**
  38915. * Renders the XR layers that have been previously added to the scene.
  38916. *
  38917. * This method is usually called in your animation loop before rendering
  38918. * the actual scene via `renderer.render( scene, camera );`.
  38919. */
  38920. renderLayers( ) {
  38921. const translationObject = new Vector3();
  38922. const quaternionObject = new Quaternion();
  38923. const renderer = this._renderer;
  38924. const wasPresenting = this.isPresenting;
  38925. const rendererOutputTarget = renderer.getOutputRenderTarget();
  38926. const rendererFramebufferTarget = renderer._frameBufferTarget;
  38927. this.isPresenting = false;
  38928. const rendererSize = new Vector2();
  38929. renderer.getSize( rendererSize );
  38930. const rendererQuad = renderer._quad;
  38931. for ( const layer of this._layers ) {
  38932. layer.renderTarget.isXRRenderTarget = this._session !== null;
  38933. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  38934. if ( layer.renderTarget.isXRRenderTarget && this._sessionUsesLayers ) {
  38935. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  38936. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  38937. renderer.backend.setXRRenderTargetTextures(
  38938. layer.renderTarget,
  38939. glSubImage.colorTexture,
  38940. undefined );
  38941. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  38942. renderer.setOutputRenderTarget( layer.renderTarget );
  38943. renderer.setRenderTarget( null );
  38944. renderer._frameBufferTarget = null;
  38945. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  38946. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  38947. if ( ! frameBufferTarget ) {
  38948. renderer._quad = new QuadMesh( new NodeMaterial() );
  38949. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  38950. } else {
  38951. renderer._frameBufferTarget = frameBufferTarget;
  38952. renderer._quad = quad;
  38953. }
  38954. layer.rendercall();
  38955. renderer._frameBufferTarget = null;
  38956. } else {
  38957. renderer.setRenderTarget( layer.renderTarget );
  38958. layer.rendercall();
  38959. }
  38960. }
  38961. renderer.setRenderTarget( null );
  38962. renderer.setOutputRenderTarget( rendererOutputTarget );
  38963. renderer._frameBufferTarget = rendererFramebufferTarget;
  38964. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  38965. renderer._quad = rendererQuad;
  38966. this.isPresenting = wasPresenting;
  38967. }
  38968. /**
  38969. * Returns the current XR session.
  38970. *
  38971. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  38972. */
  38973. getSession() {
  38974. return this._session;
  38975. }
  38976. /**
  38977. * After a XR session has been requested usually with one of the `*Button` modules, it
  38978. * is injected into the renderer with this method. This method triggers the start of
  38979. * the actual XR rendering.
  38980. *
  38981. * @async
  38982. * @param {XRSession} session - The XR session to set.
  38983. * @return {Promise} A Promise that resolves when the session has been set.
  38984. */
  38985. async setSession( session ) {
  38986. const renderer = this._renderer;
  38987. const backend = renderer.backend;
  38988. this._gl = renderer.getContext();
  38989. const gl = this._gl;
  38990. const attributes = gl.getContextAttributes();
  38991. this._session = session;
  38992. if ( session !== null ) {
  38993. 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.' );
  38994. session.addEventListener( 'select', this._onSessionEvent );
  38995. session.addEventListener( 'selectstart', this._onSessionEvent );
  38996. session.addEventListener( 'selectend', this._onSessionEvent );
  38997. session.addEventListener( 'squeeze', this._onSessionEvent );
  38998. session.addEventListener( 'squeezestart', this._onSessionEvent );
  38999. session.addEventListener( 'squeezeend', this._onSessionEvent );
  39000. session.addEventListener( 'end', this._onSessionEnd );
  39001. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  39002. await backend.makeXRCompatible();
  39003. this._currentPixelRatio = renderer.getPixelRatio();
  39004. renderer.getSize( this._currentSize );
  39005. this._currentAnimationContext = renderer._animation.getContext();
  39006. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  39007. renderer._animation.stop();
  39008. //
  39009. if ( this._supportsLayers === true ) {
  39010. // default path using XRProjectionLayer
  39011. let depthFormat = null;
  39012. let depthType = null;
  39013. let glDepthFormat = null;
  39014. if ( renderer.depth ) {
  39015. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  39016. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  39017. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  39018. }
  39019. const projectionlayerInit = {
  39020. colorFormat: gl.RGBA8,
  39021. depthFormat: glDepthFormat,
  39022. scaleFactor: this._framebufferScaleFactor,
  39023. clearOnAccess: false
  39024. };
  39025. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  39026. projectionlayerInit.textureType = 'texture-array';
  39027. this._useMultiview = true;
  39028. }
  39029. this._glBinding = this.getBinding();
  39030. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  39031. const layersArray = [ glProjLayer ];
  39032. this._glProjLayer = glProjLayer;
  39033. renderer.setPixelRatio( 1 );
  39034. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  39035. const depth = this._useMultiview ? 2 : 1;
  39036. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  39037. this._xrRenderTarget = new XRRenderTarget(
  39038. glProjLayer.textureWidth,
  39039. glProjLayer.textureHeight,
  39040. {
  39041. format: RGBAFormat,
  39042. type: UnsignedByteType,
  39043. colorSpace: renderer.outputColorSpace,
  39044. depthTexture: depthTexture,
  39045. stencilBuffer: renderer.stencil,
  39046. samples: attributes.antialias ? 4 : 0,
  39047. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  39048. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  39049. depth: this._useMultiview ? 2 : 1,
  39050. multiview: this._useMultiview
  39051. } );
  39052. this._xrRenderTarget._hasExternalTextures = true;
  39053. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  39054. this._sessionUsesLayers = session.enabledFeatures.includes( 'layers' );
  39055. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  39056. if ( this._sessionUsesLayers ) {
  39057. // switch layers to native
  39058. for ( const layer of this._layers ) {
  39059. // change material so it "punches" out a hole to show the XR Layer.
  39060. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  39061. layer.plane.material.blending = CustomBlending;
  39062. layer.plane.material.blendEquation = AddEquation;
  39063. layer.plane.material.blendSrc = ZeroFactor;
  39064. layer.plane.material.blendDst = ZeroFactor;
  39065. layer.xrlayer = this._createXRLayer( layer );
  39066. layersArray.unshift( layer.xrlayer );
  39067. }
  39068. }
  39069. session.updateRenderState( { layers: layersArray } );
  39070. } else {
  39071. // fallback to XRWebGLLayer
  39072. const layerInit = {
  39073. antialias: renderer.currentSamples > 0,
  39074. alpha: true,
  39075. depth: renderer.depth,
  39076. stencil: renderer.stencil,
  39077. framebufferScaleFactor: this.getFramebufferScaleFactor()
  39078. };
  39079. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  39080. this._glBaseLayer = glBaseLayer;
  39081. session.updateRenderState( { baseLayer: glBaseLayer } );
  39082. renderer.setPixelRatio( 1 );
  39083. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  39084. this._xrRenderTarget = new XRRenderTarget(
  39085. glBaseLayer.framebufferWidth,
  39086. glBaseLayer.framebufferHeight,
  39087. {
  39088. format: RGBAFormat,
  39089. type: UnsignedByteType,
  39090. colorSpace: renderer.outputColorSpace,
  39091. stencilBuffer: renderer.stencil,
  39092. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  39093. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  39094. }
  39095. );
  39096. this._xrRenderTarget._isOpaqueFramebuffer = true;
  39097. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  39098. }
  39099. //
  39100. this.setFoveation( this.getFoveation() );
  39101. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  39102. renderer._animation.setContext( session );
  39103. renderer._animation.start();
  39104. this.isPresenting = true;
  39105. this.dispatchEvent( { type: 'sessionstart' } );
  39106. }
  39107. }
  39108. /**
  39109. * This method is called by the renderer per frame and updates the XR camera
  39110. * and it sub cameras based on the given camera. The given camera is the "user"
  39111. * camera created on application level and used for non-XR rendering.
  39112. *
  39113. * @param {PerspectiveCamera} camera - The camera.
  39114. */
  39115. updateCamera( camera ) {
  39116. const session = this._session;
  39117. if ( session === null ) return;
  39118. const depthNear = camera.near;
  39119. const depthFar = camera.far;
  39120. const cameraXR = this._cameraXR;
  39121. const cameraL = this._cameraL;
  39122. const cameraR = this._cameraR;
  39123. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  39124. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  39125. cameraXR.isMultiViewCamera = this._useMultiview;
  39126. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  39127. // Note that the new renderState won't apply until the next frame. See #18320
  39128. session.updateRenderState( {
  39129. depthNear: cameraXR.near,
  39130. depthFar: cameraXR.far
  39131. } );
  39132. this._currentDepthNear = cameraXR.near;
  39133. this._currentDepthFar = cameraXR.far;
  39134. }
  39135. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  39136. cameraXR.layers.mask = camera.layers.mask | 0b110;
  39137. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  39138. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  39139. const parent = camera.parent;
  39140. const cameras = cameraXR.cameras;
  39141. updateCamera( cameraXR, parent );
  39142. for ( let i = 0; i < cameras.length; i ++ ) {
  39143. updateCamera( cameras[ i ], parent );
  39144. }
  39145. // update projection matrix for proper view frustum culling
  39146. if ( cameras.length === 2 ) {
  39147. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  39148. } else {
  39149. // assume single camera setup (AR)
  39150. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  39151. }
  39152. // update user camera and its children
  39153. updateUserCamera( camera, cameraXR, parent );
  39154. }
  39155. /**
  39156. * Returns a WebXR controller for the given controller index.
  39157. *
  39158. * @private
  39159. * @param {number} index - The controller index.
  39160. * @return {WebXRController} The XR controller.
  39161. */
  39162. _getController( index ) {
  39163. let controller = this._controllers[ index ];
  39164. if ( controller === undefined ) {
  39165. controller = new WebXRController();
  39166. this._controllers[ index ] = controller;
  39167. }
  39168. return controller;
  39169. }
  39170. }
  39171. /**
  39172. * Assumes 2 cameras that are parallel and share an X-axis, and that
  39173. * the cameras' projection and world matrices have already been set.
  39174. * And that near and far planes are identical for both cameras.
  39175. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  39176. *
  39177. * @param {ArrayCamera} camera - The camera to update.
  39178. * @param {PerspectiveCamera} cameraL - The left camera.
  39179. * @param {PerspectiveCamera} cameraR - The right camera.
  39180. */
  39181. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  39182. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  39183. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  39184. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  39185. const projL = cameraL.projectionMatrix.elements;
  39186. const projR = cameraR.projectionMatrix.elements;
  39187. // VR systems will have identical far and near planes, and
  39188. // most likely identical top and bottom frustum extents.
  39189. // Use the left camera for these values.
  39190. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  39191. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  39192. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  39193. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  39194. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  39195. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  39196. const left = near * leftFov;
  39197. const right = near * rightFov;
  39198. // Calculate the new camera's position offset from the
  39199. // left camera. xOffset should be roughly half `ipd`.
  39200. const zOffset = ipd / ( - leftFov + rightFov );
  39201. const xOffset = zOffset * - leftFov;
  39202. // TODO: Better way to apply this offset?
  39203. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  39204. camera.translateX( xOffset );
  39205. camera.translateZ( zOffset );
  39206. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  39207. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  39208. // Check if the projection uses an infinite far plane.
  39209. if ( projL[ 10 ] === -1 ) {
  39210. // Use the projection matrix from the left eye.
  39211. // The camera offset is sufficient to include the view volumes
  39212. // of both eyes (assuming symmetric projections).
  39213. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  39214. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  39215. } else {
  39216. // Find the union of the frustum values of the cameras and scale
  39217. // the values so that the near plane's position does not change in world space,
  39218. // although must now be relative to the new union camera.
  39219. const near2 = near + zOffset;
  39220. const far2 = far + zOffset;
  39221. const left2 = left - xOffset;
  39222. const right2 = right + ( ipd - xOffset );
  39223. const top2 = topFov * far / far2 * near2;
  39224. const bottom2 = bottomFov * far / far2 * near2;
  39225. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  39226. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  39227. }
  39228. }
  39229. /**
  39230. * Updates the world matrices for the given camera based on the parent 3D object.
  39231. *
  39232. * @inner
  39233. * @param {Camera} camera - The camera to update.
  39234. * @param {Object3D} parent - The parent 3D object.
  39235. */
  39236. function updateCamera( camera, parent ) {
  39237. if ( parent === null ) {
  39238. camera.matrixWorld.copy( camera.matrix );
  39239. } else {
  39240. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  39241. }
  39242. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  39243. }
  39244. /**
  39245. * Updates the given camera with the transformation of the XR camera and parent object.
  39246. *
  39247. * @inner
  39248. * @param {Camera} camera - The camera to update.
  39249. * @param {ArrayCamera} cameraXR - The XR camera.
  39250. * @param {Object3D} parent - The parent 3D object.
  39251. */
  39252. function updateUserCamera( camera, cameraXR, parent ) {
  39253. if ( parent === null ) {
  39254. camera.matrix.copy( cameraXR.matrixWorld );
  39255. } else {
  39256. camera.matrix.copy( parent.matrixWorld );
  39257. camera.matrix.invert();
  39258. camera.matrix.multiply( cameraXR.matrixWorld );
  39259. }
  39260. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  39261. camera.updateMatrixWorld( true );
  39262. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  39263. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  39264. if ( camera.isPerspectiveCamera ) {
  39265. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  39266. camera.zoom = 1;
  39267. }
  39268. }
  39269. function onSessionEvent( event ) {
  39270. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  39271. if ( controllerIndex === -1 ) {
  39272. return;
  39273. }
  39274. const controller = this._controllers[ controllerIndex ];
  39275. if ( controller !== undefined ) {
  39276. const referenceSpace = this.getReferenceSpace();
  39277. controller.update( event.inputSource, event.frame, referenceSpace );
  39278. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  39279. }
  39280. }
  39281. function onSessionEnd() {
  39282. const session = this._session;
  39283. const renderer = this._renderer;
  39284. session.removeEventListener( 'select', this._onSessionEvent );
  39285. session.removeEventListener( 'selectstart', this._onSessionEvent );
  39286. session.removeEventListener( 'selectend', this._onSessionEvent );
  39287. session.removeEventListener( 'squeeze', this._onSessionEvent );
  39288. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  39289. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  39290. session.removeEventListener( 'end', this._onSessionEnd );
  39291. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  39292. for ( let i = 0; i < this._controllers.length; i ++ ) {
  39293. const inputSource = this._controllerInputSources[ i ];
  39294. if ( inputSource === null ) continue;
  39295. this._controllerInputSources[ i ] = null;
  39296. this._controllers[ i ].disconnect( inputSource );
  39297. }
  39298. this._currentDepthNear = null;
  39299. this._currentDepthFar = null;
  39300. // restore framebuffer/rendering state
  39301. renderer._resetXRState();
  39302. this._session = null;
  39303. this._xrRenderTarget = null;
  39304. this._glBinding = null;
  39305. this._glBaseLayer = null;
  39306. this._glProjLayer = null;
  39307. // switch layers back to emulated
  39308. if ( this._sessionUsesLayers === true ) {
  39309. for ( const layer of this._layers ) {
  39310. // Recreate layer render target to reset state
  39311. layer.renderTarget = new XRRenderTarget(
  39312. layer.pixelwidth,
  39313. layer.pixelheight,
  39314. {
  39315. format: RGBAFormat,
  39316. type: UnsignedByteType,
  39317. depthTexture: new DepthTexture(
  39318. layer.pixelwidth,
  39319. layer.pixelheight,
  39320. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  39321. undefined,
  39322. undefined,
  39323. undefined,
  39324. undefined,
  39325. undefined,
  39326. undefined,
  39327. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  39328. ),
  39329. stencilBuffer: layer.stencilBuffer,
  39330. resolveDepthBuffer: false,
  39331. resolveStencilBuffer: false
  39332. } );
  39333. layer.renderTarget.isXRRenderTarget = false;
  39334. layer.plane.material = layer.material;
  39335. layer.material.map = layer.renderTarget.texture;
  39336. layer.material.map.offset.y = 1;
  39337. layer.material.map.repeat.y = -1;
  39338. delete layer.xrlayer;
  39339. }
  39340. }
  39341. //
  39342. this.isPresenting = false;
  39343. this._useMultiview = false;
  39344. renderer._animation.stop();
  39345. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  39346. renderer._animation.setContext( this._currentAnimationContext );
  39347. renderer._animation.start();
  39348. renderer.setPixelRatio( this._currentPixelRatio );
  39349. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  39350. this.dispatchEvent( { type: 'sessionend' } );
  39351. }
  39352. function onInputSourcesChange( event ) {
  39353. const controllers = this._controllers;
  39354. const controllerInputSources = this._controllerInputSources;
  39355. // Notify disconnected
  39356. for ( let i = 0; i < event.removed.length; i ++ ) {
  39357. const inputSource = event.removed[ i ];
  39358. const index = controllerInputSources.indexOf( inputSource );
  39359. if ( index >= 0 ) {
  39360. controllerInputSources[ index ] = null;
  39361. controllers[ index ].disconnect( inputSource );
  39362. }
  39363. }
  39364. // Notify connected
  39365. for ( let i = 0; i < event.added.length; i ++ ) {
  39366. const inputSource = event.added[ i ];
  39367. let controllerIndex = controllerInputSources.indexOf( inputSource );
  39368. if ( controllerIndex === -1 ) {
  39369. // Assign input source a controller that currently has no input source
  39370. for ( let i = 0; i < controllers.length; i ++ ) {
  39371. if ( i >= controllerInputSources.length ) {
  39372. controllerInputSources.push( inputSource );
  39373. controllerIndex = i;
  39374. break;
  39375. } else if ( controllerInputSources[ i ] === null ) {
  39376. controllerInputSources[ i ] = inputSource;
  39377. controllerIndex = i;
  39378. break;
  39379. }
  39380. }
  39381. // If all controllers do currently receive input we ignore new ones
  39382. if ( controllerIndex === -1 ) break;
  39383. }
  39384. const controller = controllers[ controllerIndex ];
  39385. if ( controller ) {
  39386. controller.connect( inputSource );
  39387. }
  39388. }
  39389. }
  39390. // Creation method for native WebXR layers
  39391. function createXRLayer( layer ) {
  39392. if ( layer.type === 'quad' ) {
  39393. return this._glBinding.createQuadLayer( {
  39394. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  39395. width: layer.width / 2,
  39396. height: layer.height / 2,
  39397. space: this._referenceSpace,
  39398. viewPixelWidth: layer.pixelwidth,
  39399. viewPixelHeight: layer.pixelheight,
  39400. clearOnAccess: false
  39401. } );
  39402. } else {
  39403. return this._glBinding.createCylinderLayer( {
  39404. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  39405. radius: layer.radius,
  39406. centralAngle: layer.centralAngle,
  39407. aspectRatio: layer.aspectRatio,
  39408. space: this._referenceSpace,
  39409. viewPixelWidth: layer.pixelwidth,
  39410. viewPixelHeight: layer.pixelheight,
  39411. clearOnAccess: false
  39412. } );
  39413. }
  39414. }
  39415. // Animation Loop
  39416. function onAnimationFrame( time, frame ) {
  39417. if ( frame === undefined ) return;
  39418. const cameraXR = this._cameraXR;
  39419. const renderer = this._renderer;
  39420. const backend = renderer.backend;
  39421. const glBaseLayer = this._glBaseLayer;
  39422. const referenceSpace = this.getReferenceSpace();
  39423. const pose = frame.getViewerPose( referenceSpace );
  39424. this._xrFrame = frame;
  39425. if ( pose !== null ) {
  39426. const views = pose.views;
  39427. if ( this._glBaseLayer !== null ) {
  39428. backend.setXRTarget( glBaseLayer.framebuffer );
  39429. }
  39430. let cameraXRNeedsUpdate = false;
  39431. // check if it's necessary to rebuild cameraXR's camera list
  39432. if ( views.length !== cameraXR.cameras.length ) {
  39433. cameraXR.cameras.length = 0;
  39434. cameraXRNeedsUpdate = true;
  39435. }
  39436. for ( let i = 0; i < views.length; i ++ ) {
  39437. const view = views[ i ];
  39438. let viewport;
  39439. if ( this._supportsLayers === true ) {
  39440. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  39441. viewport = glSubImage.viewport;
  39442. // For side-by-side projection, we only produce a single texture for both eyes.
  39443. if ( i === 0 ) {
  39444. backend.setXRRenderTargetTextures(
  39445. this._xrRenderTarget,
  39446. glSubImage.colorTexture,
  39447. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  39448. );
  39449. }
  39450. } else {
  39451. viewport = glBaseLayer.getViewport( view );
  39452. }
  39453. let camera = this._cameras[ i ];
  39454. if ( camera === undefined ) {
  39455. camera = new PerspectiveCamera();
  39456. camera.layers.enable( i );
  39457. camera.viewport = new Vector4();
  39458. this._cameras[ i ] = camera;
  39459. }
  39460. camera.matrix.fromArray( view.transform.matrix );
  39461. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  39462. camera.projectionMatrix.fromArray( view.projectionMatrix );
  39463. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  39464. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  39465. if ( i === 0 ) {
  39466. cameraXR.matrix.copy( camera.matrix );
  39467. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  39468. }
  39469. if ( cameraXRNeedsUpdate === true ) {
  39470. cameraXR.cameras.push( camera );
  39471. }
  39472. }
  39473. renderer.setOutputRenderTarget( this._xrRenderTarget );
  39474. }
  39475. //
  39476. for ( let i = 0; i < this._controllers.length; i ++ ) {
  39477. const inputSource = this._controllerInputSources[ i ];
  39478. const controller = this._controllers[ i ];
  39479. if ( inputSource !== null && controller !== undefined ) {
  39480. controller.update( inputSource, frame, referenceSpace );
  39481. }
  39482. }
  39483. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  39484. if ( frame.detectedPlanes ) {
  39485. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  39486. }
  39487. this._xrFrame = null;
  39488. }
  39489. /**
  39490. * CanvasTarget is a class that represents the final output destination of the renderer.
  39491. *
  39492. * @augments EventDispatcher
  39493. */
  39494. class CanvasTarget extends EventDispatcher {
  39495. /**
  39496. * Constructs a new CanvasTarget.
  39497. *
  39498. * @param {HTMLCanvasElement|OffscreenCanvas} domElement - The canvas element to render to.
  39499. */
  39500. constructor( domElement ) {
  39501. super();
  39502. /**
  39503. * A reference to the canvas element the renderer is drawing to.
  39504. * This value of this property will automatically be created by
  39505. * the renderer.
  39506. *
  39507. * @type {HTMLCanvasElement|OffscreenCanvas}
  39508. */
  39509. this.domElement = domElement;
  39510. /**
  39511. * The renderer's pixel ratio.
  39512. *
  39513. * @private
  39514. * @type {number}
  39515. * @default 1
  39516. */
  39517. this._pixelRatio = 1;
  39518. /**
  39519. * The width of the renderer's default framebuffer in logical pixel unit.
  39520. *
  39521. * @private
  39522. * @type {number}
  39523. */
  39524. this._width = this.domElement.width;
  39525. /**
  39526. * The height of the renderer's default framebuffer in logical pixel unit.
  39527. *
  39528. * @private
  39529. * @type {number}
  39530. */
  39531. this._height = this.domElement.height;
  39532. /**
  39533. * The viewport of the renderer in logical pixel unit.
  39534. *
  39535. * @private
  39536. * @type {Vector4}
  39537. */
  39538. this._viewport = new Vector4( 0, 0, this._width, this._height );
  39539. /**
  39540. * The scissor rectangle of the renderer in logical pixel unit.
  39541. *
  39542. * @private
  39543. * @type {Vector4}
  39544. */
  39545. this._scissor = new Vector4( 0, 0, this._width, this._height );
  39546. /**
  39547. * Whether the scissor test should be enabled or not.
  39548. *
  39549. * @private
  39550. * @type {boolean}
  39551. */
  39552. this._scissorTest = false;
  39553. /**
  39554. * The color texture of the default framebuffer.
  39555. *
  39556. * @type {FramebufferTexture}
  39557. */
  39558. this.colorTexture = new FramebufferTexture();
  39559. /**
  39560. * The depth texture of the default framebuffer.
  39561. *
  39562. * @type {DepthTexture}
  39563. */
  39564. this.depthTexture = new DepthTexture();
  39565. }
  39566. /**
  39567. * Returns the pixel ratio.
  39568. *
  39569. * @return {number} The pixel ratio.
  39570. */
  39571. getPixelRatio() {
  39572. return this._pixelRatio;
  39573. }
  39574. /**
  39575. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  39576. *
  39577. * @param {Vector2} target - The method writes the result in this target object.
  39578. * @return {Vector2} The drawing buffer size.
  39579. */
  39580. getDrawingBufferSize( target ) {
  39581. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  39582. }
  39583. /**
  39584. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  39585. *
  39586. * @param {Vector2} target - The method writes the result in this target object.
  39587. * @return {Vector2} The renderer's size in logical pixels.
  39588. */
  39589. getSize( target ) {
  39590. return target.set( this._width, this._height );
  39591. }
  39592. /**
  39593. * Sets the given pixel ratio and resizes the canvas if necessary.
  39594. *
  39595. * @param {number} [value=1] - The pixel ratio.
  39596. */
  39597. setPixelRatio( value = 1 ) {
  39598. if ( this._pixelRatio === value ) return;
  39599. this._pixelRatio = value;
  39600. this.setSize( this._width, this._height, false );
  39601. }
  39602. /**
  39603. * This method allows to define the drawing buffer size by specifying
  39604. * width, height and pixel ratio all at once. The size of the drawing
  39605. * buffer is computed with this formula:
  39606. * ```js
  39607. * size.x = width * pixelRatio;
  39608. * size.y = height * pixelRatio;
  39609. * ```
  39610. *
  39611. * @param {number} width - The width in logical pixels.
  39612. * @param {number} height - The height in logical pixels.
  39613. * @param {number} pixelRatio - The pixel ratio.
  39614. */
  39615. setDrawingBufferSize( width, height, pixelRatio ) {
  39616. // Renderer can't be resized while presenting in XR.
  39617. if ( this.xr && this.xr.isPresenting ) return;
  39618. this._width = width;
  39619. this._height = height;
  39620. this._pixelRatio = pixelRatio;
  39621. this.domElement.width = Math.floor( width * pixelRatio );
  39622. this.domElement.height = Math.floor( height * pixelRatio );
  39623. this.setViewport( 0, 0, width, height );
  39624. this._dispatchResize();
  39625. }
  39626. /**
  39627. * Sets the size of the renderer.
  39628. *
  39629. * @param {number} width - The width in logical pixels.
  39630. * @param {number} height - The height in logical pixels.
  39631. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  39632. */
  39633. setSize( width, height, updateStyle = true ) {
  39634. // Renderer can't be resized while presenting in XR.
  39635. if ( this.xr && this.xr.isPresenting ) return;
  39636. this._width = width;
  39637. this._height = height;
  39638. this.domElement.width = Math.floor( width * this._pixelRatio );
  39639. this.domElement.height = Math.floor( height * this._pixelRatio );
  39640. if ( updateStyle === true ) {
  39641. this.domElement.style.width = width + 'px';
  39642. this.domElement.style.height = height + 'px';
  39643. }
  39644. this.setViewport( 0, 0, width, height );
  39645. this._dispatchResize();
  39646. }
  39647. /**
  39648. * Returns the scissor rectangle.
  39649. *
  39650. * @param {Vector4} target - The method writes the result in this target object.
  39651. * @return {Vector4} The scissor rectangle.
  39652. */
  39653. getScissor( target ) {
  39654. const scissor = this._scissor;
  39655. target.x = scissor.x;
  39656. target.y = scissor.y;
  39657. target.width = scissor.width;
  39658. target.height = scissor.height;
  39659. return target;
  39660. }
  39661. /**
  39662. * Defines the scissor rectangle.
  39663. *
  39664. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  39665. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  39666. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  39667. * @param {number} width - The width of the scissor box in logical pixel unit.
  39668. * @param {number} height - The height of the scissor box in logical pixel unit.
  39669. */
  39670. setScissor( x, y, width, height ) {
  39671. const scissor = this._scissor;
  39672. if ( x.isVector4 ) {
  39673. scissor.copy( x );
  39674. } else {
  39675. scissor.set( x, y, width, height );
  39676. }
  39677. }
  39678. /**
  39679. * Returns the scissor test value.
  39680. *
  39681. * @return {boolean} Whether the scissor test should be enabled or not.
  39682. */
  39683. getScissorTest() {
  39684. return this._scissorTest;
  39685. }
  39686. /**
  39687. * Defines the scissor test.
  39688. *
  39689. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  39690. */
  39691. setScissorTest( boolean ) {
  39692. this._scissorTest = boolean;
  39693. }
  39694. /**
  39695. * Returns the viewport definition.
  39696. *
  39697. * @param {Vector4} target - The method writes the result in this target object.
  39698. * @return {Vector4} The viewport definition.
  39699. */
  39700. getViewport( target ) {
  39701. return target.copy( this._viewport );
  39702. }
  39703. /**
  39704. * Defines the viewport.
  39705. *
  39706. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  39707. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  39708. * @param {number} width - The width of the viewport in logical pixel unit.
  39709. * @param {number} height - The height of the viewport in logical pixel unit.
  39710. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  39711. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  39712. */
  39713. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  39714. const viewport = this._viewport;
  39715. if ( x.isVector4 ) {
  39716. viewport.copy( x );
  39717. } else {
  39718. viewport.set( x, y, width, height );
  39719. }
  39720. viewport.minDepth = minDepth;
  39721. viewport.maxDepth = maxDepth;
  39722. }
  39723. /**
  39724. * Dispatches the resize event.
  39725. *
  39726. * @private
  39727. */
  39728. _dispatchResize() {
  39729. this.dispatchEvent( { type: 'resize' } );
  39730. }
  39731. /**
  39732. * Frees the GPU-related resources allocated by this instance. Call this
  39733. * method whenever this instance is no longer used in your app.
  39734. *
  39735. * @fires RenderTarget#dispose
  39736. */
  39737. dispose() {
  39738. this.dispatchEvent( { type: 'dispose' } );
  39739. }
  39740. }
  39741. const _scene = /*@__PURE__*/ new Scene();
  39742. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  39743. const _screen = /*@__PURE__*/ new Vector4();
  39744. const _frustum = /*@__PURE__*/ new Frustum();
  39745. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  39746. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  39747. const _vector4 = /*@__PURE__*/ new Vector4();
  39748. /**
  39749. * Base class for renderers.
  39750. */
  39751. class Renderer {
  39752. /**
  39753. * Renderer options.
  39754. *
  39755. * @typedef {Object} Renderer~Options
  39756. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  39757. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  39758. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  39759. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  39760. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  39761. * @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
  39762. * to overwrite the default.
  39763. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  39764. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  39765. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  39766. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  39767. */
  39768. /**
  39769. * Constructs a new renderer.
  39770. *
  39771. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  39772. * @param {Renderer~Options} [parameters] - The configuration parameter.
  39773. */
  39774. constructor( backend, parameters = {} ) {
  39775. /**
  39776. * This flag can be used for type testing.
  39777. *
  39778. * @type {boolean}
  39779. * @readonly
  39780. * @default true
  39781. */
  39782. this.isRenderer = true;
  39783. //
  39784. const {
  39785. logarithmicDepthBuffer = false,
  39786. alpha = true,
  39787. depth = true,
  39788. stencil = false,
  39789. antialias = false,
  39790. samples = 0,
  39791. getFallback = null,
  39792. colorBufferType = HalfFloatType,
  39793. multiview = false
  39794. } = parameters;
  39795. /**
  39796. * A reference to the current backend.
  39797. *
  39798. * @type {Backend}
  39799. */
  39800. this.backend = backend;
  39801. /**
  39802. * Whether the renderer should automatically clear the current rendering target
  39803. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  39804. * or the current bound render target (custom framebuffer).
  39805. *
  39806. * @type {boolean}
  39807. * @default true
  39808. */
  39809. this.autoClear = true;
  39810. /**
  39811. * When `autoClear` is set to `true`, this property defines whether the renderer
  39812. * should clear the color buffer.
  39813. *
  39814. * @type {boolean}
  39815. * @default true
  39816. */
  39817. this.autoClearColor = true;
  39818. /**
  39819. * When `autoClear` is set to `true`, this property defines whether the renderer
  39820. * should clear the depth buffer.
  39821. *
  39822. * @type {boolean}
  39823. * @default true
  39824. */
  39825. this.autoClearDepth = true;
  39826. /**
  39827. * When `autoClear` is set to `true`, this property defines whether the renderer
  39828. * should clear the stencil buffer.
  39829. *
  39830. * @type {boolean}
  39831. * @default true
  39832. */
  39833. this.autoClearStencil = true;
  39834. /**
  39835. * Whether the default framebuffer should be transparent or opaque.
  39836. *
  39837. * @type {boolean}
  39838. * @default true
  39839. */
  39840. this.alpha = alpha;
  39841. /**
  39842. * Whether logarithmic depth buffer is enabled or not.
  39843. *
  39844. * @type {boolean}
  39845. * @default false
  39846. */
  39847. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  39848. /**
  39849. * Defines the output color space of the renderer.
  39850. *
  39851. * @type {string}
  39852. * @default SRGBColorSpace
  39853. */
  39854. this.outputColorSpace = SRGBColorSpace;
  39855. /**
  39856. * Defines the tone mapping of the renderer.
  39857. *
  39858. * @type {number}
  39859. * @default NoToneMapping
  39860. */
  39861. this.toneMapping = NoToneMapping;
  39862. /**
  39863. * Defines the tone mapping exposure.
  39864. *
  39865. * @type {number}
  39866. * @default 1
  39867. */
  39868. this.toneMappingExposure = 1.0;
  39869. /**
  39870. * Whether the renderer should sort its render lists or not.
  39871. *
  39872. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  39873. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  39874. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  39875. * e.g. manually determining each object's rendering order.
  39876. *
  39877. * @type {boolean}
  39878. * @default true
  39879. */
  39880. this.sortObjects = true;
  39881. /**
  39882. * Whether the default framebuffer should have a depth buffer or not.
  39883. *
  39884. * @type {boolean}
  39885. * @default true
  39886. */
  39887. this.depth = depth;
  39888. /**
  39889. * Whether the default framebuffer should have a stencil buffer or not.
  39890. *
  39891. * @type {boolean}
  39892. * @default false
  39893. */
  39894. this.stencil = stencil;
  39895. /**
  39896. * Holds a series of statistical information about the GPU memory
  39897. * and the rendering process. Useful for debugging and monitoring.
  39898. *
  39899. * @type {Info}
  39900. */
  39901. this.info = new Info();
  39902. /**
  39903. * Stores override nodes for specific transformations or calculations.
  39904. * These nodes can be used to replace default behavior in the rendering pipeline.
  39905. *
  39906. * @type {Object}
  39907. * @property {?Node} modelViewMatrix - An override node for the model-view matrix.
  39908. * @property {?Node} modelNormalViewMatrix - An override node for the model normal view matrix.
  39909. */
  39910. this.overrideNodes = {
  39911. modelViewMatrix: null,
  39912. modelNormalViewMatrix: null
  39913. };
  39914. /**
  39915. * The node library defines how certain library objects like materials, lights
  39916. * or tone mapping functions are mapped to node types. This is required since
  39917. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  39918. * be part of the scene graph, they are internally represented as nodes for
  39919. * further processing.
  39920. *
  39921. * @type {NodeLibrary}
  39922. */
  39923. this.library = new NodeLibrary();
  39924. /**
  39925. * A map-like data structure for managing lights.
  39926. *
  39927. * @type {Lighting}
  39928. */
  39929. this.lighting = new Lighting();
  39930. // internals
  39931. /**
  39932. * The number of MSAA samples.
  39933. *
  39934. * @private
  39935. * @type {number}
  39936. * @default 0
  39937. */
  39938. this._samples = samples || ( antialias === true ) ? 4 : 0;
  39939. /**
  39940. * OnCanvasTargetResize callback function.
  39941. *
  39942. * @private
  39943. * @type {Function}
  39944. */
  39945. this._onCanvasTargetResize = this._onCanvasTargetResize.bind( this );
  39946. /**
  39947. * The canvas target for rendering.
  39948. *
  39949. * @private
  39950. * @type {CanvasTarget}
  39951. */
  39952. this._canvasTarget = new CanvasTarget( backend.getDomElement() );
  39953. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  39954. this._canvasTarget.isDefaultCanvasTarget = true;
  39955. /**
  39956. * The inspector provides information about the internal renderer state.
  39957. *
  39958. * @private
  39959. * @type {InspectorBase}
  39960. */
  39961. this._inspector = new InspectorBase();
  39962. this._inspector.setRenderer( this );
  39963. /**
  39964. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  39965. *
  39966. * @private
  39967. * @type {?Function}
  39968. */
  39969. this._getFallback = getFallback;
  39970. /**
  39971. * A reference to a renderer module for managing shader attributes.
  39972. *
  39973. * @private
  39974. * @type {?Attributes}
  39975. * @default null
  39976. */
  39977. this._attributes = null;
  39978. /**
  39979. * A reference to a renderer module for managing geometries.
  39980. *
  39981. * @private
  39982. * @type {?Geometries}
  39983. * @default null
  39984. */
  39985. this._geometries = null;
  39986. /**
  39987. * A reference to a renderer module for managing node related logic.
  39988. *
  39989. * @private
  39990. * @type {?Nodes}
  39991. * @default null
  39992. */
  39993. this._nodes = null;
  39994. /**
  39995. * A reference to a renderer module for managing the internal animation loop.
  39996. *
  39997. * @private
  39998. * @type {?Animation}
  39999. * @default null
  40000. */
  40001. this._animation = null;
  40002. /**
  40003. * A reference to a renderer module for managing shader program bindings.
  40004. *
  40005. * @private
  40006. * @type {?Bindings}
  40007. * @default null
  40008. */
  40009. this._bindings = null;
  40010. /**
  40011. * A reference to a renderer module for managing render objects.
  40012. *
  40013. * @private
  40014. * @type {?RenderObjects}
  40015. * @default null
  40016. */
  40017. this._objects = null;
  40018. /**
  40019. * A reference to a renderer module for managing render and compute pipelines.
  40020. *
  40021. * @private
  40022. * @type {?Pipelines}
  40023. * @default null
  40024. */
  40025. this._pipelines = null;
  40026. /**
  40027. * A reference to a renderer module for managing render bundles.
  40028. *
  40029. * @private
  40030. * @type {?RenderBundles}
  40031. * @default null
  40032. */
  40033. this._bundles = null;
  40034. /**
  40035. * A reference to a renderer module for managing render lists.
  40036. *
  40037. * @private
  40038. * @type {?RenderLists}
  40039. * @default null
  40040. */
  40041. this._renderLists = null;
  40042. /**
  40043. * A reference to a renderer module for managing render contexts.
  40044. *
  40045. * @private
  40046. * @type {?RenderContexts}
  40047. * @default null
  40048. */
  40049. this._renderContexts = null;
  40050. /**
  40051. * A reference to a renderer module for managing textures.
  40052. *
  40053. * @private
  40054. * @type {?Textures}
  40055. * @default null
  40056. */
  40057. this._textures = null;
  40058. /**
  40059. * A reference to a renderer module for backgrounds.
  40060. *
  40061. * @private
  40062. * @type {?Background}
  40063. * @default null
  40064. */
  40065. this._background = null;
  40066. /**
  40067. * This fullscreen quad is used for internal render passes
  40068. * like the tone mapping and color space output pass.
  40069. *
  40070. * @private
  40071. * @type {QuadMesh}
  40072. */
  40073. this._quad = new QuadMesh( new NodeMaterial() );
  40074. this._quad.name = 'Output Color Transform';
  40075. this._quad.material.name = 'outputColorTransform';
  40076. /**
  40077. * A reference to the current render context.
  40078. *
  40079. * @private
  40080. * @type {?RenderContext}
  40081. * @default null
  40082. */
  40083. this._currentRenderContext = null;
  40084. /**
  40085. * A custom sort function for the opaque render list.
  40086. *
  40087. * @private
  40088. * @type {?Function}
  40089. * @default null
  40090. */
  40091. this._opaqueSort = null;
  40092. /**
  40093. * A custom sort function for the transparent render list.
  40094. *
  40095. * @private
  40096. * @type {?Function}
  40097. * @default null
  40098. */
  40099. this._transparentSort = null;
  40100. /**
  40101. * The framebuffer target.
  40102. *
  40103. * @private
  40104. * @type {?RenderTarget}
  40105. * @default null
  40106. */
  40107. this._frameBufferTarget = null;
  40108. const alphaClear = this.alpha === true ? 0 : 1;
  40109. /**
  40110. * The clear color value.
  40111. *
  40112. * @private
  40113. * @type {Color4}
  40114. */
  40115. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  40116. /**
  40117. * The clear depth value.
  40118. *
  40119. * @private
  40120. * @type {number}
  40121. * @default 1
  40122. */
  40123. this._clearDepth = 1;
  40124. /**
  40125. * The clear stencil value.
  40126. *
  40127. * @private
  40128. * @type {number}
  40129. * @default 0
  40130. */
  40131. this._clearStencil = 0;
  40132. /**
  40133. * The current render target.
  40134. *
  40135. * @private
  40136. * @type {?RenderTarget}
  40137. * @default null
  40138. */
  40139. this._renderTarget = null;
  40140. /**
  40141. * The active cube face.
  40142. *
  40143. * @private
  40144. * @type {number}
  40145. * @default 0
  40146. */
  40147. this._activeCubeFace = 0;
  40148. /**
  40149. * The active mipmap level.
  40150. *
  40151. * @private
  40152. * @type {number}
  40153. * @default 0
  40154. */
  40155. this._activeMipmapLevel = 0;
  40156. /**
  40157. * The current output render target.
  40158. *
  40159. * @private
  40160. * @type {?RenderTarget}
  40161. * @default null
  40162. */
  40163. this._outputRenderTarget = null;
  40164. /**
  40165. * The MRT setting.
  40166. *
  40167. * @private
  40168. * @type {?MRTNode}
  40169. * @default null
  40170. */
  40171. this._mrt = null;
  40172. /**
  40173. * This function defines how a render object is going
  40174. * to be rendered.
  40175. *
  40176. * @private
  40177. * @type {?Function}
  40178. * @default null
  40179. */
  40180. this._renderObjectFunction = null;
  40181. /**
  40182. * Used to keep track of the current render object function.
  40183. *
  40184. * @private
  40185. * @type {?Function}
  40186. * @default null
  40187. */
  40188. this._currentRenderObjectFunction = null;
  40189. /**
  40190. * Used to keep track of the current render bundle.
  40191. *
  40192. * @private
  40193. * @type {?RenderBundle}
  40194. * @default null
  40195. */
  40196. this._currentRenderBundle = null;
  40197. /**
  40198. * Next to `_renderObjectFunction()`, this function provides another hook
  40199. * for influencing the render process of a render object. It is meant for internal
  40200. * use and only relevant for `compileAsync()` right now. Instead of using
  40201. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  40202. * a different function might be used which performs no draw but just the node
  40203. * and pipeline updates.
  40204. *
  40205. * @private
  40206. * @type {?Function}
  40207. * @default null
  40208. */
  40209. this._handleObjectFunction = this._renderObjectDirect;
  40210. /**
  40211. * Indicates whether the device has been lost or not. In WebGL terms, the device
  40212. * lost is considered as a context lost. When this is set to `true`, rendering
  40213. * isn't possible anymore.
  40214. *
  40215. * @private
  40216. * @type {boolean}
  40217. * @default false
  40218. */
  40219. this._isDeviceLost = false;
  40220. /**
  40221. * A callback function that defines what should happen when a device/context lost occurs.
  40222. *
  40223. * @type {Function}
  40224. */
  40225. this.onDeviceLost = this._onDeviceLost;
  40226. /**
  40227. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  40228. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  40229. * This will reduce rendering quality though.
  40230. *
  40231. * @private
  40232. * @type {number}
  40233. * @default HalfFloatType
  40234. */
  40235. this._colorBufferType = colorBufferType;
  40236. /**
  40237. * A cache for shadow nodes per material
  40238. *
  40239. * @private
  40240. * @type {WeakMap<Material, Object>}
  40241. */
  40242. this._cacheShadowNodes = new WeakMap();
  40243. /**
  40244. * Whether the renderer has been initialized or not.
  40245. *
  40246. * @private
  40247. * @type {boolean}
  40248. * @default false
  40249. */
  40250. this._initialized = false;
  40251. /**
  40252. * A reference to the promise which initializes the renderer.
  40253. *
  40254. * @private
  40255. * @type {?Promise<this>}
  40256. * @default null
  40257. */
  40258. this._initPromise = null;
  40259. /**
  40260. * An array of compilation promises which are used in `compileAsync()`.
  40261. *
  40262. * @private
  40263. * @type {?Array<Promise>}
  40264. * @default null
  40265. */
  40266. this._compilationPromises = null;
  40267. /**
  40268. * Whether the renderer should render transparent render objects or not.
  40269. *
  40270. * @type {boolean}
  40271. * @default true
  40272. */
  40273. this.transparent = true;
  40274. /**
  40275. * Whether the renderer should render opaque render objects or not.
  40276. *
  40277. * @type {boolean}
  40278. * @default true
  40279. */
  40280. this.opaque = true;
  40281. /**
  40282. * Shadow map configuration
  40283. * @typedef {Object} ShadowMapConfig
  40284. * @property {boolean} enabled - Whether to globally enable shadows or not.
  40285. * @property {number} type - The shadow map type.
  40286. */
  40287. /**
  40288. * The renderer's shadow configuration.
  40289. *
  40290. * @type {ShadowMapConfig}
  40291. */
  40292. this.shadowMap = {
  40293. enabled: false,
  40294. type: PCFShadowMap
  40295. };
  40296. /**
  40297. * XR configuration.
  40298. * @typedef {Object} XRConfig
  40299. * @property {boolean} enabled - Whether to globally enable XR or not.
  40300. */
  40301. /**
  40302. * The renderer's XR manager.
  40303. *
  40304. * @type {XRManager}
  40305. */
  40306. this.xr = new XRManager( this, multiview );
  40307. /**
  40308. * Debug configuration.
  40309. * @typedef {Object} DebugConfig
  40310. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  40311. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  40312. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  40313. */
  40314. /**
  40315. * The renderer's debug configuration.
  40316. *
  40317. * @type {DebugConfig}
  40318. */
  40319. this.debug = {
  40320. checkShaderErrors: true,
  40321. onShaderError: null,
  40322. getShaderAsync: async ( scene, camera, object ) => {
  40323. await this.compileAsync( scene, camera );
  40324. const renderList = this._renderLists.get( scene, camera );
  40325. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  40326. const material = scene.overrideMaterial || object.material;
  40327. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  40328. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  40329. return { fragmentShader, vertexShader };
  40330. }
  40331. };
  40332. }
  40333. /**
  40334. * Initializes the renderer so it is ready for usage.
  40335. *
  40336. * @async
  40337. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  40338. */
  40339. async init() {
  40340. if ( this._initPromise !== null ) {
  40341. return this._initPromise;
  40342. }
  40343. this._initPromise = new Promise( async ( resolve, reject ) => {
  40344. let backend = this.backend;
  40345. try {
  40346. await backend.init( this );
  40347. } catch ( error ) {
  40348. if ( this._getFallback !== null ) {
  40349. // try the fallback
  40350. try {
  40351. this.backend = backend = this._getFallback( error );
  40352. await backend.init( this );
  40353. } catch ( error ) {
  40354. reject( error );
  40355. return;
  40356. }
  40357. } else {
  40358. reject( error );
  40359. return;
  40360. }
  40361. }
  40362. this._nodes = new Nodes( this, backend );
  40363. this._animation = new Animation( this, this._nodes, this.info );
  40364. this._attributes = new Attributes( backend );
  40365. this._background = new Background( this, this._nodes );
  40366. this._geometries = new Geometries( this._attributes, this.info );
  40367. this._textures = new Textures( this, backend, this.info );
  40368. this._pipelines = new Pipelines( backend, this._nodes );
  40369. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  40370. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  40371. this._renderLists = new RenderLists( this.lighting );
  40372. this._bundles = new RenderBundles();
  40373. this._renderContexts = new RenderContexts();
  40374. //
  40375. this._animation.start();
  40376. this._initialized = true;
  40377. //
  40378. this._inspector.init();
  40379. //
  40380. resolve( this );
  40381. } );
  40382. return this._initPromise;
  40383. }
  40384. /**
  40385. * A reference to the canvas element the renderer is drawing to.
  40386. * This value of this property will automatically be created by
  40387. * the renderer.
  40388. *
  40389. * @type {HTMLCanvasElement|OffscreenCanvas}
  40390. */
  40391. get domElement() {
  40392. return this._canvasTarget.domElement;
  40393. }
  40394. /**
  40395. * The coordinate system of the renderer. The value of this property
  40396. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  40397. * `THREE.WebGPUCoordinateSystem`.
  40398. *
  40399. * @readonly
  40400. * @type {number}
  40401. */
  40402. get coordinateSystem() {
  40403. return this.backend.coordinateSystem;
  40404. }
  40405. /**
  40406. * Compiles all materials in the given scene. This can be useful to avoid a
  40407. * phenomenon which is called "shader compilation stutter", which occurs when
  40408. * rendering an object with a new shader for the first time.
  40409. *
  40410. * If you want to add a 3D object to an existing scene, use the third optional
  40411. * parameter for applying the target scene. Note that the (target) scene's lighting
  40412. * and environment must be configured before calling this method.
  40413. *
  40414. * @async
  40415. * @param {Object3D} scene - The scene or 3D object to precompile.
  40416. * @param {Camera} camera - The camera that is used to render the scene.
  40417. * @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.
  40418. * @return {Promise<Array|undefined>} A Promise that resolves when the compile has been finished.
  40419. */
  40420. async compileAsync( scene, camera, targetScene = null ) {
  40421. if ( this._isDeviceLost === true ) return;
  40422. if ( this._initialized === false ) await this.init();
  40423. // preserve render tree
  40424. const nodeFrame = this._nodes.nodeFrame;
  40425. const previousRenderId = nodeFrame.renderId;
  40426. const previousRenderContext = this._currentRenderContext;
  40427. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  40428. const previousCompilationPromises = this._compilationPromises;
  40429. //
  40430. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  40431. if ( targetScene === null ) targetScene = scene;
  40432. const renderTarget = this._renderTarget;
  40433. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  40434. const activeMipmapLevel = this._activeMipmapLevel;
  40435. const compilationPromises = [];
  40436. this._currentRenderContext = renderContext;
  40437. this._currentRenderObjectFunction = this.renderObject;
  40438. this._handleObjectFunction = this._createObjectPipeline;
  40439. this._compilationPromises = compilationPromises;
  40440. nodeFrame.renderId ++;
  40441. //
  40442. nodeFrame.update();
  40443. //
  40444. renderContext.depth = this.depth;
  40445. renderContext.stencil = this.stencil;
  40446. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  40447. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  40448. //
  40449. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  40450. //
  40451. const renderList = this._renderLists.get( scene, camera );
  40452. renderList.begin();
  40453. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  40454. // include lights from target scene
  40455. if ( targetScene !== scene ) {
  40456. targetScene.traverseVisible( function ( object ) {
  40457. if ( object.isLight && object.layers.test( camera.layers ) ) {
  40458. renderList.pushLight( object );
  40459. }
  40460. } );
  40461. }
  40462. renderList.finish();
  40463. //
  40464. if ( renderTarget !== null ) {
  40465. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  40466. const renderTargetData = this._textures.get( renderTarget );
  40467. renderContext.textures = renderTargetData.textures;
  40468. renderContext.depthTexture = renderTargetData.depthTexture;
  40469. } else {
  40470. renderContext.textures = null;
  40471. renderContext.depthTexture = null;
  40472. }
  40473. //
  40474. this._background.update( sceneRef, renderList, renderContext );
  40475. // process render lists
  40476. const opaqueObjects = renderList.opaque;
  40477. const transparentObjects = renderList.transparent;
  40478. const transparentDoublePassObjects = renderList.transparentDoublePass;
  40479. const lightsNode = renderList.lightsNode;
  40480. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  40481. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  40482. // restore render tree
  40483. nodeFrame.renderId = previousRenderId;
  40484. this._currentRenderContext = previousRenderContext;
  40485. this._currentRenderObjectFunction = previousRenderObjectFunction;
  40486. this._compilationPromises = previousCompilationPromises;
  40487. this._handleObjectFunction = this._renderObjectDirect;
  40488. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  40489. await Promise.all( compilationPromises );
  40490. }
  40491. /**
  40492. * Renders the scene in an async fashion.
  40493. *
  40494. * @async
  40495. * @deprecated
  40496. * @param {Object3D} scene - The scene or 3D object to render.
  40497. * @param {Camera} camera - The camera.
  40498. * @return {Promise} A Promise that resolves when the render has been finished.
  40499. */
  40500. async renderAsync( scene, camera ) {
  40501. warnOnce( 'Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  40502. await this.init();
  40503. this.render( scene, camera );
  40504. }
  40505. /**
  40506. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  40507. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  40508. *
  40509. * @async
  40510. * @deprecated
  40511. * @return {Promise} A Promise that resolves when synchronization has been finished.
  40512. */
  40513. async waitForGPU() {
  40514. error( 'Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.' );
  40515. }
  40516. //
  40517. /**
  40518. * Sets the inspector instance. The inspector can be any class that extends from `InspectorBase`.
  40519. *
  40520. * @param {InspectorBase} value - The new inspector.
  40521. */
  40522. set inspector( value ) {
  40523. if ( this._inspector !== null ) {
  40524. this._inspector.setRenderer( null );
  40525. }
  40526. this._inspector = value;
  40527. this._inspector.setRenderer( this );
  40528. }
  40529. get inspector() {
  40530. return this._inspector;
  40531. }
  40532. /**
  40533. * Enables or disables high precision for model-view and normal-view matrices.
  40534. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  40535. *
  40536. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  40537. *
  40538. * @param {boolean} value - Whether to enable or disable high precision.
  40539. * @type {boolean}
  40540. */
  40541. set highPrecision( value ) {
  40542. if ( value === true ) {
  40543. this.overrideNodes.modelViewMatrix = highpModelViewMatrix;
  40544. this.overrideNodes.modelNormalViewMatrix = highpModelNormalViewMatrix;
  40545. } else if ( this.highPrecision ) {
  40546. this.overrideNodes.modelViewMatrix = null;
  40547. this.overrideNodes.modelNormalViewMatrix = null;
  40548. }
  40549. }
  40550. /**
  40551. * Returns whether high precision is enabled or not.
  40552. *
  40553. * @return {boolean} Whether high precision is enabled or not.
  40554. * @type {boolean}
  40555. */
  40556. get highPrecision() {
  40557. return this.overrideNodes.modelViewMatrix === highpModelViewMatrix && this.overrideNodes.modelNormalViewMatrix === highpModelNormalViewMatrix;
  40558. }
  40559. /**
  40560. * Sets the given MRT configuration.
  40561. *
  40562. * @param {MRTNode} mrt - The MRT node to set.
  40563. * @return {Renderer} A reference to this renderer.
  40564. */
  40565. setMRT( mrt ) {
  40566. this._mrt = mrt;
  40567. return this;
  40568. }
  40569. /**
  40570. * Returns the MRT configuration.
  40571. *
  40572. * @return {MRTNode} The MRT configuration.
  40573. */
  40574. getMRT() {
  40575. return this._mrt;
  40576. }
  40577. /**
  40578. * Returns the color buffer type.
  40579. *
  40580. * @return {number} The color buffer type.
  40581. */
  40582. getColorBufferType() {
  40583. return this._colorBufferType;
  40584. }
  40585. /**
  40586. * Default implementation of the device lost callback.
  40587. *
  40588. * @private
  40589. * @param {Object} info - Information about the context lost.
  40590. */
  40591. _onDeviceLost( info ) {
  40592. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  40593. if ( info.reason ) {
  40594. errorMessage += `\nReason: ${info.reason}`;
  40595. }
  40596. error( errorMessage );
  40597. this._isDeviceLost = true;
  40598. }
  40599. /**
  40600. * Renders the given render bundle.
  40601. *
  40602. * @private
  40603. * @param {Object} bundle - Render bundle data.
  40604. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  40605. * @param {LightsNode} lightsNode - The lights node.
  40606. */
  40607. _renderBundle( bundle, sceneRef, lightsNode ) {
  40608. const { bundleGroup, camera, renderList } = bundle;
  40609. const renderContext = this._currentRenderContext;
  40610. //
  40611. const renderBundle = this._bundles.get( bundleGroup, camera );
  40612. const renderBundleData = this.backend.get( renderBundle );
  40613. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  40614. //
  40615. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  40616. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  40617. renderBundleData.renderContexts.add( renderContext );
  40618. if ( renderBundleNeedsUpdate ) {
  40619. this.backend.beginBundle( renderContext );
  40620. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  40621. renderBundleData.renderObjects = [];
  40622. }
  40623. this._currentRenderBundle = renderBundle;
  40624. const {
  40625. transparentDoublePass: transparentDoublePassObjects,
  40626. transparent: transparentObjects,
  40627. opaque: opaqueObjects
  40628. } = renderList;
  40629. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  40630. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  40631. this._currentRenderBundle = null;
  40632. //
  40633. this.backend.finishBundle( renderContext, renderBundle );
  40634. renderBundleData.version = bundleGroup.version;
  40635. } else {
  40636. const { renderObjects } = renderBundleData;
  40637. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  40638. const renderObject = renderObjects[ i ];
  40639. if ( this._nodes.needsRefresh( renderObject ) ) {
  40640. this._nodes.updateBefore( renderObject );
  40641. this._nodes.updateForRender( renderObject );
  40642. this._bindings.updateForRender( renderObject );
  40643. this._nodes.updateAfter( renderObject );
  40644. }
  40645. }
  40646. }
  40647. this.backend.addBundle( renderContext, renderBundle );
  40648. }
  40649. /**
  40650. * Renders the scene or 3D object with the given camera. This method can only be called
  40651. * if the renderer has been initialized. When using `render()` inside an animation loop,
  40652. * it's guaranteed the renderer will be initialized. The animation loop must be defined
  40653. * with {@link Renderer#setAnimationLoop} though.
  40654. *
  40655. * For all other use cases (like when using on-demand rendering), you must call
  40656. * {@link Renderer#init} before rendering.
  40657. *
  40658. * The target of the method is the default framebuffer (meaning the canvas)
  40659. * or alternatively a render target when specified via `setRenderTarget()`.
  40660. *
  40661. * @param {Object3D} scene - The scene or 3D object to render.
  40662. * @param {Camera} camera - The camera to render the scene with.
  40663. */
  40664. render( scene, camera ) {
  40665. if ( this._initialized === false ) {
  40666. throw new Error( 'Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.' );
  40667. }
  40668. this._renderScene( scene, camera );
  40669. }
  40670. /**
  40671. * Returns whether the renderer has been initialized or not.
  40672. *
  40673. * @readonly
  40674. * @return {boolean} Whether the renderer has been initialized or not.
  40675. */
  40676. get initialized() {
  40677. return this._initialized;
  40678. }
  40679. /**
  40680. * Returns an internal render target which is used when computing the output tone mapping
  40681. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  40682. * pass and not inline to achieve more correct results.
  40683. *
  40684. * @private
  40685. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  40686. */
  40687. _getFrameBufferTarget() {
  40688. const { currentToneMapping, currentColorSpace } = this;
  40689. const useToneMapping = currentToneMapping !== NoToneMapping;
  40690. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  40691. if ( useToneMapping === false && useColorSpace === false ) return null;
  40692. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  40693. const { depth, stencil } = this;
  40694. let frameBufferTarget = this._frameBufferTarget;
  40695. if ( frameBufferTarget === null ) {
  40696. frameBufferTarget = new RenderTarget( width, height, {
  40697. depthBuffer: depth,
  40698. stencilBuffer: stencil,
  40699. type: this._colorBufferType,
  40700. format: RGBAFormat,
  40701. colorSpace: ColorManagement.workingColorSpace,
  40702. generateMipmaps: false,
  40703. minFilter: LinearFilter,
  40704. magFilter: LinearFilter,
  40705. samples: this.samples
  40706. } );
  40707. frameBufferTarget.isPostProcessingRenderTarget = true;
  40708. this._frameBufferTarget = frameBufferTarget;
  40709. }
  40710. const outputRenderTarget = this.getOutputRenderTarget();
  40711. frameBufferTarget.depthBuffer = depth;
  40712. frameBufferTarget.stencilBuffer = stencil;
  40713. if ( outputRenderTarget !== null ) {
  40714. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  40715. } else {
  40716. frameBufferTarget.setSize( width, height, 1 );
  40717. }
  40718. const canvasTarget = this._canvasTarget;
  40719. frameBufferTarget.viewport.copy( canvasTarget._viewport );
  40720. frameBufferTarget.scissor.copy( canvasTarget._scissor );
  40721. frameBufferTarget.viewport.multiplyScalar( canvasTarget._pixelRatio );
  40722. frameBufferTarget.scissor.multiplyScalar( canvasTarget._pixelRatio );
  40723. frameBufferTarget.scissorTest = canvasTarget._scissorTest;
  40724. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  40725. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  40726. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  40727. return frameBufferTarget;
  40728. }
  40729. /**
  40730. * Renders the scene or 3D object with the given camera.
  40731. *
  40732. * @private
  40733. * @param {Object3D} scene - The scene or 3D object to render.
  40734. * @param {Camera} camera - The camera to render the scene with.
  40735. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  40736. * @return {RenderContext} The current render context.
  40737. */
  40738. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  40739. if ( this._isDeviceLost === true ) return;
  40740. //
  40741. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  40742. // preserve render tree
  40743. const nodeFrame = this._nodes.nodeFrame;
  40744. const previousRenderId = nodeFrame.renderId;
  40745. const previousRenderContext = this._currentRenderContext;
  40746. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  40747. //
  40748. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  40749. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  40750. const activeCubeFace = this._activeCubeFace;
  40751. const activeMipmapLevel = this._activeMipmapLevel;
  40752. //
  40753. let renderTarget;
  40754. if ( frameBufferTarget !== null ) {
  40755. renderTarget = frameBufferTarget;
  40756. this.setRenderTarget( renderTarget );
  40757. } else {
  40758. renderTarget = outputRenderTarget;
  40759. }
  40760. //
  40761. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  40762. this._currentRenderContext = renderContext;
  40763. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  40764. //
  40765. this.info.calls ++;
  40766. this.info.render.calls ++;
  40767. this.info.render.frameCalls ++;
  40768. nodeFrame.renderId = this.info.calls;
  40769. //
  40770. this.backend.updateTimeStampUID( renderContext );
  40771. this.inspector.beginRender( this.backend.getTimestampUID( renderContext ), scene, camera, renderTarget );
  40772. //
  40773. const coordinateSystem = this.coordinateSystem;
  40774. const xr = this.xr;
  40775. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  40776. camera.coordinateSystem = coordinateSystem;
  40777. camera.updateProjectionMatrix();
  40778. if ( camera.isArrayCamera ) {
  40779. for ( const subCamera of camera.cameras ) {
  40780. subCamera.coordinateSystem = coordinateSystem;
  40781. subCamera.updateProjectionMatrix();
  40782. }
  40783. }
  40784. }
  40785. //
  40786. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  40787. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  40788. if ( xr.enabled === true && xr.isPresenting === true ) {
  40789. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  40790. camera = xr.getCamera(); // use XR camera for rendering
  40791. }
  40792. //
  40793. const canvasTarget = this._canvasTarget;
  40794. let viewport = canvasTarget._viewport;
  40795. let scissor = canvasTarget._scissor;
  40796. let pixelRatio = canvasTarget._pixelRatio;
  40797. if ( renderTarget !== null ) {
  40798. viewport = renderTarget.viewport;
  40799. scissor = renderTarget.scissor;
  40800. pixelRatio = 1;
  40801. }
  40802. this.getDrawingBufferSize( _drawingBufferSize );
  40803. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  40804. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  40805. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  40806. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  40807. renderContext.viewportValue.width >>= activeMipmapLevel;
  40808. renderContext.viewportValue.height >>= activeMipmapLevel;
  40809. renderContext.viewportValue.minDepth = minDepth;
  40810. renderContext.viewportValue.maxDepth = maxDepth;
  40811. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  40812. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  40813. renderContext.scissor = canvasTarget._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  40814. renderContext.scissorValue.width >>= activeMipmapLevel;
  40815. renderContext.scissorValue.height >>= activeMipmapLevel;
  40816. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  40817. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  40818. //
  40819. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  40820. //
  40821. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  40822. if ( ! camera.isArrayCamera ) {
  40823. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  40824. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  40825. }
  40826. const renderList = this._renderLists.get( scene, camera );
  40827. renderList.begin();
  40828. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  40829. renderList.finish();
  40830. if ( this.sortObjects === true ) {
  40831. renderList.sort( this._opaqueSort, this._transparentSort );
  40832. }
  40833. //
  40834. if ( renderTarget !== null ) {
  40835. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  40836. const renderTargetData = this._textures.get( renderTarget );
  40837. renderContext.textures = renderTargetData.textures;
  40838. renderContext.depthTexture = renderTargetData.depthTexture;
  40839. renderContext.width = renderTargetData.width;
  40840. renderContext.height = renderTargetData.height;
  40841. renderContext.renderTarget = renderTarget;
  40842. renderContext.depth = renderTarget.depthBuffer;
  40843. renderContext.stencil = renderTarget.stencilBuffer;
  40844. } else {
  40845. renderContext.textures = null;
  40846. renderContext.depthTexture = null;
  40847. renderContext.width = _drawingBufferSize.width;
  40848. renderContext.height = _drawingBufferSize.height;
  40849. renderContext.depth = this.depth;
  40850. renderContext.stencil = this.stencil;
  40851. }
  40852. renderContext.width >>= activeMipmapLevel;
  40853. renderContext.height >>= activeMipmapLevel;
  40854. renderContext.activeCubeFace = activeCubeFace;
  40855. renderContext.activeMipmapLevel = activeMipmapLevel;
  40856. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  40857. //
  40858. renderContext.scissorValue.max( _vector4.set( 0, 0, 0, 0 ) );
  40859. if ( renderContext.scissorValue.x + renderContext.scissorValue.width > renderContext.width ) {
  40860. renderContext.scissorValue.width = Math.max( renderContext.width - renderContext.scissorValue.x, 0 );
  40861. }
  40862. if ( renderContext.scissorValue.y + renderContext.scissorValue.height > renderContext.height ) {
  40863. renderContext.scissorValue.height = Math.max( renderContext.height - renderContext.scissorValue.y, 0 );
  40864. }
  40865. //
  40866. this._background.update( sceneRef, renderList, renderContext );
  40867. //
  40868. renderContext.camera = camera;
  40869. this.backend.beginRender( renderContext );
  40870. // process render lists
  40871. const {
  40872. bundles,
  40873. lightsNode,
  40874. transparentDoublePass: transparentDoublePassObjects,
  40875. transparent: transparentObjects,
  40876. opaque: opaqueObjects
  40877. } = renderList;
  40878. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  40879. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  40880. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  40881. // finish render pass
  40882. this.backend.finishRender( renderContext );
  40883. // restore render tree
  40884. nodeFrame.renderId = previousRenderId;
  40885. this._currentRenderContext = previousRenderContext;
  40886. this._currentRenderObjectFunction = previousRenderObjectFunction;
  40887. //
  40888. if ( frameBufferTarget !== null ) {
  40889. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  40890. this._renderOutput( renderTarget );
  40891. }
  40892. //
  40893. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  40894. //
  40895. this.inspector.finishRender( this.backend.getTimestampUID( renderContext ) );
  40896. //
  40897. return renderContext;
  40898. }
  40899. _setXRLayerSize( width, height ) {
  40900. // TODO: Find a better solution to resize the canvas when in XR.
  40901. this._canvasTarget._width = width;
  40902. this._canvasTarget._height = height;
  40903. this.setViewport( 0, 0, width, height );
  40904. }
  40905. /**
  40906. * The output pass performs tone mapping and color space conversion.
  40907. *
  40908. * @private
  40909. * @param {RenderTarget} renderTarget - The current render target.
  40910. */
  40911. _renderOutput( renderTarget ) {
  40912. const quad = this._quad;
  40913. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  40914. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  40915. quad.material.needsUpdate = true;
  40916. }
  40917. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  40918. const currentAutoClear = this.autoClear;
  40919. const currentXR = this.xr.enabled;
  40920. this.autoClear = false;
  40921. this.xr.enabled = false;
  40922. this._renderScene( quad, quad.camera, false );
  40923. this.autoClear = currentAutoClear;
  40924. this.xr.enabled = currentXR;
  40925. }
  40926. /**
  40927. * Returns the maximum available anisotropy for texture filtering.
  40928. *
  40929. * @return {number} The maximum available anisotropy.
  40930. */
  40931. getMaxAnisotropy() {
  40932. return this.backend.getMaxAnisotropy();
  40933. }
  40934. /**
  40935. * Returns the active cube face.
  40936. *
  40937. * @return {number} The active cube face.
  40938. */
  40939. getActiveCubeFace() {
  40940. return this._activeCubeFace;
  40941. }
  40942. /**
  40943. * Returns the active mipmap level.
  40944. *
  40945. * @return {number} The active mipmap level.
  40946. */
  40947. getActiveMipmapLevel() {
  40948. return this._activeMipmapLevel;
  40949. }
  40950. /**
  40951. * Applications are advised to always define the animation loop
  40952. * with this method and not manually with `requestAnimationFrame()`
  40953. * for best compatibility.
  40954. *
  40955. * @async
  40956. * @param {?onAnimationCallback} callback - The application's animation loop.
  40957. * @return {Promise} A Promise that resolves when the set has been executed.
  40958. */
  40959. async setAnimationLoop( callback ) {
  40960. if ( this._initialized === false ) await this.init();
  40961. this._animation.setAnimationLoop( callback );
  40962. }
  40963. /**
  40964. * Returns the current animation loop callback.
  40965. *
  40966. * @return {?Function} The current animation loop callback.
  40967. */
  40968. getAnimationLoop() {
  40969. return this._animation.getAnimationLoop();
  40970. }
  40971. /**
  40972. * Can be used to transfer buffer data from a storage buffer attribute
  40973. * from the GPU to the CPU in context of compute shaders.
  40974. *
  40975. * @async
  40976. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  40977. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  40978. */
  40979. async getArrayBufferAsync( attribute ) {
  40980. return await this.backend.getArrayBufferAsync( attribute );
  40981. }
  40982. /**
  40983. * Returns the rendering context.
  40984. *
  40985. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  40986. */
  40987. getContext() {
  40988. return this.backend.getContext();
  40989. }
  40990. /**
  40991. * Returns the pixel ratio.
  40992. *
  40993. * @return {number} The pixel ratio.
  40994. */
  40995. getPixelRatio() {
  40996. return this._canvasTarget.getPixelRatio();
  40997. }
  40998. /**
  40999. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  41000. *
  41001. * @param {Vector2} target - The method writes the result in this target object.
  41002. * @return {Vector2} The drawing buffer size.
  41003. */
  41004. getDrawingBufferSize( target ) {
  41005. return this._canvasTarget.getDrawingBufferSize( target );
  41006. }
  41007. /**
  41008. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  41009. *
  41010. * @param {Vector2} target - The method writes the result in this target object.
  41011. * @return {Vector2} The renderer's size in logical pixels.
  41012. */
  41013. getSize( target ) {
  41014. return this._canvasTarget.getSize( target );
  41015. }
  41016. /**
  41017. * Sets the given pixel ratio and resizes the canvas if necessary.
  41018. *
  41019. * @param {number} [value=1] - The pixel ratio.
  41020. */
  41021. setPixelRatio( value = 1 ) {
  41022. this._canvasTarget.setPixelRatio( value );
  41023. }
  41024. /**
  41025. * This method allows to define the drawing buffer size by specifying
  41026. * width, height and pixel ratio all at once. The size of the drawing
  41027. * buffer is computed with this formula:
  41028. * ```js
  41029. * size.x = width * pixelRatio;
  41030. * size.y = height * pixelRatio;
  41031. * ```
  41032. *
  41033. * @param {number} width - The width in logical pixels.
  41034. * @param {number} height - The height in logical pixels.
  41035. * @param {number} pixelRatio - The pixel ratio.
  41036. */
  41037. setDrawingBufferSize( width, height, pixelRatio ) {
  41038. // Renderer can't be resized while presenting in XR.
  41039. if ( this.xr && this.xr.isPresenting ) return;
  41040. this._canvasTarget.setDrawingBufferSize( width, height, pixelRatio );
  41041. }
  41042. /**
  41043. * Sets the size of the renderer.
  41044. *
  41045. * @param {number} width - The width in logical pixels.
  41046. * @param {number} height - The height in logical pixels.
  41047. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  41048. */
  41049. setSize( width, height, updateStyle = true ) {
  41050. // Renderer can't be resized while presenting in XR.
  41051. if ( this.xr && this.xr.isPresenting ) return;
  41052. this._canvasTarget.setSize( width, height, updateStyle );
  41053. }
  41054. /**
  41055. * Defines a manual sort function for the opaque render list.
  41056. * Pass `null` to use the default sort.
  41057. *
  41058. * @param {Function} method - The sort function.
  41059. */
  41060. setOpaqueSort( method ) {
  41061. this._opaqueSort = method;
  41062. }
  41063. /**
  41064. * Defines a manual sort function for the transparent render list.
  41065. * Pass `null` to use the default sort.
  41066. *
  41067. * @param {Function} method - The sort function.
  41068. */
  41069. setTransparentSort( method ) {
  41070. this._transparentSort = method;
  41071. }
  41072. /**
  41073. * Returns the scissor rectangle.
  41074. *
  41075. * @param {Vector4} target - The method writes the result in this target object.
  41076. * @return {Vector4} The scissor rectangle.
  41077. */
  41078. getScissor( target ) {
  41079. return this._canvasTarget.getScissor( target );
  41080. }
  41081. /**
  41082. * Defines the scissor rectangle.
  41083. *
  41084. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  41085. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  41086. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  41087. * @param {number} width - The width of the scissor box in logical pixel unit.
  41088. * @param {number} height - The height of the scissor box in logical pixel unit.
  41089. */
  41090. setScissor( x, y, width, height ) {
  41091. this._canvasTarget.setScissor( x, y, width, height );
  41092. }
  41093. /**
  41094. * Returns the scissor test value.
  41095. *
  41096. * @return {boolean} Whether the scissor test should be enabled or not.
  41097. */
  41098. getScissorTest() {
  41099. return this._canvasTarget.getScissorTest();
  41100. }
  41101. /**
  41102. * Defines the scissor test.
  41103. *
  41104. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  41105. */
  41106. setScissorTest( boolean ) {
  41107. this._canvasTarget.setScissorTest( boolean );
  41108. // TODO: Move it to CanvasTarget event listener.
  41109. this.backend.setScissorTest( boolean );
  41110. }
  41111. /**
  41112. * Returns the viewport definition.
  41113. *
  41114. * @param {Vector4} target - The method writes the result in this target object.
  41115. * @return {Vector4} The viewport definition.
  41116. */
  41117. getViewport( target ) {
  41118. return this._canvasTarget.getViewport( target );
  41119. }
  41120. /**
  41121. * Defines the viewport.
  41122. *
  41123. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  41124. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  41125. * @param {number} width - The width of the viewport in logical pixel unit.
  41126. * @param {number} height - The height of the viewport in logical pixel unit.
  41127. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  41128. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  41129. */
  41130. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  41131. this._canvasTarget.setViewport( x, y, width, height, minDepth, maxDepth );
  41132. }
  41133. /**
  41134. * Returns the clear color.
  41135. *
  41136. * @param {Color} target - The method writes the result in this target object.
  41137. * @return {Color} The clear color.
  41138. */
  41139. getClearColor( target ) {
  41140. return target.copy( this._clearColor );
  41141. }
  41142. /**
  41143. * Defines the clear color and optionally the clear alpha.
  41144. *
  41145. * @param {Color} color - The clear color.
  41146. * @param {number} [alpha=1] - The clear alpha.
  41147. */
  41148. setClearColor( color, alpha = 1 ) {
  41149. this._clearColor.set( color );
  41150. this._clearColor.a = alpha;
  41151. }
  41152. /**
  41153. * Returns the clear alpha.
  41154. *
  41155. * @return {number} The clear alpha.
  41156. */
  41157. getClearAlpha() {
  41158. return this._clearColor.a;
  41159. }
  41160. /**
  41161. * Defines the clear alpha.
  41162. *
  41163. * @param {number} alpha - The clear alpha.
  41164. */
  41165. setClearAlpha( alpha ) {
  41166. this._clearColor.a = alpha;
  41167. }
  41168. /**
  41169. * Returns the clear depth.
  41170. *
  41171. * @return {number} The clear depth.
  41172. */
  41173. getClearDepth() {
  41174. return this._clearDepth;
  41175. }
  41176. /**
  41177. * Defines the clear depth.
  41178. *
  41179. * @param {number} depth - The clear depth.
  41180. */
  41181. setClearDepth( depth ) {
  41182. this._clearDepth = depth;
  41183. }
  41184. /**
  41185. * Returns the clear stencil.
  41186. *
  41187. * @return {number} The clear stencil.
  41188. */
  41189. getClearStencil() {
  41190. return this._clearStencil;
  41191. }
  41192. /**
  41193. * Defines the clear stencil.
  41194. *
  41195. * @param {number} stencil - The clear stencil.
  41196. */
  41197. setClearStencil( stencil ) {
  41198. this._clearStencil = stencil;
  41199. }
  41200. /**
  41201. * This method performs an occlusion query for the given 3D object.
  41202. * It returns `true` if the given 3D object is fully occluded by other
  41203. * 3D objects in the scene.
  41204. *
  41205. * @param {Object3D} object - The 3D object to test.
  41206. * @return {boolean} Whether the 3D object is fully occluded or not.
  41207. */
  41208. isOccluded( object ) {
  41209. const renderContext = this._currentRenderContext;
  41210. return renderContext && this.backend.isOccluded( renderContext, object );
  41211. }
  41212. /**
  41213. * Performs a manual clear operation. This method ignores `autoClear` properties.
  41214. *
  41215. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  41216. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  41217. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  41218. */
  41219. clear( color = true, depth = true, stencil = true ) {
  41220. if ( this._initialized === false ) {
  41221. throw new Error( 'Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  41222. }
  41223. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  41224. let renderContext = null;
  41225. if ( renderTarget !== null ) {
  41226. this._textures.updateRenderTarget( renderTarget );
  41227. const renderTargetData = this._textures.get( renderTarget );
  41228. renderContext = this._renderContexts.getForClear( renderTarget );
  41229. renderContext.textures = renderTargetData.textures;
  41230. renderContext.depthTexture = renderTargetData.depthTexture;
  41231. renderContext.width = renderTargetData.width;
  41232. renderContext.height = renderTargetData.height;
  41233. renderContext.renderTarget = renderTarget;
  41234. renderContext.depth = renderTarget.depthBuffer;
  41235. renderContext.stencil = renderTarget.stencilBuffer;
  41236. // #30329
  41237. renderContext.clearColorValue = this.backend.getClearColor();
  41238. renderContext.activeCubeFace = this.getActiveCubeFace();
  41239. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  41240. }
  41241. this.backend.clear( color, depth, stencil, renderContext );
  41242. if ( renderTarget !== null && this._renderTarget === null ) {
  41243. this._renderOutput( renderTarget );
  41244. }
  41245. }
  41246. /**
  41247. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  41248. */
  41249. clearColor() {
  41250. this.clear( true, false, false );
  41251. }
  41252. /**
  41253. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  41254. */
  41255. clearDepth() {
  41256. this.clear( false, true, false );
  41257. }
  41258. /**
  41259. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  41260. */
  41261. clearStencil() {
  41262. this.clear( false, false, true );
  41263. }
  41264. /**
  41265. * Async version of {@link Renderer#clear}.
  41266. *
  41267. * @async
  41268. * @deprecated
  41269. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  41270. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  41271. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  41272. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  41273. */
  41274. async clearAsync( color = true, depth = true, stencil = true ) {
  41275. warnOnce( 'Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41276. await this.init();
  41277. this.clear( color, depth, stencil );
  41278. }
  41279. /**
  41280. * Async version of {@link Renderer#clearColor}.
  41281. *
  41282. * @async
  41283. * @deprecated
  41284. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  41285. */
  41286. async clearColorAsync() {
  41287. warnOnce( 'Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41288. this.clear( true, false, false );
  41289. }
  41290. /**
  41291. * Async version of {@link Renderer#clearDepth}.
  41292. *
  41293. * @async
  41294. * @deprecated
  41295. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  41296. */
  41297. async clearDepthAsync() {
  41298. warnOnce( 'Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41299. this.clear( false, true, false );
  41300. }
  41301. /**
  41302. * Async version of {@link Renderer#clearStencil}.
  41303. *
  41304. * @async
  41305. * @deprecated
  41306. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  41307. */
  41308. async clearStencilAsync() {
  41309. warnOnce( 'Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41310. this.clear( false, false, true );
  41311. }
  41312. /**
  41313. * Returns `true` if a framebuffer target is needed to perform tone mapping or color space conversion.
  41314. * If this is the case, the renderer allocates an internal render target for that purpose.
  41315. *
  41316. */
  41317. get needsFrameBufferTarget() {
  41318. const useToneMapping = this.currentToneMapping !== NoToneMapping;
  41319. const useColorSpace = this.currentColorSpace !== ColorManagement.workingColorSpace;
  41320. return useToneMapping || useColorSpace;
  41321. }
  41322. /**
  41323. * The number of samples used for multi-sample anti-aliasing (MSAA).
  41324. *
  41325. * @type {number}
  41326. * @default 0
  41327. */
  41328. get samples() {
  41329. return this._samples;
  41330. }
  41331. /**
  41332. * The current number of samples used for multi-sample anti-aliasing (MSAA).
  41333. *
  41334. * When rendering to a custom render target, the number of samples of that render target is used.
  41335. * If the renderer needs an internal framebuffer target for tone mapping or color space conversion,
  41336. * the number of samples is set to 0.
  41337. *
  41338. * @type {number}
  41339. */
  41340. get currentSamples() {
  41341. let samples = this._samples;
  41342. if ( this._renderTarget !== null ) {
  41343. samples = this._renderTarget.samples;
  41344. } else if ( this.needsFrameBufferTarget ) {
  41345. samples = 0;
  41346. }
  41347. return samples;
  41348. }
  41349. /**
  41350. * The current tone mapping of the renderer. When not producing screen output,
  41351. * the tone mapping is always `NoToneMapping`.
  41352. *
  41353. * @type {number}
  41354. */
  41355. get currentToneMapping() {
  41356. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  41357. }
  41358. /**
  41359. * The current color space of the renderer. When not producing screen output,
  41360. * the color space is always the working color space.
  41361. *
  41362. * @type {string}
  41363. */
  41364. get currentColorSpace() {
  41365. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  41366. }
  41367. /**
  41368. * Returns `true` if the rendering settings are set to screen output.
  41369. *
  41370. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  41371. */
  41372. get isOutputTarget() {
  41373. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  41374. }
  41375. /**
  41376. * Frees all internal resources of the renderer. Call this method if the renderer
  41377. * is no longer in use by your app.
  41378. */
  41379. dispose() {
  41380. if ( this._initialized === true ) {
  41381. this.info.dispose();
  41382. this.backend.dispose();
  41383. this._animation.dispose();
  41384. this._objects.dispose();
  41385. this._geometries.dispose();
  41386. this._pipelines.dispose();
  41387. this._nodes.dispose();
  41388. this._bindings.dispose();
  41389. this._renderLists.dispose();
  41390. this._renderContexts.dispose();
  41391. this._textures.dispose();
  41392. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  41393. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  41394. if ( queryPool !== null ) queryPool.dispose();
  41395. } );
  41396. }
  41397. this.setRenderTarget( null );
  41398. this.setAnimationLoop( null );
  41399. }
  41400. /**
  41401. * Sets the given render target. Calling this method means the renderer does not
  41402. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  41403. * Use `null` as the first argument to reset the state.
  41404. *
  41405. * @param {?RenderTarget} renderTarget - The render target to set.
  41406. * @param {number} [activeCubeFace=0] - The active cube face.
  41407. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  41408. */
  41409. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  41410. this._renderTarget = renderTarget;
  41411. this._activeCubeFace = activeCubeFace;
  41412. this._activeMipmapLevel = activeMipmapLevel;
  41413. }
  41414. /**
  41415. * Returns the current render target.
  41416. *
  41417. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  41418. */
  41419. getRenderTarget() {
  41420. return this._renderTarget;
  41421. }
  41422. /**
  41423. * Sets the output render target for the renderer.
  41424. *
  41425. * @param {Object} renderTarget - The render target to set as the output target.
  41426. */
  41427. setOutputRenderTarget( renderTarget ) {
  41428. this._outputRenderTarget = renderTarget;
  41429. }
  41430. /**
  41431. * Returns the current output target.
  41432. *
  41433. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  41434. */
  41435. getOutputRenderTarget() {
  41436. return this._outputRenderTarget;
  41437. }
  41438. /**
  41439. * Sets the canvas target. The canvas target manages the HTML canvas
  41440. * or the offscreen canvas the renderer draws into.
  41441. *
  41442. * @param {CanvasTarget} canvasTarget - The canvas target.
  41443. */
  41444. setCanvasTarget( canvasTarget ) {
  41445. this._canvasTarget.removeEventListener( 'resize', this._onCanvasTargetResize );
  41446. this._canvasTarget = canvasTarget;
  41447. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  41448. }
  41449. /**
  41450. * Returns the current canvas target.
  41451. *
  41452. * @return {CanvasTarget} The current canvas target.
  41453. */
  41454. getCanvasTarget() {
  41455. return this._canvasTarget;
  41456. }
  41457. /**
  41458. * Resets the renderer to the initial state before WebXR started.
  41459. *
  41460. */
  41461. _resetXRState() {
  41462. this.backend.setXRTarget( null );
  41463. this.setOutputRenderTarget( null );
  41464. this.setRenderTarget( null );
  41465. this._frameBufferTarget.dispose();
  41466. this._frameBufferTarget = null;
  41467. }
  41468. /**
  41469. * Callback for {@link Renderer#setRenderObjectFunction}.
  41470. *
  41471. * @callback renderObjectFunction
  41472. * @param {Object3D} object - The 3D object.
  41473. * @param {Scene} scene - The scene the 3D object belongs to.
  41474. * @param {Camera} camera - The camera the object should be rendered with.
  41475. * @param {BufferGeometry} geometry - The object's geometry.
  41476. * @param {Material} material - The object's material.
  41477. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  41478. * @param {LightsNode} lightsNode - The current lights node.
  41479. * @param {ClippingContext} clippingContext - The clipping context.
  41480. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  41481. */
  41482. /**
  41483. * Sets the given render object function. Calling this method overwrites the default implementation
  41484. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  41485. * if you want to modify the way objects are rendered. For example you can define things like "every
  41486. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  41487. * The custom function must always call `renderObject()` in its implementation.
  41488. *
  41489. * Use `null` as the first argument to reset the state.
  41490. *
  41491. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  41492. */
  41493. setRenderObjectFunction( renderObjectFunction ) {
  41494. this._renderObjectFunction = renderObjectFunction;
  41495. }
  41496. /**
  41497. * Returns the current render object function.
  41498. *
  41499. * @return {?Function} The current render object function. Returns `null` if no function is set.
  41500. */
  41501. getRenderObjectFunction() {
  41502. return this._renderObjectFunction;
  41503. }
  41504. /**
  41505. * Execute a single or an array of compute nodes. This method can only be called
  41506. * if the renderer has been initialized.
  41507. *
  41508. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  41509. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  41510. * - A single number representing count, or
  41511. * - An array [x, y, z] representing dispatch size, or
  41512. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  41513. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  41514. */
  41515. compute( computeNodes, dispatchSize = null ) {
  41516. if ( this._isDeviceLost === true ) return;
  41517. if ( this._initialized === false ) {
  41518. warn( 'Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  41519. return this.computeAsync( computeNodes, dispatchSize );
  41520. }
  41521. //
  41522. const nodeFrame = this._nodes.nodeFrame;
  41523. const previousRenderId = nodeFrame.renderId;
  41524. //
  41525. this.info.calls ++;
  41526. this.info.compute.calls ++;
  41527. this.info.compute.frameCalls ++;
  41528. nodeFrame.renderId = this.info.calls;
  41529. //
  41530. this.backend.updateTimeStampUID( computeNodes );
  41531. this.inspector.beginCompute( this.backend.getTimestampUID( computeNodes ), computeNodes );
  41532. //
  41533. const backend = this.backend;
  41534. const pipelines = this._pipelines;
  41535. const bindings = this._bindings;
  41536. const nodes = this._nodes;
  41537. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  41538. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  41539. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  41540. }
  41541. backend.beginCompute( computeNodes );
  41542. for ( const computeNode of computeList ) {
  41543. // onInit
  41544. if ( pipelines.has( computeNode ) === false ) {
  41545. const dispose = () => {
  41546. computeNode.removeEventListener( 'dispose', dispose );
  41547. pipelines.delete( computeNode );
  41548. bindings.deleteForCompute( computeNode );
  41549. nodes.delete( computeNode );
  41550. };
  41551. computeNode.addEventListener( 'dispose', dispose );
  41552. //
  41553. const onInitFn = computeNode.onInitFunction;
  41554. if ( onInitFn !== null ) {
  41555. onInitFn.call( computeNode, { renderer: this } );
  41556. }
  41557. }
  41558. nodes.updateForCompute( computeNode );
  41559. bindings.updateForCompute( computeNode );
  41560. const computeBindings = bindings.getForCompute( computeNode );
  41561. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  41562. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSize );
  41563. }
  41564. backend.finishCompute( computeNodes );
  41565. //
  41566. nodeFrame.renderId = previousRenderId;
  41567. //
  41568. this.inspector.finishCompute( this.backend.getTimestampUID( computeNodes ) );
  41569. }
  41570. /**
  41571. * Execute a single or an array of compute nodes.
  41572. *
  41573. * @async
  41574. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  41575. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  41576. * - A single number representing count, or
  41577. * - An array [x, y, z] representing dispatch size, or
  41578. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  41579. * @return {Promise} A Promise that resolve when the compute has finished.
  41580. */
  41581. async computeAsync( computeNodes, dispatchSize = null ) {
  41582. if ( this._initialized === false ) await this.init();
  41583. this.compute( computeNodes, dispatchSize );
  41584. }
  41585. /**
  41586. * Checks if the given feature is supported by the selected backend.
  41587. *
  41588. * @async
  41589. * @deprecated
  41590. * @param {string} name - The feature's name.
  41591. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  41592. */
  41593. async hasFeatureAsync( name ) {
  41594. warnOnce( 'Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41595. await this.init();
  41596. return this.hasFeature( name );
  41597. }
  41598. async resolveTimestampsAsync( type = 'render' ) {
  41599. if ( this._initialized === false ) await this.init();
  41600. return this.backend.resolveTimestampsAsync( type );
  41601. }
  41602. /**
  41603. * Checks if the given feature is supported by the selected backend. If the
  41604. * renderer has not been initialized, this method always returns `false`.
  41605. *
  41606. * @param {string} name - The feature's name.
  41607. * @return {boolean} Whether the feature is supported or not.
  41608. */
  41609. hasFeature( name ) {
  41610. if ( this._initialized === false ) {
  41611. throw new Error( 'Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  41612. }
  41613. return this.backend.hasFeature( name );
  41614. }
  41615. /**
  41616. * Returns `true` when the renderer has been initialized.
  41617. *
  41618. * @return {boolean} Whether the renderer has been initialized or not.
  41619. */
  41620. hasInitialized() {
  41621. return this._initialized;
  41622. }
  41623. /**
  41624. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  41625. * (which can cause noticeable lags due to decode and GPU upload overhead).
  41626. *
  41627. * @async
  41628. * @deprecated
  41629. * @param {Texture} texture - The texture.
  41630. * @return {Promise} A Promise that resolves when the texture has been initialized.
  41631. */
  41632. async initTextureAsync( texture ) {
  41633. warnOnce( 'Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41634. await this.init();
  41635. this.initTexture( texture );
  41636. }
  41637. /**
  41638. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  41639. * (which can cause noticeable lags due to decode and GPU upload overhead).
  41640. *
  41641. * This method can only be used if the renderer has been initialized.
  41642. *
  41643. * @param {Texture} texture - The texture.
  41644. */
  41645. initTexture( texture ) {
  41646. if ( this._initialized === false ) {
  41647. throw new Error( 'Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  41648. }
  41649. this._textures.updateTexture( texture );
  41650. }
  41651. /**
  41652. * Copies the current bound framebuffer into the given texture.
  41653. *
  41654. * @param {FramebufferTexture} framebufferTexture - The texture.
  41655. * @param {?(Vector2|Vector4)} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  41656. */
  41657. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  41658. if ( rectangle !== null ) {
  41659. if ( rectangle.isVector2 ) {
  41660. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  41661. } else if ( rectangle.isVector4 ) {
  41662. rectangle = _vector4.copy( rectangle ).floor();
  41663. } else {
  41664. error( 'Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  41665. return;
  41666. }
  41667. } else {
  41668. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  41669. }
  41670. //
  41671. let renderContext = this._currentRenderContext;
  41672. let renderTarget;
  41673. if ( renderContext !== null ) {
  41674. renderTarget = renderContext.renderTarget;
  41675. } else {
  41676. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  41677. if ( renderTarget !== null ) {
  41678. this._textures.updateRenderTarget( renderTarget );
  41679. renderContext = this._textures.get( renderTarget );
  41680. }
  41681. }
  41682. //
  41683. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  41684. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  41685. this._inspector.copyFramebufferToTexture( framebufferTexture );
  41686. }
  41687. /**
  41688. * Copies data of the given source texture into a destination texture.
  41689. *
  41690. * @param {Texture} srcTexture - The source texture.
  41691. * @param {Texture} dstTexture - The destination texture.
  41692. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  41693. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  41694. * @param {number} [srcLevel=0] - The source mip level to copy from.
  41695. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  41696. */
  41697. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  41698. this._textures.updateTexture( srcTexture );
  41699. this._textures.updateTexture( dstTexture );
  41700. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  41701. this._inspector.copyTextureToTexture( srcTexture, dstTexture );
  41702. }
  41703. /**
  41704. * Reads pixel data from the given render target.
  41705. *
  41706. * @async
  41707. * @param {RenderTarget} renderTarget - The render target to read from.
  41708. * @param {number} x - The `x` coordinate of the copy region's origin.
  41709. * @param {number} y - The `y` coordinate of the copy region's origin.
  41710. * @param {number} width - The width of the copy region.
  41711. * @param {number} height - The height of the copy region.
  41712. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  41713. * @param {number} [faceIndex=0] - The active cube face index.
  41714. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  41715. */
  41716. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  41717. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  41718. }
  41719. /**
  41720. * Analyzes the given 3D object's hierarchy and builds render lists from the
  41721. * processed hierarchy.
  41722. *
  41723. * @param {Object3D} object - The 3D object to process (usually a scene).
  41724. * @param {Camera} camera - The camera the object is rendered with.
  41725. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  41726. * @param {RenderList} renderList - The current render list.
  41727. * @param {ClippingContext} clippingContext - The current clipping context.
  41728. */
  41729. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  41730. if ( object.visible === false ) return;
  41731. const visible = object.layers.test( camera.layers );
  41732. if ( visible ) {
  41733. if ( object.isGroup ) {
  41734. groupOrder = object.renderOrder;
  41735. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  41736. } else if ( object.isLOD ) {
  41737. if ( object.autoUpdate === true ) object.update( camera );
  41738. } else if ( object.isLight ) {
  41739. renderList.pushLight( object );
  41740. } else if ( object.isSprite ) {
  41741. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  41742. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  41743. if ( this.sortObjects === true ) {
  41744. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  41745. }
  41746. const { geometry, material } = object;
  41747. if ( material.visible ) {
  41748. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  41749. }
  41750. }
  41751. } else if ( object.isLineLoop ) {
  41752. error( 'Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  41753. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  41754. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  41755. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  41756. const { geometry, material } = object;
  41757. if ( this.sortObjects === true ) {
  41758. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  41759. _vector4
  41760. .copy( geometry.boundingSphere.center )
  41761. .applyMatrix4( object.matrixWorld )
  41762. .applyMatrix4( _projScreenMatrix );
  41763. }
  41764. if ( Array.isArray( material ) ) {
  41765. const groups = geometry.groups;
  41766. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  41767. const group = groups[ i ];
  41768. const groupMaterial = material[ group.materialIndex ];
  41769. if ( groupMaterial && groupMaterial.visible ) {
  41770. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  41771. }
  41772. }
  41773. } else if ( material.visible ) {
  41774. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  41775. }
  41776. }
  41777. }
  41778. }
  41779. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  41780. const baseRenderList = renderList;
  41781. // replace render list
  41782. renderList = this._renderLists.get( object, camera );
  41783. renderList.begin();
  41784. baseRenderList.pushBundle( {
  41785. bundleGroup: object,
  41786. camera,
  41787. renderList,
  41788. } );
  41789. renderList.finish();
  41790. }
  41791. const children = object.children;
  41792. for ( let i = 0, l = children.length; i < l; i ++ ) {
  41793. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  41794. }
  41795. }
  41796. /**
  41797. * Renders the given render bundles.
  41798. *
  41799. * @private
  41800. * @param {Array<Object>} bundles - Array with render bundle data.
  41801. * @param {Scene} sceneRef - The scene the render bundles belong to.
  41802. * @param {LightsNode} lightsNode - The current lights node.
  41803. */
  41804. _renderBundles( bundles, sceneRef, lightsNode ) {
  41805. for ( const bundle of bundles ) {
  41806. this._renderBundle( bundle, sceneRef, lightsNode );
  41807. }
  41808. }
  41809. /**
  41810. * Renders the transparent objects from the given render lists.
  41811. *
  41812. * @private
  41813. * @param {Array<Object>} renderList - The transparent render list.
  41814. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  41815. * @param {Camera} camera - The camera the render list should be rendered with.
  41816. * @param {Scene} scene - The scene the render list belongs to.
  41817. * @param {LightsNode} lightsNode - The current lights node.
  41818. */
  41819. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  41820. if ( doublePassList.length > 0 ) {
  41821. // render back side
  41822. for ( const { material } of doublePassList ) {
  41823. material.side = BackSide;
  41824. }
  41825. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  41826. // render front side
  41827. for ( const { material } of doublePassList ) {
  41828. material.side = FrontSide;
  41829. }
  41830. this._renderObjects( renderList, camera, scene, lightsNode );
  41831. // restore
  41832. for ( const { material } of doublePassList ) {
  41833. material.side = DoubleSide;
  41834. }
  41835. } else {
  41836. this._renderObjects( renderList, camera, scene, lightsNode );
  41837. }
  41838. }
  41839. /**
  41840. * Renders the objects from the given render list.
  41841. *
  41842. * @private
  41843. * @param {Array<Object>} renderList - The render list.
  41844. * @param {Camera} camera - The camera the render list should be rendered with.
  41845. * @param {Scene} scene - The scene the render list belongs to.
  41846. * @param {LightsNode} lightsNode - The current lights node.
  41847. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  41848. */
  41849. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  41850. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  41851. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  41852. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  41853. }
  41854. }
  41855. /**
  41856. * Retrieves shadow nodes for the given material. This is used to setup shadow passes.
  41857. * The result is cached per material and updated when the material's version changes.
  41858. *
  41859. * @param {Material} material
  41860. * @returns {Object} - The shadow nodes for the material.
  41861. */
  41862. _getShadowNodes( material ) {
  41863. const version = material.version;
  41864. let cache = this._cacheShadowNodes.get( material );
  41865. if ( cache === undefined || cache.version !== version ) {
  41866. const hasMap = material.map !== null;
  41867. const hasColorNode = material.colorNode && material.colorNode.isNode;
  41868. const hasCastShadowNode = material.castShadowNode && material.castShadowNode.isNode;
  41869. let positionNode = null;
  41870. let colorNode = null;
  41871. let depthNode = null;
  41872. if ( hasMap || hasColorNode || hasCastShadowNode ) {
  41873. let shadowRGB;
  41874. let shadowAlpha;
  41875. if ( hasCastShadowNode ) {
  41876. shadowRGB = material.castShadowNode.rgb;
  41877. shadowAlpha = material.castShadowNode.a;
  41878. } else {
  41879. shadowRGB = vec3( 0 );
  41880. shadowAlpha = float( 1 );
  41881. }
  41882. if ( hasMap ) {
  41883. shadowAlpha = shadowAlpha.mul( reference( 'map', 'texture', material ).a );
  41884. }
  41885. if ( hasColorNode ) {
  41886. shadowAlpha = shadowAlpha.mul( material.colorNode.a );
  41887. }
  41888. colorNode = vec4( shadowRGB, shadowAlpha );
  41889. }
  41890. if ( material.depthNode && material.depthNode.isNode ) {
  41891. depthNode = material.depthNode;
  41892. }
  41893. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  41894. positionNode = material.castShadowPositionNode;
  41895. } else if ( material.positionNode && material.positionNode.isNode ) {
  41896. positionNode = material.positionNode;
  41897. }
  41898. cache = {
  41899. version,
  41900. colorNode,
  41901. depthNode,
  41902. positionNode
  41903. };
  41904. this._cacheShadowNodes.set( material, cache );
  41905. }
  41906. return cache;
  41907. }
  41908. /**
  41909. * This method represents the default render object function that manages the render lifecycle
  41910. * of the object.
  41911. *
  41912. * @param {Object3D} object - The 3D object.
  41913. * @param {Scene} scene - The scene the 3D object belongs to.
  41914. * @param {Camera} camera - The camera the object should be rendered with.
  41915. * @param {BufferGeometry} geometry - The object's geometry.
  41916. * @param {Material} material - The object's material.
  41917. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  41918. * @param {LightsNode} lightsNode - The current lights node.
  41919. * @param {?ClippingContext} clippingContext - The clipping context.
  41920. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  41921. */
  41922. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  41923. let materialOverride = false;
  41924. let materialColorNode;
  41925. let materialDepthNode;
  41926. let materialPositionNode;
  41927. let materialSide;
  41928. //
  41929. object.onBeforeRender( this, scene, camera, geometry, material, group );
  41930. //
  41931. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  41932. const overrideMaterial = scene.overrideMaterial;
  41933. materialOverride = true;
  41934. // store original nodes
  41935. materialColorNode = scene.overrideMaterial.colorNode;
  41936. materialDepthNode = scene.overrideMaterial.depthNode;
  41937. materialPositionNode = scene.overrideMaterial.positionNode;
  41938. materialSide = scene.overrideMaterial.side;
  41939. if ( material.positionNode && material.positionNode.isNode ) {
  41940. overrideMaterial.positionNode = material.positionNode;
  41941. }
  41942. overrideMaterial.alphaTest = material.alphaTest;
  41943. overrideMaterial.alphaMap = material.alphaMap;
  41944. overrideMaterial.transparent = material.transparent || material.transmission > 0 ||
  41945. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  41946. ( material.backdropNode && material.backdropNode.isNode );
  41947. if ( overrideMaterial.isShadowPassMaterial ) {
  41948. const { colorNode, depthNode, positionNode } = this._getShadowNodes( material );
  41949. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  41950. if ( colorNode !== null ) overrideMaterial.colorNode = colorNode;
  41951. if ( depthNode !== null ) overrideMaterial.depthNode = depthNode;
  41952. if ( positionNode !== null ) overrideMaterial.positionNode = positionNode;
  41953. }
  41954. material = overrideMaterial;
  41955. }
  41956. //
  41957. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  41958. material.side = BackSide;
  41959. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  41960. material.side = FrontSide;
  41961. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  41962. material.side = DoubleSide;
  41963. } else {
  41964. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  41965. }
  41966. //
  41967. if ( materialOverride ) {
  41968. scene.overrideMaterial.colorNode = materialColorNode;
  41969. scene.overrideMaterial.depthNode = materialDepthNode;
  41970. scene.overrideMaterial.positionNode = materialPositionNode;
  41971. scene.overrideMaterial.side = materialSide;
  41972. }
  41973. //
  41974. object.onAfterRender( this, scene, camera, geometry, material, group );
  41975. }
  41976. /**
  41977. * This method represents the default `_handleObjectFunction` implementation which creates
  41978. * a render object from the given data and performs the draw command with the selected backend.
  41979. *
  41980. * @private
  41981. * @param {Object3D} object - The 3D object.
  41982. * @param {Material} material - The object's material.
  41983. * @param {Scene} scene - The scene the 3D object belongs to.
  41984. * @param {Camera} camera - The camera the object should be rendered with.
  41985. * @param {LightsNode} lightsNode - The current lights node.
  41986. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  41987. * @param {ClippingContext} clippingContext - The clipping context.
  41988. * @param {string} [passId] - An optional ID for identifying the pass.
  41989. */
  41990. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  41991. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  41992. renderObject.drawRange = object.geometry.drawRange;
  41993. renderObject.group = group;
  41994. //
  41995. const needsRefresh = this._nodes.needsRefresh( renderObject );
  41996. if ( needsRefresh ) {
  41997. this._nodes.updateBefore( renderObject );
  41998. this._geometries.updateForRender( renderObject );
  41999. this._nodes.updateForRender( renderObject );
  42000. this._bindings.updateForRender( renderObject );
  42001. }
  42002. this._pipelines.updateForRender( renderObject );
  42003. //
  42004. if ( this._currentRenderBundle !== null ) {
  42005. const renderBundleData = this.backend.get( this._currentRenderBundle );
  42006. renderBundleData.renderObjects.push( renderObject );
  42007. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  42008. }
  42009. this.backend.draw( renderObject, this.info );
  42010. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  42011. }
  42012. /**
  42013. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  42014. * Used in `compileAsync()`.
  42015. *
  42016. * @private
  42017. * @param {Object3D} object - The 3D object.
  42018. * @param {Material} material - The object's material.
  42019. * @param {Scene} scene - The scene the 3D object belongs to.
  42020. * @param {Camera} camera - The camera the object should be rendered with.
  42021. * @param {LightsNode} lightsNode - The current lights node.
  42022. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  42023. * @param {ClippingContext} clippingContext - The clipping context.
  42024. * @param {string} [passId] - An optional ID for identifying the pass.
  42025. */
  42026. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  42027. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  42028. renderObject.drawRange = object.geometry.drawRange;
  42029. renderObject.group = group;
  42030. //
  42031. this._nodes.updateBefore( renderObject );
  42032. this._geometries.updateForRender( renderObject );
  42033. this._nodes.updateForRender( renderObject );
  42034. this._bindings.updateForRender( renderObject );
  42035. this._pipelines.getForRender( renderObject, this._compilationPromises );
  42036. this._nodes.updateAfter( renderObject );
  42037. }
  42038. /**
  42039. * Callback when the canvas has been resized.
  42040. *
  42041. * @private
  42042. */
  42043. _onCanvasTargetResize() {
  42044. if ( this._initialized ) this.backend.updateSize();
  42045. }
  42046. /**
  42047. * Alias for `compileAsync()`.
  42048. *
  42049. * @method
  42050. * @param {Object3D} scene - The scene or 3D object to precompile.
  42051. * @param {Camera} camera - The camera that is used to render the scene.
  42052. * @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.
  42053. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  42054. */
  42055. get compile() {
  42056. return this.compileAsync;
  42057. }
  42058. }
  42059. /**
  42060. * A binding represents the connection between a resource (like a texture, sampler
  42061. * or uniform buffer) and the resource definition in a shader stage.
  42062. *
  42063. * This module is an abstract base class for all concrete bindings types.
  42064. *
  42065. * @abstract
  42066. * @private
  42067. */
  42068. class Binding {
  42069. /**
  42070. * Constructs a new binding.
  42071. *
  42072. * @param {string} [name=''] - The binding's name.
  42073. */
  42074. constructor( name = '' ) {
  42075. /**
  42076. * The binding's name.
  42077. *
  42078. * @type {string}
  42079. */
  42080. this.name = name;
  42081. /**
  42082. * A bitmask that defines in what shader stages the
  42083. * binding's resource is accessible.
  42084. *
  42085. * @type {number}
  42086. */
  42087. this.visibility = 0;
  42088. }
  42089. /**
  42090. * Makes sure binding's resource is visible for the given shader stage.
  42091. *
  42092. * @param {number} visibility - The shader stage.
  42093. */
  42094. setVisibility( visibility ) {
  42095. this.visibility |= visibility;
  42096. }
  42097. /**
  42098. * Clones the binding.
  42099. *
  42100. * @return {Binding} The cloned binding.
  42101. */
  42102. clone() {
  42103. return Object.assign( new this.constructor(), this );
  42104. }
  42105. }
  42106. /**
  42107. * This function is usually called with the length in bytes of an array buffer.
  42108. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  42109. *
  42110. * @function
  42111. * @param {number} floatLength - The buffer length.
  42112. * @return {number} The padded length.
  42113. */
  42114. function getFloatLength( floatLength ) {
  42115. // ensure chunk size alignment (STD140 layout)
  42116. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  42117. }
  42118. /**
  42119. * Represents a buffer binding type.
  42120. *
  42121. * @private
  42122. * @abstract
  42123. * @augments Binding
  42124. */
  42125. class Buffer extends Binding {
  42126. /**
  42127. * Constructs a new buffer.
  42128. *
  42129. * @param {string} name - The buffer's name.
  42130. * @param {TypedArray} [buffer=null] - The buffer.
  42131. */
  42132. constructor( name, buffer = null ) {
  42133. super( name );
  42134. /**
  42135. * This flag can be used for type testing.
  42136. *
  42137. * @type {boolean}
  42138. * @readonly
  42139. * @default true
  42140. */
  42141. this.isBuffer = true;
  42142. /**
  42143. * The bytes per element.
  42144. *
  42145. * @type {number}
  42146. */
  42147. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  42148. /**
  42149. * A reference to the internal buffer.
  42150. *
  42151. * @private
  42152. * @type {TypedArray}
  42153. */
  42154. this._buffer = buffer;
  42155. }
  42156. /**
  42157. * The buffer's byte length.
  42158. *
  42159. * @type {number}
  42160. * @readonly
  42161. */
  42162. get byteLength() {
  42163. return getFloatLength( this._buffer.byteLength );
  42164. }
  42165. /**
  42166. * A reference to the internal buffer.
  42167. *
  42168. * @type {Float32Array}
  42169. * @readonly
  42170. */
  42171. get buffer() {
  42172. return this._buffer;
  42173. }
  42174. /**
  42175. * Updates the binding.
  42176. *
  42177. * @return {boolean} Whether the buffer has been updated and must be
  42178. * uploaded to the GPU.
  42179. */
  42180. update() {
  42181. return true;
  42182. }
  42183. }
  42184. /**
  42185. * Represents a uniform buffer binding type.
  42186. *
  42187. * @private
  42188. * @augments Buffer
  42189. */
  42190. class UniformBuffer extends Buffer {
  42191. /**
  42192. * Constructs a new uniform buffer.
  42193. *
  42194. * @param {string} name - The buffer's name.
  42195. * @param {TypedArray} [buffer=null] - The buffer.
  42196. */
  42197. constructor( name, buffer = null ) {
  42198. super( name, buffer );
  42199. /**
  42200. * This flag can be used for type testing.
  42201. *
  42202. * @type {boolean}
  42203. * @readonly
  42204. * @default true
  42205. */
  42206. this.isUniformBuffer = true;
  42207. }
  42208. }
  42209. let _id$4 = 0;
  42210. /**
  42211. * A special form of uniform buffer binding type.
  42212. * It's buffer value is managed by a node object.
  42213. *
  42214. * @private
  42215. * @augments UniformBuffer
  42216. */
  42217. class NodeUniformBuffer extends UniformBuffer {
  42218. /**
  42219. * Constructs a new node-based uniform buffer.
  42220. *
  42221. * @param {BufferNode} nodeUniform - The uniform buffer node.
  42222. * @param {UniformGroupNode} groupNode - The uniform group node.
  42223. */
  42224. constructor( nodeUniform, groupNode ) {
  42225. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  42226. /**
  42227. * The uniform buffer node.
  42228. *
  42229. * @type {BufferNode}
  42230. */
  42231. this.nodeUniform = nodeUniform;
  42232. /**
  42233. * The uniform group node.
  42234. *
  42235. * @type {UniformGroupNode}
  42236. */
  42237. this.groupNode = groupNode;
  42238. }
  42239. /**
  42240. * The uniform buffer.
  42241. *
  42242. * @type {Float32Array}
  42243. */
  42244. get buffer() {
  42245. return this.nodeUniform.value;
  42246. }
  42247. }
  42248. /**
  42249. * This class represents a uniform buffer binding but with
  42250. * an API that allows to maintain individual uniform objects.
  42251. *
  42252. * @private
  42253. * @augments UniformBuffer
  42254. */
  42255. class UniformsGroup extends UniformBuffer {
  42256. /**
  42257. * Constructs a new uniforms group.
  42258. *
  42259. * @param {string} name - The group's name.
  42260. */
  42261. constructor( name ) {
  42262. super( name );
  42263. /**
  42264. * This flag can be used for type testing.
  42265. *
  42266. * @type {boolean}
  42267. * @readonly
  42268. * @default true
  42269. */
  42270. this.isUniformsGroup = true;
  42271. /**
  42272. * An array with the raw uniform values.
  42273. *
  42274. * @private
  42275. * @type {?Array<number>}
  42276. * @default null
  42277. */
  42278. this._values = null;
  42279. /**
  42280. * An array of uniform objects.
  42281. *
  42282. * The order of uniforms in this array must match the order of uniforms in the shader.
  42283. *
  42284. * @type {Array<Uniform>}
  42285. */
  42286. this.uniforms = [];
  42287. }
  42288. /**
  42289. * Adds a uniform to this group.
  42290. *
  42291. * @param {Uniform} uniform - The uniform to add.
  42292. * @return {UniformsGroup} A reference to this group.
  42293. */
  42294. addUniform( uniform ) {
  42295. this.uniforms.push( uniform );
  42296. return this;
  42297. }
  42298. /**
  42299. * Removes a uniform from this group.
  42300. *
  42301. * @param {Uniform} uniform - The uniform to remove.
  42302. * @return {UniformsGroup} A reference to this group.
  42303. */
  42304. removeUniform( uniform ) {
  42305. const index = this.uniforms.indexOf( uniform );
  42306. if ( index !== -1 ) {
  42307. this.uniforms.splice( index, 1 );
  42308. }
  42309. return this;
  42310. }
  42311. /**
  42312. * An array with the raw uniform values.
  42313. *
  42314. * @type {Array<number>}
  42315. */
  42316. get values() {
  42317. if ( this._values === null ) {
  42318. this._values = Array.from( this.buffer );
  42319. }
  42320. return this._values;
  42321. }
  42322. /**
  42323. * A Float32 array buffer with the uniform values.
  42324. *
  42325. * @type {Float32Array}
  42326. */
  42327. get buffer() {
  42328. let buffer = this._buffer;
  42329. if ( buffer === null ) {
  42330. const byteLength = this.byteLength;
  42331. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  42332. this._buffer = buffer;
  42333. }
  42334. return buffer;
  42335. }
  42336. /**
  42337. * The byte length of the buffer with correct buffer alignment.
  42338. *
  42339. * @type {number}
  42340. */
  42341. get byteLength() {
  42342. const bytesPerElement = this.bytesPerElement;
  42343. let offset = 0; // global buffer offset in bytes
  42344. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  42345. const uniform = this.uniforms[ i ];
  42346. const boundary = uniform.boundary;
  42347. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  42348. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  42349. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  42350. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  42351. offset += chunkPadding;
  42352. // Check for chunk overflow
  42353. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  42354. // Add padding to the end of the chunk
  42355. offset += ( GPU_CHUNK_BYTES - chunkStart );
  42356. }
  42357. uniform.offset = offset / bytesPerElement;
  42358. offset += itemSize;
  42359. }
  42360. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  42361. }
  42362. /**
  42363. * Updates this group by updating each uniform object of
  42364. * the internal uniform list. The uniform objects check if their
  42365. * values has actually changed so this method only returns
  42366. * `true` if there is a real value change.
  42367. *
  42368. * @return {boolean} Whether the uniforms have been updated and
  42369. * must be uploaded to the GPU.
  42370. */
  42371. update() {
  42372. let updated = false;
  42373. for ( const uniform of this.uniforms ) {
  42374. if ( this.updateByType( uniform ) === true ) {
  42375. updated = true;
  42376. }
  42377. }
  42378. return updated;
  42379. }
  42380. /**
  42381. * Updates a given uniform by calling an update method matching
  42382. * the uniforms type.
  42383. *
  42384. * @param {Uniform} uniform - The uniform to update.
  42385. * @return {boolean} Whether the uniform has been updated or not.
  42386. */
  42387. updateByType( uniform ) {
  42388. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  42389. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  42390. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  42391. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  42392. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  42393. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  42394. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  42395. error( 'WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  42396. }
  42397. /**
  42398. * Updates a given Number uniform.
  42399. *
  42400. * @param {NumberUniform} uniform - The Number uniform.
  42401. * @return {boolean} Whether the uniform has been updated or not.
  42402. */
  42403. updateNumber( uniform ) {
  42404. let updated = false;
  42405. const a = this.values;
  42406. const v = uniform.getValue();
  42407. const offset = uniform.offset;
  42408. const type = uniform.getType();
  42409. if ( a[ offset ] !== v ) {
  42410. const b = this._getBufferForType( type );
  42411. b[ offset ] = a[ offset ] = v;
  42412. updated = true;
  42413. }
  42414. return updated;
  42415. }
  42416. /**
  42417. * Updates a given Vector2 uniform.
  42418. *
  42419. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  42420. * @return {boolean} Whether the uniform has been updated or not.
  42421. */
  42422. updateVector2( uniform ) {
  42423. let updated = false;
  42424. const a = this.values;
  42425. const v = uniform.getValue();
  42426. const offset = uniform.offset;
  42427. const type = uniform.getType();
  42428. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  42429. const b = this._getBufferForType( type );
  42430. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  42431. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  42432. updated = true;
  42433. }
  42434. return updated;
  42435. }
  42436. /**
  42437. * Updates a given Vector3 uniform.
  42438. *
  42439. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  42440. * @return {boolean} Whether the uniform has been updated or not.
  42441. */
  42442. updateVector3( uniform ) {
  42443. let updated = false;
  42444. const a = this.values;
  42445. const v = uniform.getValue();
  42446. const offset = uniform.offset;
  42447. const type = uniform.getType();
  42448. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  42449. const b = this._getBufferForType( type );
  42450. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  42451. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  42452. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  42453. updated = true;
  42454. }
  42455. return updated;
  42456. }
  42457. /**
  42458. * Updates a given Vector4 uniform.
  42459. *
  42460. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  42461. * @return {boolean} Whether the uniform has been updated or not.
  42462. */
  42463. updateVector4( uniform ) {
  42464. let updated = false;
  42465. const a = this.values;
  42466. const v = uniform.getValue();
  42467. const offset = uniform.offset;
  42468. const type = uniform.getType();
  42469. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  42470. const b = this._getBufferForType( type );
  42471. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  42472. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  42473. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  42474. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  42475. updated = true;
  42476. }
  42477. return updated;
  42478. }
  42479. /**
  42480. * Updates a given Color uniform.
  42481. *
  42482. * @param {ColorUniform} uniform - The Color uniform.
  42483. * @return {boolean} Whether the uniform has been updated or not.
  42484. */
  42485. updateColor( uniform ) {
  42486. let updated = false;
  42487. const a = this.values;
  42488. const c = uniform.getValue();
  42489. const offset = uniform.offset;
  42490. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  42491. const b = this.buffer;
  42492. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  42493. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  42494. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  42495. updated = true;
  42496. }
  42497. return updated;
  42498. }
  42499. /**
  42500. * Updates a given Matrix3 uniform.
  42501. *
  42502. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  42503. * @return {boolean} Whether the uniform has been updated or not.
  42504. */
  42505. updateMatrix3( uniform ) {
  42506. let updated = false;
  42507. const a = this.values;
  42508. const e = uniform.getValue().elements;
  42509. const offset = uniform.offset;
  42510. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  42511. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  42512. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  42513. const b = this.buffer;
  42514. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  42515. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  42516. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  42517. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  42518. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  42519. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  42520. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  42521. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  42522. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  42523. updated = true;
  42524. }
  42525. return updated;
  42526. }
  42527. /**
  42528. * Updates a given Matrix4 uniform.
  42529. *
  42530. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  42531. * @return {boolean} Whether the uniform has been updated or not.
  42532. */
  42533. updateMatrix4( uniform ) {
  42534. let updated = false;
  42535. const a = this.values;
  42536. const e = uniform.getValue().elements;
  42537. const offset = uniform.offset;
  42538. if ( arraysEqual( a, e, offset ) === false ) {
  42539. const b = this.buffer;
  42540. b.set( e, offset );
  42541. setArray( a, e, offset );
  42542. updated = true;
  42543. }
  42544. return updated;
  42545. }
  42546. /**
  42547. * Returns a typed array that matches the given data type.
  42548. *
  42549. * @param {string} type - The data type.
  42550. * @return {TypedArray} The typed array.
  42551. */
  42552. _getBufferForType( type ) {
  42553. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  42554. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  42555. return this.buffer;
  42556. }
  42557. }
  42558. /**
  42559. * Sets the values of the second array to the first array.
  42560. *
  42561. * @private
  42562. * @param {TypedArray} a - The first array.
  42563. * @param {TypedArray} b - The second array.
  42564. * @param {number} offset - An index offset for the first array.
  42565. */
  42566. function setArray( a, b, offset ) {
  42567. for ( let i = 0, l = b.length; i < l; i ++ ) {
  42568. a[ offset + i ] = b[ i ];
  42569. }
  42570. }
  42571. /**
  42572. * Returns `true` if the given arrays are equal.
  42573. *
  42574. * @private
  42575. * @param {TypedArray} a - The first array.
  42576. * @param {TypedArray} b - The second array.
  42577. * @param {number} offset - An index offset for the first array.
  42578. * @return {boolean} Whether the given arrays are equal or not.
  42579. */
  42580. function arraysEqual( a, b, offset ) {
  42581. for ( let i = 0, l = b.length; i < l; i ++ ) {
  42582. if ( a[ offset + i ] !== b[ i ] ) return false;
  42583. }
  42584. return true;
  42585. }
  42586. let _id$3 = 0;
  42587. /**
  42588. * A special form of uniforms group that represents
  42589. * the individual uniforms as node-based uniforms.
  42590. *
  42591. * @private
  42592. * @augments UniformsGroup
  42593. */
  42594. class NodeUniformsGroup extends UniformsGroup {
  42595. /**
  42596. * Constructs a new node-based uniforms group.
  42597. *
  42598. * @param {string} name - The group's name.
  42599. * @param {UniformGroupNode} groupNode - The uniform group node.
  42600. */
  42601. constructor( name, groupNode ) {
  42602. super( name );
  42603. /**
  42604. * The group's ID.
  42605. *
  42606. * @type {number}
  42607. */
  42608. this.id = _id$3 ++;
  42609. /**
  42610. * The uniform group node.
  42611. *
  42612. * @type {UniformGroupNode}
  42613. */
  42614. this.groupNode = groupNode;
  42615. /**
  42616. * This flag can be used for type testing.
  42617. *
  42618. * @type {boolean}
  42619. * @readonly
  42620. * @default true
  42621. */
  42622. this.isNodeUniformsGroup = true;
  42623. }
  42624. }
  42625. /**
  42626. * Represents a sampler binding type.
  42627. *
  42628. * @private
  42629. * @augments Binding
  42630. */
  42631. class Sampler extends Binding {
  42632. /**
  42633. * Constructs a new sampler.
  42634. *
  42635. * @param {string} name - The samplers's name.
  42636. * @param {?Texture} texture - The texture this binding is referring to.
  42637. */
  42638. constructor( name, texture ) {
  42639. super( name );
  42640. /**
  42641. * The texture the sampler is referring to.
  42642. *
  42643. * @private
  42644. * @type {?Texture}
  42645. */
  42646. this._texture = null;
  42647. /**
  42648. * An event listener which is added to {@link texture}'s dispose event.
  42649. *
  42650. * @private
  42651. * @type {Function}
  42652. */
  42653. this._onTextureDispose = () => {
  42654. this.generation = null;
  42655. this.version = 0;
  42656. };
  42657. // Assignment to the texture via a setter must occur after "_onTextureDispose" is initialized.
  42658. this.texture = texture;
  42659. /**
  42660. * The binding's version.
  42661. *
  42662. * @type {number}
  42663. */
  42664. this.version = texture ? texture.version : 0;
  42665. /**
  42666. * The binding's generation which is an additional version
  42667. * qualifier.
  42668. *
  42669. * @type {?number}
  42670. * @default null
  42671. */
  42672. this.generation = null;
  42673. /**
  42674. * The binding's sampler key.
  42675. *
  42676. * @type {string}
  42677. * @default ''
  42678. */
  42679. this.samplerKey = '';
  42680. /**
  42681. * This flag can be used for type testing.
  42682. *
  42683. * @type {boolean}
  42684. * @readonly
  42685. * @default true
  42686. */
  42687. this.isSampler = true;
  42688. }
  42689. /**
  42690. * Sets the texture of this sampler.
  42691. *
  42692. * @param {Texture} value - The texture to set.
  42693. */
  42694. set texture( value ) {
  42695. if ( this._texture === value ) return;
  42696. if ( this._texture ) {
  42697. this._texture.removeEventListener( 'dispose', this._onTextureDispose );
  42698. }
  42699. this._texture = value;
  42700. this.generation = null;
  42701. this.version = 0;
  42702. if ( this._texture ) {
  42703. this._texture.addEventListener( 'dispose', this._onTextureDispose );
  42704. }
  42705. }
  42706. /**
  42707. * Gets the texture of this sampler.
  42708. * @return {?Texture} The texture.
  42709. */
  42710. get texture() {
  42711. return this._texture;
  42712. }
  42713. /**
  42714. * Updates the binding.
  42715. *
  42716. * @return {boolean} Whether the texture has been updated and must be
  42717. * uploaded to the GPU.
  42718. */
  42719. update() {
  42720. const { texture, version } = this;
  42721. if ( version !== texture.version ) {
  42722. this.version = texture.version;
  42723. return true;
  42724. }
  42725. return false;
  42726. }
  42727. clone() {
  42728. const clonedSampler = super.clone();
  42729. // fix dispose handler for cloned instances
  42730. // TODO: Find better solution, see #31747
  42731. clonedSampler._texture = null;
  42732. clonedSampler._onTextureDispose = () => {
  42733. clonedSampler.generation = null;
  42734. clonedSampler.version = 0;
  42735. };
  42736. clonedSampler.texture = this.texture;
  42737. return clonedSampler;
  42738. }
  42739. }
  42740. let _id$2 = 0;
  42741. /**
  42742. * Represents a sampled texture binding type.
  42743. *
  42744. * @private
  42745. * @augments Sampler
  42746. */
  42747. class SampledTexture extends Sampler {
  42748. /**
  42749. * Constructs a new sampled texture.
  42750. *
  42751. * @param {string} name - The sampled texture's name.
  42752. * @param {?Texture} texture - The texture this binding is referring to.
  42753. */
  42754. constructor( name, texture ) {
  42755. super( name, texture );
  42756. /**
  42757. * This identifier.
  42758. *
  42759. * @type {number}
  42760. */
  42761. this.id = _id$2 ++;
  42762. /**
  42763. * Whether the texture is a storage texture or not.
  42764. *
  42765. * @type {boolean}
  42766. * @default false
  42767. */
  42768. this.store = false;
  42769. /**
  42770. * The mip level to bind for storage textures.
  42771. *
  42772. * @type {number}
  42773. * @default 0
  42774. */
  42775. this.mipLevel = 0;
  42776. /**
  42777. * This flag can be used for type testing.
  42778. *
  42779. * @type {boolean}
  42780. * @readonly
  42781. * @default true
  42782. */
  42783. this.isSampledTexture = true;
  42784. }
  42785. }
  42786. /**
  42787. * A special form of sampled texture binding type.
  42788. * It's texture value is managed by a node object.
  42789. *
  42790. * @private
  42791. * @augments SampledTexture
  42792. */
  42793. class NodeSampledTexture extends SampledTexture {
  42794. /**
  42795. * Constructs a new node-based sampled texture.
  42796. *
  42797. * @param {string} name - The textures's name.
  42798. * @param {TextureNode} textureNode - The texture node.
  42799. * @param {UniformGroupNode} groupNode - The uniform group node.
  42800. * @param {?string} [access=null] - The access type.
  42801. */
  42802. constructor( name, textureNode, groupNode, access = null ) {
  42803. super( name, textureNode ? textureNode.value : null );
  42804. /**
  42805. * The texture node.
  42806. *
  42807. * @type {TextureNode}
  42808. */
  42809. this.textureNode = textureNode;
  42810. /**
  42811. * The uniform group node.
  42812. *
  42813. * @type {UniformGroupNode}
  42814. */
  42815. this.groupNode = groupNode;
  42816. /**
  42817. * The access type.
  42818. *
  42819. * @type {?string}
  42820. * @default null
  42821. */
  42822. this.access = access;
  42823. }
  42824. /**
  42825. * Updates the binding.
  42826. *
  42827. * @return {boolean} Whether the texture has been updated and must be
  42828. * uploaded to the GPU.
  42829. */
  42830. update() {
  42831. const { textureNode } = this;
  42832. if ( this.texture !== textureNode.value ) {
  42833. this.texture = textureNode.value;
  42834. return true;
  42835. }
  42836. return super.update();
  42837. }
  42838. }
  42839. /**
  42840. * A special form of sampled cube texture binding type.
  42841. * It's texture value is managed by a node object.
  42842. *
  42843. * @private
  42844. * @augments NodeSampledTexture
  42845. */
  42846. class NodeSampledCubeTexture extends NodeSampledTexture {
  42847. /**
  42848. * Constructs a new node-based sampled cube texture.
  42849. *
  42850. * @param {string} name - The textures's name.
  42851. * @param {TextureNode} textureNode - The texture node.
  42852. * @param {UniformGroupNode} groupNode - The uniform group node.
  42853. * @param {?string} [access=null] - The access type.
  42854. */
  42855. constructor( name, textureNode, groupNode, access = null ) {
  42856. super( name, textureNode, groupNode, access );
  42857. /**
  42858. * This flag can be used for type testing.
  42859. *
  42860. * @type {boolean}
  42861. * @readonly
  42862. * @default true
  42863. */
  42864. this.isSampledCubeTexture = true;
  42865. }
  42866. }
  42867. /**
  42868. * A special form of sampled 3D texture binding type.
  42869. * It's texture value is managed by a node object.
  42870. *
  42871. * @private
  42872. * @augments NodeSampledTexture
  42873. */
  42874. class NodeSampledTexture3D extends NodeSampledTexture {
  42875. /**
  42876. * Constructs a new node-based sampled 3D texture.
  42877. *
  42878. * @param {string} name - The textures's name.
  42879. * @param {TextureNode} textureNode - The texture node.
  42880. * @param {UniformGroupNode} groupNode - The uniform group node.
  42881. * @param {?string} [access=null] - The access type.
  42882. */
  42883. constructor( name, textureNode, groupNode, access = null ) {
  42884. super( name, textureNode, groupNode, access );
  42885. /**
  42886. * This flag can be used for type testing.
  42887. *
  42888. * @type {boolean}
  42889. * @readonly
  42890. * @default true
  42891. */
  42892. this.isSampledTexture3D = true;
  42893. }
  42894. }
  42895. const glslPolyfills = {
  42896. bitcast_int_uint: new CodeNode( /* glsl */'uint tsl_bitcast_uint_to_int ( int x ) { return floatBitsToInt( uintBitsToFloat( x ) ); }' ),
  42897. bitcast_uint_int: new CodeNode( /* glsl */'uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }' )
  42898. };
  42899. const glslMethods = {
  42900. textureDimensions: 'textureSize',
  42901. equals: 'equal',
  42902. bitcast_float_int: 'floatBitsToInt',
  42903. bitcast_int_float: 'intBitsToFloat',
  42904. bitcast_uint_float: 'uintBitsToFloat',
  42905. bitcast_float_uint: 'floatBitsToUint',
  42906. bitcast_uint_int: 'tsl_bitcast_uint_to_int',
  42907. bitcast_int_uint: 'tsl_bitcast_int_to_uint'
  42908. };
  42909. const precisionLib = {
  42910. low: 'lowp',
  42911. medium: 'mediump',
  42912. high: 'highp'
  42913. };
  42914. const supports$1 = {
  42915. swizzleAssign: true,
  42916. storageBuffer: false
  42917. };
  42918. const interpolationTypeMap = {
  42919. perspective: 'smooth',
  42920. linear: 'noperspective'
  42921. };
  42922. const interpolationModeMap = {
  42923. 'centroid': 'centroid'
  42924. };
  42925. const defaultPrecisions = `
  42926. precision highp float;
  42927. precision highp int;
  42928. precision highp sampler2D;
  42929. precision highp sampler3D;
  42930. precision highp samplerCube;
  42931. precision highp sampler2DArray;
  42932. precision highp usampler2D;
  42933. precision highp usampler3D;
  42934. precision highp usamplerCube;
  42935. precision highp usampler2DArray;
  42936. precision highp isampler2D;
  42937. precision highp isampler3D;
  42938. precision highp isamplerCube;
  42939. precision highp isampler2DArray;
  42940. precision lowp sampler2DShadow;
  42941. precision lowp sampler2DArrayShadow;
  42942. precision lowp samplerCubeShadow;
  42943. `;
  42944. /**
  42945. * A node builder targeting GLSL.
  42946. *
  42947. * This module generates GLSL shader code from node materials and also
  42948. * generates the respective bindings and vertex buffer definitions. These
  42949. * data are later used by the renderer to create render and compute pipelines
  42950. * for render objects.
  42951. *
  42952. * @augments NodeBuilder
  42953. */
  42954. class GLSLNodeBuilder extends NodeBuilder {
  42955. /**
  42956. * Constructs a new GLSL node builder renderer.
  42957. *
  42958. * @param {Object3D} object - The 3D object.
  42959. * @param {Renderer} renderer - The renderer.
  42960. */
  42961. constructor( object, renderer ) {
  42962. super( object, renderer, new GLSLNodeParser() );
  42963. /**
  42964. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  42965. * another dictionary which manages UBOs per group ('render','frame','object').
  42966. *
  42967. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  42968. */
  42969. this.uniformGroups = {};
  42970. /**
  42971. * An array that holds objects defining the varying and attribute data in
  42972. * context of Transform Feedback.
  42973. *
  42974. * @type {Array<Object<string,AttributeNode|string>>}
  42975. */
  42976. this.transforms = [];
  42977. /**
  42978. * A dictionary that holds for each shader stage a Map of used extensions.
  42979. *
  42980. * @type {Object<string,Map<string,Object>>}
  42981. */
  42982. this.extensions = {};
  42983. /**
  42984. * A dictionary that holds for each shader stage an Array of used builtins.
  42985. *
  42986. * @type {Object<string,Array<string>>}
  42987. */
  42988. this.builtins = { vertex: [], fragment: [], compute: [] };
  42989. }
  42990. /**
  42991. * Checks if the given texture requires a manual conversion to the working color space.
  42992. *
  42993. * @param {Texture} texture - The texture to check.
  42994. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  42995. */
  42996. needsToWorkingColorSpace( texture ) {
  42997. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  42998. }
  42999. /**
  43000. * Includes the given method name into the current
  43001. * function node.
  43002. *
  43003. * @private
  43004. * @param {string} name - The method name to include.
  43005. * @return {CodeNode} The respective code node.
  43006. */
  43007. _include( name ) {
  43008. const codeNode = glslPolyfills[ name ];
  43009. codeNode.build( this );
  43010. this.addInclude( codeNode );
  43011. return codeNode;
  43012. }
  43013. /**
  43014. * Returns the native shader method name for a given generic name.
  43015. *
  43016. * @param {string} method - The method name to resolve.
  43017. * @return {string} The resolved GLSL method name.
  43018. */
  43019. getMethod( method ) {
  43020. if ( glslPolyfills[ method ] !== undefined ) {
  43021. this._include( method );
  43022. }
  43023. return glslMethods[ method ] || method;
  43024. }
  43025. /**
  43026. * Returns the bitcast method name for a given input and outputType.
  43027. *
  43028. * @param {string} type - The output type to bitcast to.
  43029. * @param {string} inputType - The input type of the.
  43030. * @return {string} The resolved WGSL bitcast invocation.
  43031. */
  43032. getBitcastMethod( type, inputType ) {
  43033. return this.getMethod( `bitcast_${ inputType }_${ type }` );
  43034. }
  43035. /**
  43036. * Returns the native snippet for a ternary operation.
  43037. *
  43038. * @param {string} condSnippet - The condition determining which expression gets resolved.
  43039. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  43040. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  43041. * @return {string} The resolved method name.
  43042. */
  43043. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  43044. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  43045. }
  43046. /**
  43047. * Returns the output struct name. Not relevant for GLSL.
  43048. *
  43049. * @return {string}
  43050. */
  43051. getOutputStructName() {
  43052. return '';
  43053. }
  43054. /**
  43055. * Builds the given shader node.
  43056. *
  43057. * @param {ShaderNodeInternal} shaderNode - The shader node.
  43058. * @return {string} The GLSL function code.
  43059. */
  43060. buildFunctionCode( shaderNode ) {
  43061. const layout = shaderNode.layout;
  43062. const flowData = this.flowShaderNode( shaderNode );
  43063. const parameters = [];
  43064. for ( const input of layout.inputs ) {
  43065. parameters.push( this.getType( input.type ) + ' ' + input.name );
  43066. }
  43067. //
  43068. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  43069. ${ flowData.vars }
  43070. ${ flowData.code }
  43071. return ${ flowData.result };
  43072. }`;
  43073. //
  43074. return code;
  43075. }
  43076. /**
  43077. * Setups the Pixel Buffer Object (PBO) for the given storage
  43078. * buffer node.
  43079. *
  43080. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  43081. */
  43082. setupPBO( storageBufferNode ) {
  43083. const attribute = storageBufferNode.value;
  43084. if ( attribute.pbo === undefined ) {
  43085. const originalArray = attribute.array;
  43086. const numElements = attribute.count * attribute.itemSize;
  43087. const { itemSize } = attribute;
  43088. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  43089. let format = isInteger ? RedIntegerFormat : RedFormat;
  43090. if ( itemSize === 2 ) {
  43091. format = isInteger ? RGIntegerFormat : RGFormat;
  43092. } else if ( itemSize === 3 ) {
  43093. format = isInteger ? RGBIntegerFormat : RGBFormat;
  43094. } else if ( itemSize === 4 ) {
  43095. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  43096. }
  43097. const typeMap = {
  43098. Float32Array: FloatType,
  43099. Uint8Array: UnsignedByteType,
  43100. Uint16Array: UnsignedShortType,
  43101. Uint32Array: UnsignedIntType,
  43102. Int8Array: ByteType,
  43103. Int16Array: ShortType,
  43104. Int32Array: IntType,
  43105. Uint8ClampedArray: UnsignedByteType,
  43106. };
  43107. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  43108. let height = Math.ceil( ( numElements / itemSize ) / width );
  43109. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  43110. const newSize = width * height * itemSize;
  43111. const newArray = new originalArray.constructor( newSize );
  43112. newArray.set( originalArray, 0 );
  43113. attribute.array = newArray;
  43114. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  43115. pboTexture.needsUpdate = true;
  43116. pboTexture.isPBOTexture = true;
  43117. const pbo = new TextureNode( pboTexture, null, null );
  43118. pbo.setPrecision( 'high' );
  43119. attribute.pboNode = pbo;
  43120. attribute.pbo = pbo.value;
  43121. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  43122. }
  43123. }
  43124. /**
  43125. * Returns a GLSL snippet that represents the property name of the given node.
  43126. *
  43127. * @param {Node} node - The node.
  43128. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43129. * @return {string} The property name.
  43130. */
  43131. getPropertyName( node, shaderStage = this.shaderStage ) {
  43132. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  43133. return shaderStage.charAt( 0 ) + '_' + node.name;
  43134. }
  43135. return super.getPropertyName( node, shaderStage );
  43136. }
  43137. /**
  43138. * Setups the Pixel Buffer Object (PBO) for the given storage
  43139. * buffer node.
  43140. *
  43141. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  43142. * @return {string} The property name.
  43143. */
  43144. generatePBO( storageArrayElementNode ) {
  43145. const { node, indexNode } = storageArrayElementNode;
  43146. const attribute = node.value;
  43147. if ( this.renderer.backend.has( attribute ) ) {
  43148. const attributeData = this.renderer.backend.get( attribute );
  43149. attributeData.pbo = attribute.pbo;
  43150. }
  43151. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  43152. const textureName = this.getPropertyName( nodeUniform );
  43153. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  43154. const indexSnippet = indexNode.build( this, 'uint' );
  43155. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  43156. let propertyName = elementNodeData.propertyName;
  43157. if ( propertyName === undefined ) {
  43158. // property element
  43159. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  43160. propertyName = this.getPropertyName( nodeVar );
  43161. // property size
  43162. const bufferNodeData = this.getDataFromNode( node );
  43163. let propertySizeName = bufferNodeData.propertySizeName;
  43164. if ( propertySizeName === undefined ) {
  43165. propertySizeName = propertyName + 'Size';
  43166. this.getVarFromNode( node, propertySizeName, 'uint' );
  43167. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  43168. bufferNodeData.propertySizeName = propertySizeName;
  43169. }
  43170. //
  43171. const { itemSize } = attribute;
  43172. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  43173. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  43174. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, '0', null, null );
  43175. //
  43176. let prefix = 'vec4';
  43177. if ( attribute.pbo.type === UnsignedIntType ) {
  43178. prefix = 'uvec4';
  43179. } else if ( attribute.pbo.type === IntType ) {
  43180. prefix = 'ivec4';
  43181. }
  43182. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  43183. elementNodeData.propertyName = propertyName;
  43184. }
  43185. return propertyName;
  43186. }
  43187. /**
  43188. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  43189. *
  43190. * @param {?Texture} texture - The texture.
  43191. * @param {string} textureProperty - The name of the texture uniform in the shader.
  43192. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  43193. * @param {?string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  43194. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  43195. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  43196. * @return {string} The GLSL snippet.
  43197. */
  43198. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  43199. if ( levelSnippet === null ) levelSnippet = '0';
  43200. let snippet;
  43201. if ( depthSnippet ) {
  43202. if ( offsetSnippet ) {
  43203. snippet = `texelFetchOffset( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet }, ${ offsetSnippet } )`;
  43204. } else {
  43205. snippet = `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  43206. }
  43207. } else {
  43208. if ( offsetSnippet ) {
  43209. snippet = `texelFetchOffset( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  43210. } else {
  43211. snippet = `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  43212. }
  43213. }
  43214. if ( texture !== null && texture.isDepthTexture ) {
  43215. snippet += '.x';
  43216. }
  43217. return snippet;
  43218. }
  43219. /**
  43220. * Generates the GLSL snippet for sampling/loading the given texture.
  43221. *
  43222. * @param {Texture} texture - The texture.
  43223. * @param {string} textureProperty - The name of the texture uniform in the shader.
  43224. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  43225. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  43226. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  43227. * @return {string} The GLSL snippet.
  43228. */
  43229. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet ) {
  43230. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  43231. if ( texture.isDepthTexture ) {
  43232. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } ).x`;
  43233. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  43234. }
  43235. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } )`;
  43236. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  43237. }
  43238. /**
  43239. * Generates the GLSL snippet when sampling textures with explicit mip level.
  43240. *
  43241. * @param {Texture} texture - The texture.
  43242. * @param {string} textureProperty - The name of the texture uniform in the shader.
  43243. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  43244. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  43245. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  43246. * @return {string} The GLSL snippet.
  43247. */
  43248. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, offsetSnippet ) {
  43249. if ( offsetSnippet ) {
  43250. return `textureLodOffset( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  43251. }
  43252. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  43253. }
  43254. /**
  43255. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  43256. *
  43257. * @param {Texture} texture - The texture.
  43258. * @param {string} textureProperty - The name of the texture uniform in the shader.
  43259. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  43260. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  43261. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  43262. * @return {string} The GLSL snippet.
  43263. */
  43264. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, offsetSnippet ) {
  43265. if ( offsetSnippet ) {
  43266. return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ biasSnippet } )`;
  43267. }
  43268. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  43269. }
  43270. /**
  43271. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  43272. *
  43273. * @param {Texture} texture - The texture.
  43274. * @param {string} textureProperty - The name of the texture uniform in the shader.
  43275. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  43276. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  43277. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  43278. * @return {string} The GLSL snippet.
  43279. */
  43280. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, offsetSnippet ) {
  43281. if ( offsetSnippet ) {
  43282. return `textureGradOffset( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  43283. }
  43284. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  43285. }
  43286. /**
  43287. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  43288. * against a reference value.
  43289. *
  43290. * @param {Texture} texture - The texture.
  43291. * @param {string} textureProperty - The name of the texture uniform in the shader.
  43292. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  43293. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  43294. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  43295. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  43296. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43297. * @return {string} The GLSL snippet.
  43298. */
  43299. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  43300. if ( shaderStage === 'fragment' ) {
  43301. if ( depthSnippet ) {
  43302. if ( offsetSnippet ) {
  43303. return `textureOffset( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  43304. }
  43305. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  43306. }
  43307. if ( offsetSnippet ) {
  43308. return `textureOffset( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  43309. }
  43310. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  43311. } else {
  43312. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  43313. }
  43314. }
  43315. /**
  43316. * Returns the variables of the given shader stage as a GLSL string.
  43317. *
  43318. * @param {string} shaderStage - The shader stage.
  43319. * @return {string} The GLSL snippet that defines the variables.
  43320. */
  43321. getVars( shaderStage ) {
  43322. const snippets = [];
  43323. const vars = this.vars[ shaderStage ];
  43324. if ( vars !== undefined ) {
  43325. for ( const variable of vars ) {
  43326. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  43327. }
  43328. }
  43329. return snippets.join( '\n\t' );
  43330. }
  43331. /**
  43332. * Returns the uniforms of the given shader stage as a GLSL string.
  43333. *
  43334. * @param {string} shaderStage - The shader stage.
  43335. * @return {string} The GLSL snippet that defines the uniforms.
  43336. */
  43337. getUniforms( shaderStage ) {
  43338. const uniforms = this.uniforms[ shaderStage ];
  43339. const bindingSnippets = [];
  43340. const uniformGroups = {};
  43341. for ( const uniform of uniforms ) {
  43342. let snippet = null;
  43343. let group = false;
  43344. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  43345. const texture = uniform.node.value;
  43346. let typePrefix = '';
  43347. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  43348. if ( texture.type === UnsignedIntType ) {
  43349. typePrefix = 'u';
  43350. } else if ( texture.type === IntType ) {
  43351. typePrefix = 'i';
  43352. }
  43353. }
  43354. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  43355. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  43356. } else if ( texture.compareFunction ) {
  43357. if ( texture.isArrayTexture === true ) {
  43358. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  43359. } else {
  43360. snippet = `sampler2DShadow ${ uniform.name };`;
  43361. }
  43362. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  43363. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  43364. } else {
  43365. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  43366. }
  43367. } else if ( uniform.type === 'cubeTexture' ) {
  43368. snippet = `samplerCube ${ uniform.name };`;
  43369. } else if ( uniform.type === 'buffer' ) {
  43370. const bufferNode = uniform.node;
  43371. const bufferType = this.getType( bufferNode.bufferType );
  43372. const bufferCount = bufferNode.bufferCount;
  43373. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  43374. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  43375. } else {
  43376. const vectorType = this.getVectorType( uniform.type );
  43377. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  43378. group = true;
  43379. }
  43380. const precision = uniform.node.precision;
  43381. if ( precision !== null ) {
  43382. snippet = precisionLib[ precision ] + ' ' + snippet;
  43383. }
  43384. if ( group ) {
  43385. snippet = '\t' + snippet;
  43386. const groupName = uniform.groupNode.name;
  43387. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  43388. groupSnippets.push( snippet );
  43389. } else {
  43390. snippet = 'uniform ' + snippet;
  43391. bindingSnippets.push( snippet );
  43392. }
  43393. }
  43394. let output = '';
  43395. for ( const name in uniformGroups ) {
  43396. const groupSnippets = uniformGroups[ name ];
  43397. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  43398. }
  43399. output += bindingSnippets.join( '\n' );
  43400. return output;
  43401. }
  43402. /**
  43403. * Returns the type for a given buffer attribute.
  43404. *
  43405. * @param {BufferAttribute} attribute - The buffer attribute.
  43406. * @return {string} The type.
  43407. */
  43408. getTypeFromAttribute( attribute ) {
  43409. let nodeType = super.getTypeFromAttribute( attribute );
  43410. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  43411. let dataAttribute = attribute;
  43412. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  43413. const array = dataAttribute.array;
  43414. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  43415. nodeType = nodeType.slice( 1 );
  43416. }
  43417. }
  43418. return nodeType;
  43419. }
  43420. /**
  43421. * Returns the shader attributes of the given shader stage as a GLSL string.
  43422. *
  43423. * @param {string} shaderStage - The shader stage.
  43424. * @return {string} The GLSL snippet that defines the shader attributes.
  43425. */
  43426. getAttributes( shaderStage ) {
  43427. let snippet = '';
  43428. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  43429. const attributes = this.getAttributesArray();
  43430. let location = 0;
  43431. for ( const attribute of attributes ) {
  43432. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  43433. }
  43434. }
  43435. return snippet;
  43436. }
  43437. /**
  43438. * Returns the members of the given struct type node as a GLSL string.
  43439. *
  43440. * @param {StructTypeNode} struct - The struct type node.
  43441. * @return {string} The GLSL snippet that defines the struct members.
  43442. */
  43443. getStructMembers( struct ) {
  43444. const snippets = [];
  43445. for ( const member of struct.members ) {
  43446. snippets.push( `\t${ member.type } ${ member.name };` );
  43447. }
  43448. return snippets.join( '\n' );
  43449. }
  43450. /**
  43451. * Returns the structs of the given shader stage as a GLSL string.
  43452. *
  43453. * @param {string} shaderStage - The shader stage.
  43454. * @return {string} The GLSL snippet that defines the structs.
  43455. */
  43456. getStructs( shaderStage ) {
  43457. const snippets = [];
  43458. const structs = this.structs[ shaderStage ];
  43459. const outputSnippet = [];
  43460. for ( const struct of structs ) {
  43461. if ( struct.output ) {
  43462. for ( const member of struct.members ) {
  43463. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  43464. }
  43465. } else {
  43466. let snippet = 'struct ' + struct.name + ' {\n';
  43467. snippet += this.getStructMembers( struct );
  43468. snippet += '\n};\n';
  43469. snippets.push( snippet );
  43470. }
  43471. }
  43472. if ( outputSnippet.length === 0 ) {
  43473. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  43474. }
  43475. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  43476. }
  43477. /**
  43478. * Returns the varyings of the given shader stage as a GLSL string.
  43479. *
  43480. * @param {string} shaderStage - The shader stage.
  43481. * @return {string} The GLSL snippet that defines the varyings.
  43482. */
  43483. getVaryings( shaderStage ) {
  43484. let snippet = '';
  43485. const varyings = this.varyings;
  43486. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  43487. for ( const varying of varyings ) {
  43488. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  43489. const type = this.getType( varying.type );
  43490. if ( varying.needsInterpolation ) {
  43491. if ( varying.interpolationType ) {
  43492. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  43493. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  43494. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  43495. } else {
  43496. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  43497. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  43498. }
  43499. } else {
  43500. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  43501. }
  43502. }
  43503. } else if ( shaderStage === 'fragment' ) {
  43504. for ( const varying of varyings ) {
  43505. if ( varying.needsInterpolation ) {
  43506. const type = this.getType( varying.type );
  43507. if ( varying.interpolationType ) {
  43508. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  43509. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  43510. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  43511. } else {
  43512. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  43513. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  43514. }
  43515. }
  43516. }
  43517. }
  43518. for ( const builtin of this.builtins[ shaderStage ] ) {
  43519. snippet += `${builtin};\n`;
  43520. }
  43521. return snippet;
  43522. }
  43523. /**
  43524. * Returns the vertex index builtin.
  43525. *
  43526. * @return {string} The vertex index.
  43527. */
  43528. getVertexIndex() {
  43529. return 'uint( gl_VertexID )';
  43530. }
  43531. /**
  43532. * Contextually returns either the vertex stage instance index builtin
  43533. * or the linearized index of an compute invocation within a grid of workgroups.
  43534. *
  43535. * @return {string} The instance index.
  43536. */
  43537. getInstanceIndex() {
  43538. return 'uint( gl_InstanceID )';
  43539. }
  43540. /**
  43541. * Returns a builtin representing the index of an invocation within its workgroup.
  43542. *
  43543. * @return {string} The invocation local index.
  43544. */
  43545. getInvocationLocalIndex() {
  43546. const workgroupSize = this.object.workgroupSize;
  43547. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  43548. return `uint( gl_InstanceID ) % ${size}u`;
  43549. }
  43550. /**
  43551. * Returns a builtin representing the size of a subgroup within the current shader.
  43552. */
  43553. getSubgroupSize() {
  43554. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node' );
  43555. }
  43556. /**
  43557. * Returns a builtin representing the index of an invocation within its subgroup.
  43558. */
  43559. getInvocationSubgroupIndex() {
  43560. error( 'GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node' );
  43561. }
  43562. /**
  43563. * Returns a builtin representing the index of the current invocation's subgroup within its workgroup.
  43564. */
  43565. getSubgroupIndex() {
  43566. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node' );
  43567. }
  43568. /**
  43569. * Returns the draw index builtin.
  43570. *
  43571. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  43572. */
  43573. getDrawIndex() {
  43574. const extensions = this.renderer.backend.extensions;
  43575. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  43576. return 'uint( gl_DrawID )';
  43577. }
  43578. return null;
  43579. }
  43580. /**
  43581. * Returns the front facing builtin.
  43582. *
  43583. * @return {string} The front facing builtin.
  43584. */
  43585. getFrontFacing() {
  43586. return 'gl_FrontFacing';
  43587. }
  43588. /**
  43589. * Returns the frag coord builtin.
  43590. *
  43591. * @return {string} The frag coord builtin.
  43592. */
  43593. getFragCoord() {
  43594. return 'gl_FragCoord.xy';
  43595. }
  43596. /**
  43597. * Returns the frag depth builtin.
  43598. *
  43599. * @return {string} The frag depth builtin.
  43600. */
  43601. getFragDepth() {
  43602. return 'gl_FragDepth';
  43603. }
  43604. /**
  43605. * Enables the given extension.
  43606. *
  43607. * @param {string} name - The extension name.
  43608. * @param {string} behavior - The extension behavior.
  43609. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  43610. */
  43611. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  43612. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  43613. if ( map.has( name ) === false ) {
  43614. map.set( name, {
  43615. name,
  43616. behavior
  43617. } );
  43618. }
  43619. }
  43620. /**
  43621. * Returns the enabled extensions of the given shader stage as a GLSL string.
  43622. *
  43623. * @param {string} shaderStage - The shader stage.
  43624. * @return {string} The GLSL snippet that defines the enabled extensions.
  43625. */
  43626. getExtensions( shaderStage ) {
  43627. const snippets = [];
  43628. if ( shaderStage === 'vertex' ) {
  43629. const ext = this.renderer.backend.extensions;
  43630. const isBatchedMesh = this.object.isBatchedMesh;
  43631. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  43632. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  43633. }
  43634. }
  43635. const extensions = this.extensions[ shaderStage ];
  43636. if ( extensions !== undefined ) {
  43637. for ( const { name, behavior } of extensions.values() ) {
  43638. snippets.push( `#extension ${name} : ${behavior}` );
  43639. }
  43640. }
  43641. return snippets.join( '\n' );
  43642. }
  43643. /**
  43644. * Returns the clip distances builtin.
  43645. *
  43646. * @return {string} The clip distances builtin.
  43647. */
  43648. getClipDistance() {
  43649. return 'gl_ClipDistance';
  43650. }
  43651. /**
  43652. * Whether the requested feature is available or not.
  43653. *
  43654. * @param {string} name - The requested feature.
  43655. * @return {boolean} Whether the requested feature is supported or not.
  43656. */
  43657. isAvailable( name ) {
  43658. let result = supports$1[ name ];
  43659. if ( result === undefined ) {
  43660. let extensionName;
  43661. result = false;
  43662. switch ( name ) {
  43663. case 'float32Filterable':
  43664. extensionName = 'OES_texture_float_linear';
  43665. break;
  43666. case 'clipDistance':
  43667. extensionName = 'WEBGL_clip_cull_distance';
  43668. break;
  43669. }
  43670. if ( extensionName !== undefined ) {
  43671. const extensions = this.renderer.backend.extensions;
  43672. if ( extensions.has( extensionName ) ) {
  43673. extensions.get( extensionName );
  43674. result = true;
  43675. }
  43676. }
  43677. supports$1[ name ] = result;
  43678. }
  43679. return result;
  43680. }
  43681. /**
  43682. * Whether to flip texture data along its vertical axis or not.
  43683. *
  43684. * @return {boolean} Returns always `true` in context of GLSL.
  43685. */
  43686. isFlipY() {
  43687. return true;
  43688. }
  43689. /**
  43690. * Enables hardware clipping.
  43691. *
  43692. * @param {string} planeCount - The clipping plane count.
  43693. */
  43694. enableHardwareClipping( planeCount ) {
  43695. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  43696. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  43697. }
  43698. /**
  43699. * Enables multiview.
  43700. */
  43701. enableMultiview() {
  43702. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  43703. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  43704. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  43705. }
  43706. /**
  43707. * Registers a transform in context of Transform Feedback.
  43708. *
  43709. * @param {string} varyingName - The varying name.
  43710. * @param {AttributeNode} attributeNode - The attribute node.
  43711. */
  43712. registerTransform( varyingName, attributeNode ) {
  43713. this.transforms.push( { varyingName, attributeNode } );
  43714. }
  43715. /**
  43716. * Returns the transforms of the given shader stage as a GLSL string.
  43717. *
  43718. * @param {string} shaderStage - The shader stage.
  43719. * @return {string} The GLSL snippet that defines the transforms.
  43720. */
  43721. getTransforms( /* shaderStage */ ) {
  43722. const transforms = this.transforms;
  43723. let snippet = '';
  43724. for ( let i = 0; i < transforms.length; i ++ ) {
  43725. const transform = transforms[ i ];
  43726. const attributeName = this.getPropertyName( transform.attributeNode );
  43727. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  43728. }
  43729. return snippet;
  43730. }
  43731. /**
  43732. * Returns a GLSL struct based on the given name and variables.
  43733. *
  43734. * @private
  43735. * @param {string} name - The struct name.
  43736. * @param {string} vars - The struct variables.
  43737. * @return {string} The GLSL snippet representing a struct.
  43738. */
  43739. _getGLSLUniformStruct( name, vars ) {
  43740. return `
  43741. layout( std140 ) uniform ${name} {
  43742. ${vars}
  43743. };`;
  43744. }
  43745. /**
  43746. * Returns a GLSL vertex shader based on the given shader data.
  43747. *
  43748. * @private
  43749. * @param {Object} shaderData - The shader data.
  43750. * @return {string} The vertex shader.
  43751. */
  43752. _getGLSLVertexCode( shaderData ) {
  43753. return `#version 300 es
  43754. ${ this.getSignature() }
  43755. // extensions
  43756. ${shaderData.extensions}
  43757. // precision
  43758. ${ defaultPrecisions }
  43759. // uniforms
  43760. ${shaderData.uniforms}
  43761. // varyings
  43762. ${shaderData.varyings}
  43763. // attributes
  43764. ${shaderData.attributes}
  43765. // codes
  43766. ${shaderData.codes}
  43767. void main() {
  43768. // vars
  43769. ${shaderData.vars}
  43770. // transforms
  43771. ${shaderData.transforms}
  43772. // flow
  43773. ${shaderData.flow}
  43774. gl_PointSize = 1.0;
  43775. }
  43776. `;
  43777. }
  43778. /**
  43779. * Returns a GLSL fragment shader based on the given shader data.
  43780. *
  43781. * @private
  43782. * @param {Object} shaderData - The shader data.
  43783. * @return {string} The vertex shader.
  43784. */
  43785. _getGLSLFragmentCode( shaderData ) {
  43786. return `#version 300 es
  43787. ${ this.getSignature() }
  43788. // extensions
  43789. ${shaderData.extensions}
  43790. // precision
  43791. ${ defaultPrecisions }
  43792. // structs
  43793. ${shaderData.structs}
  43794. // uniforms
  43795. ${shaderData.uniforms}
  43796. // varyings
  43797. ${shaderData.varyings}
  43798. // codes
  43799. ${shaderData.codes}
  43800. void main() {
  43801. // vars
  43802. ${shaderData.vars}
  43803. // flow
  43804. ${shaderData.flow}
  43805. }
  43806. `;
  43807. }
  43808. /**
  43809. * Controls the code build of the shader stages.
  43810. */
  43811. buildCode() {
  43812. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  43813. this.sortBindingGroups();
  43814. for ( const shaderStage in shadersData ) {
  43815. let flow = '// code\n\n';
  43816. flow += this.flowCode[ shaderStage ];
  43817. const flowNodes = this.flowNodes[ shaderStage ];
  43818. const mainNode = flowNodes[ flowNodes.length - 1 ];
  43819. for ( const node of flowNodes ) {
  43820. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  43821. const slotName = node.name;
  43822. if ( slotName ) {
  43823. if ( flow.length > 0 ) flow += '\n';
  43824. flow += `\t// flow -> ${ slotName }\n\t`;
  43825. }
  43826. flow += `${ flowSlotData.code }\n\t`;
  43827. if ( node === mainNode && shaderStage !== 'compute' ) {
  43828. flow += '// result\n\t';
  43829. if ( shaderStage === 'vertex' ) {
  43830. flow += 'gl_Position = ';
  43831. flow += `${ flowSlotData.result };`;
  43832. } else if ( shaderStage === 'fragment' ) {
  43833. if ( ! node.outputNode.isOutputStructNode ) {
  43834. flow += 'fragColor = ';
  43835. flow += `${ flowSlotData.result };`;
  43836. }
  43837. }
  43838. }
  43839. }
  43840. const stageData = shadersData[ shaderStage ];
  43841. stageData.extensions = this.getExtensions( shaderStage );
  43842. stageData.uniforms = this.getUniforms( shaderStage );
  43843. stageData.attributes = this.getAttributes( shaderStage );
  43844. stageData.varyings = this.getVaryings( shaderStage );
  43845. stageData.vars = this.getVars( shaderStage );
  43846. stageData.structs = this.getStructs( shaderStage );
  43847. stageData.codes = this.getCodes( shaderStage );
  43848. stageData.transforms = this.getTransforms( shaderStage );
  43849. stageData.flow = flow;
  43850. }
  43851. if ( this.material !== null ) {
  43852. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  43853. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  43854. } else {
  43855. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  43856. }
  43857. }
  43858. /**
  43859. * This method is one of the more important ones since it's responsible
  43860. * for generating a matching binding instance for the given uniform node.
  43861. *
  43862. * These bindings are later used in the renderer to create bind groups
  43863. * and layouts.
  43864. *
  43865. * @param {UniformNode} node - The uniform node.
  43866. * @param {string} type - The node data type.
  43867. * @param {string} shaderStage - The shader stage.
  43868. * @param {?string} [name=null] - An optional uniform name.
  43869. * @return {NodeUniform} The node uniform object.
  43870. */
  43871. getUniformFromNode( node, type, shaderStage, name = null ) {
  43872. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  43873. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  43874. let uniformGPU = nodeData.uniformGPU;
  43875. if ( uniformGPU === undefined ) {
  43876. const group = node.groupNode;
  43877. const groupName = group.name;
  43878. const bindings = this.getBindGroupArray( groupName, shaderStage );
  43879. if ( type === 'texture' ) {
  43880. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  43881. bindings.push( uniformGPU );
  43882. } else if ( type === 'cubeTexture' ) {
  43883. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  43884. bindings.push( uniformGPU );
  43885. } else if ( type === 'texture3D' ) {
  43886. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  43887. bindings.push( uniformGPU );
  43888. } else if ( type === 'buffer' ) {
  43889. node.name = `NodeBuffer_${ node.id }`;
  43890. uniformNode.name = `buffer${ node.id }`;
  43891. const buffer = new NodeUniformBuffer( node, group );
  43892. buffer.name = node.name;
  43893. bindings.push( buffer );
  43894. uniformGPU = buffer;
  43895. } else {
  43896. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  43897. let uniformsGroup = uniformsStage[ groupName ];
  43898. if ( uniformsGroup === undefined ) {
  43899. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  43900. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43901. uniformsStage[ groupName ] = uniformsGroup;
  43902. bindings.push( uniformsGroup );
  43903. }
  43904. uniformGPU = this.getNodeUniform( uniformNode, type );
  43905. uniformsGroup.addUniform( uniformGPU );
  43906. }
  43907. nodeData.uniformGPU = uniformGPU;
  43908. }
  43909. return uniformNode;
  43910. }
  43911. }
  43912. let _vector2 = null;
  43913. let _color4 = null;
  43914. /**
  43915. * Most of the rendering related logic is implemented in the
  43916. * {@link Renderer} module and related management components.
  43917. * Sometimes it is required though to execute commands which are
  43918. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  43919. * This abstract base class defines an interface that encapsulates
  43920. * all backend-related logic. Derived classes for each backend must
  43921. * implement the interface.
  43922. *
  43923. * @abstract
  43924. * @private
  43925. */
  43926. class Backend {
  43927. /**
  43928. * Constructs a new backend.
  43929. *
  43930. * @param {Object} parameters - An object holding parameters for the backend.
  43931. */
  43932. constructor( parameters = {} ) {
  43933. /**
  43934. * The parameters of the backend.
  43935. *
  43936. * @type {Object}
  43937. */
  43938. this.parameters = Object.assign( {}, parameters );
  43939. /**
  43940. * This weak map holds backend-specific data of objects
  43941. * like textures, attributes or render targets.
  43942. *
  43943. * @type {WeakMap<Object, Object>}
  43944. */
  43945. this.data = new WeakMap();
  43946. /**
  43947. * A reference to the renderer.
  43948. *
  43949. * @type {?Renderer}
  43950. * @default null
  43951. */
  43952. this.renderer = null;
  43953. /**
  43954. * A reference to the canvas element the renderer is drawing to.
  43955. *
  43956. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  43957. * @default null
  43958. */
  43959. this.domElement = null;
  43960. /**
  43961. * A reference to the timestamp query pool.
  43962. *
  43963. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  43964. */
  43965. this.timestampQueryPool = {
  43966. [ TimestampQuery.RENDER ]: null,
  43967. [ TimestampQuery.COMPUTE ]: null
  43968. };
  43969. /**
  43970. * Whether to track timestamps with a Timestamp Query API or not.
  43971. *
  43972. * @type {boolean}
  43973. * @default false
  43974. */
  43975. this.trackTimestamp = ( parameters.trackTimestamp === true );
  43976. }
  43977. /**
  43978. * Initializes the backend so it is ready for usage. Concrete backends
  43979. * are supposed to implement their rendering context creation and related
  43980. * operations in this method.
  43981. *
  43982. * @async
  43983. * @param {Renderer} renderer - The renderer.
  43984. * @return {Promise} A Promise that resolves when the backend has been initialized.
  43985. */
  43986. async init( renderer ) {
  43987. this.renderer = renderer;
  43988. }
  43989. /**
  43990. * The coordinate system of the backend.
  43991. *
  43992. * @abstract
  43993. * @type {number}
  43994. * @readonly
  43995. */
  43996. get coordinateSystem() {}
  43997. // render context
  43998. /**
  43999. * This method is executed at the beginning of a render call and
  44000. * can be used by the backend to prepare the state for upcoming
  44001. * draw calls.
  44002. *
  44003. * @abstract
  44004. * @param {RenderContext} renderContext - The render context.
  44005. */
  44006. beginRender( /*renderContext*/ ) {}
  44007. /**
  44008. * This method is executed at the end of a render call and
  44009. * can be used by the backend to finalize work after draw
  44010. * calls.
  44011. *
  44012. * @abstract
  44013. * @param {RenderContext} renderContext - The render context.
  44014. */
  44015. finishRender( /*renderContext*/ ) {}
  44016. /**
  44017. * This method is executed at the beginning of a compute call and
  44018. * can be used by the backend to prepare the state for upcoming
  44019. * compute tasks.
  44020. *
  44021. * @abstract
  44022. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  44023. */
  44024. beginCompute( /*computeGroup*/ ) {}
  44025. /**
  44026. * This method is executed at the end of a compute call and
  44027. * can be used by the backend to finalize work after compute
  44028. * tasks.
  44029. *
  44030. * @abstract
  44031. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  44032. */
  44033. finishCompute( /*computeGroup*/ ) {}
  44034. // render object
  44035. /**
  44036. * Executes a draw command for the given render object.
  44037. *
  44038. * @abstract
  44039. * @param {RenderObject} renderObject - The render object to draw.
  44040. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  44041. */
  44042. draw( /*renderObject, info*/ ) { }
  44043. // compute node
  44044. /**
  44045. * Executes a compute command for the given compute node.
  44046. *
  44047. * @abstract
  44048. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  44049. * @param {Node} computeNode - The compute node.
  44050. * @param {Array<BindGroup>} bindings - The bindings.
  44051. * @param {ComputePipeline} computePipeline - The compute pipeline.
  44052. */
  44053. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  44054. // program
  44055. /**
  44056. * Creates a shader program from the given programmable stage.
  44057. *
  44058. * @abstract
  44059. * @param {ProgrammableStage} program - The programmable stage.
  44060. */
  44061. createProgram( /*program*/ ) { }
  44062. /**
  44063. * Destroys the shader program of the given programmable stage.
  44064. *
  44065. * @abstract
  44066. * @param {ProgrammableStage} program - The programmable stage.
  44067. */
  44068. destroyProgram( /*program*/ ) { }
  44069. // bindings
  44070. /**
  44071. * Creates bindings from the given bind group definition.
  44072. *
  44073. * @abstract
  44074. * @param {BindGroup} bindGroup - The bind group.
  44075. * @param {Array<BindGroup>} bindings - Array of bind groups.
  44076. * @param {number} cacheIndex - The cache index.
  44077. * @param {number} version - The version.
  44078. */
  44079. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  44080. /**
  44081. * Updates the given bind group definition.
  44082. *
  44083. * @abstract
  44084. * @param {BindGroup} bindGroup - The bind group.
  44085. * @param {Array<BindGroup>} bindings - Array of bind groups.
  44086. * @param {number} cacheIndex - The cache index.
  44087. * @param {number} version - The version.
  44088. */
  44089. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  44090. /**
  44091. * Updates a buffer binding.
  44092. *
  44093. * @abstract
  44094. * @param {Buffer} binding - The buffer binding to update.
  44095. */
  44096. updateBinding( /*binding*/ ) { }
  44097. // pipeline
  44098. /**
  44099. * Creates a render pipeline for the given render object.
  44100. *
  44101. * @abstract
  44102. * @param {RenderObject} renderObject - The render object.
  44103. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  44104. */
  44105. createRenderPipeline( /*renderObject, promises*/ ) { }
  44106. /**
  44107. * Creates a compute pipeline for the given compute node.
  44108. *
  44109. * @abstract
  44110. * @param {ComputePipeline} computePipeline - The compute pipeline.
  44111. * @param {Array<BindGroup>} bindings - The bindings.
  44112. */
  44113. createComputePipeline( /*computePipeline, bindings*/ ) { }
  44114. // cache key
  44115. /**
  44116. * Returns `true` if the render pipeline requires an update.
  44117. *
  44118. * @abstract
  44119. * @param {RenderObject} renderObject - The render object.
  44120. * @return {boolean} Whether the render pipeline requires an update or not.
  44121. */
  44122. needsRenderUpdate( /*renderObject*/ ) { }
  44123. /**
  44124. * Returns a cache key that is used to identify render pipelines.
  44125. *
  44126. * @abstract
  44127. * @param {RenderObject} renderObject - The render object.
  44128. * @return {string} The cache key.
  44129. */
  44130. getRenderCacheKey( /*renderObject*/ ) { }
  44131. // node builder
  44132. /**
  44133. * Returns a node builder for the given render object.
  44134. *
  44135. * @abstract
  44136. * @param {RenderObject} renderObject - The render object.
  44137. * @param {Renderer} renderer - The renderer.
  44138. * @return {NodeBuilder} The node builder.
  44139. */
  44140. createNodeBuilder( /*renderObject, renderer*/ ) { }
  44141. // textures
  44142. /**
  44143. * Updates a GPU sampler for the given texture.
  44144. *
  44145. * @abstract
  44146. * @param {Texture} texture - The texture to update the sampler for.
  44147. * @return {string} The current sampler key.
  44148. */
  44149. updateSampler( /*texture*/ ) { }
  44150. /**
  44151. * Creates a default texture for the given texture that can be used
  44152. * as a placeholder until the actual texture is ready for usage.
  44153. *
  44154. * @abstract
  44155. * @param {Texture} texture - The texture to create a default texture for.
  44156. */
  44157. createDefaultTexture( /*texture*/ ) { }
  44158. /**
  44159. * Defines a texture on the GPU for the given texture object.
  44160. *
  44161. * @abstract
  44162. * @param {Texture} texture - The texture.
  44163. * @param {Object} [options={}] - Optional configuration parameter.
  44164. */
  44165. createTexture( /*texture, options={}*/ ) { }
  44166. /**
  44167. * Uploads the updated texture data to the GPU.
  44168. *
  44169. * @abstract
  44170. * @param {Texture} texture - The texture.
  44171. * @param {Object} [options={}] - Optional configuration parameter.
  44172. */
  44173. updateTexture( /*texture, options = {}*/ ) { }
  44174. /**
  44175. * Generates mipmaps for the given texture.
  44176. *
  44177. * @abstract
  44178. * @param {Texture} texture - The texture.
  44179. */
  44180. generateMipmaps( /*texture*/ ) { }
  44181. /**
  44182. * Destroys the GPU data for the given texture object.
  44183. *
  44184. * @abstract
  44185. * @param {Texture} texture - The texture.
  44186. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  44187. */
  44188. destroyTexture( /*texture, isDefaultTexture*/ ) { }
  44189. /**
  44190. * Returns texture data as a typed array.
  44191. *
  44192. * @abstract
  44193. * @async
  44194. * @param {Texture} texture - The texture to copy.
  44195. * @param {number} x - The x coordinate of the copy origin.
  44196. * @param {number} y - The y coordinate of the copy origin.
  44197. * @param {number} width - The width of the copy.
  44198. * @param {number} height - The height of the copy.
  44199. * @param {number} faceIndex - The face index.
  44200. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  44201. */
  44202. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  44203. /**
  44204. * Copies data of the given source texture to the given destination texture.
  44205. *
  44206. * @abstract
  44207. * @param {Texture} srcTexture - The source texture.
  44208. * @param {Texture} dstTexture - The destination texture.
  44209. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  44210. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  44211. * @param {number} [srcLevel=0] - The source mip level to copy from.
  44212. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  44213. */
  44214. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  44215. /**
  44216. * Copies the current bound framebuffer to the given texture.
  44217. *
  44218. * @abstract
  44219. * @param {Texture} texture - The destination texture.
  44220. * @param {RenderContext} renderContext - The render context.
  44221. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  44222. */
  44223. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  44224. // attributes
  44225. /**
  44226. * Creates the GPU buffer of a shader attribute.
  44227. *
  44228. * @abstract
  44229. * @param {BufferAttribute} attribute - The buffer attribute.
  44230. */
  44231. createAttribute( /*attribute*/ ) { }
  44232. /**
  44233. * Creates the GPU buffer of an indexed shader attribute.
  44234. *
  44235. * @abstract
  44236. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  44237. */
  44238. createIndexAttribute( /*attribute*/ ) { }
  44239. /**
  44240. * Creates the GPU buffer of a storage attribute.
  44241. *
  44242. * @abstract
  44243. * @param {BufferAttribute} attribute - The buffer attribute.
  44244. */
  44245. createStorageAttribute( /*attribute*/ ) { }
  44246. /**
  44247. * Updates the GPU buffer of a shader attribute.
  44248. *
  44249. * @abstract
  44250. * @param {BufferAttribute} attribute - The buffer attribute to update.
  44251. */
  44252. updateAttribute( /*attribute*/ ) { }
  44253. /**
  44254. * Destroys the GPU buffer of a shader attribute.
  44255. *
  44256. * @abstract
  44257. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  44258. */
  44259. destroyAttribute( /*attribute*/ ) { }
  44260. // canvas
  44261. /**
  44262. * Returns the backend's rendering context.
  44263. *
  44264. * @abstract
  44265. * @return {Object} The rendering context.
  44266. */
  44267. getContext() { }
  44268. /**
  44269. * Backends can use this method if they have to run
  44270. * logic when the renderer gets resized.
  44271. *
  44272. * @abstract
  44273. */
  44274. updateSize() { }
  44275. /**
  44276. * Updates the viewport with the values from the given render context.
  44277. *
  44278. * @abstract
  44279. * @param {RenderContext} renderContext - The render context.
  44280. */
  44281. updateViewport( /*renderContext*/ ) {}
  44282. // utils
  44283. /**
  44284. * Updates a unique identifier for the given render context that can be used
  44285. * to allocate resources like occlusion queries or timestamp queries.
  44286. *
  44287. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  44288. */
  44289. updateTimeStampUID( abstractRenderContext ) {
  44290. const contextData = this.get( abstractRenderContext );
  44291. const frame = this.renderer.info.frame;
  44292. let prefix;
  44293. if ( abstractRenderContext.isComputeNode === true ) {
  44294. prefix = 'c:' + this.renderer.info.compute.frameCalls;
  44295. } else {
  44296. prefix = 'r:' + this.renderer.info.render.frameCalls;
  44297. }
  44298. contextData.timestampUID = prefix + ':' + abstractRenderContext.id + ':f' + frame;
  44299. }
  44300. /**
  44301. * Returns a unique identifier for the given render context that can be used
  44302. * to allocate resources like occlusion queries or timestamp queries.
  44303. *
  44304. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  44305. * @return {string} The unique identifier.
  44306. */
  44307. getTimestampUID( abstractRenderContext ) {
  44308. return this.get( abstractRenderContext ).timestampUID;
  44309. }
  44310. /**
  44311. * Returns all timestamp frames for the given type.
  44312. *
  44313. * @param {string} type - The type of the time stamp.
  44314. * @return {Array<number>} The timestamp frames.
  44315. */
  44316. getTimestampFrames( type ) {
  44317. const queryPool = this.timestampQueryPool[ type ];
  44318. return queryPool ? queryPool.getTimestampFrames() : [];
  44319. }
  44320. /**
  44321. * Returns the query pool for the given uid.
  44322. *
  44323. * @param {string} uid - The unique identifier.
  44324. * @return {TimestampQueryPool} The query pool.
  44325. */
  44326. _getQueryPool( uid ) {
  44327. const type = uid.startsWith( 'c:' ) ? TimestampQuery.COMPUTE : TimestampQuery.RENDER;
  44328. const queryPool = this.timestampQueryPool[ type ];
  44329. return queryPool;
  44330. }
  44331. /**
  44332. * Returns the timestamp for the given uid.
  44333. *
  44334. * @param {string} uid - The unique identifier.
  44335. * @return {number} The timestamp.
  44336. */
  44337. getTimestamp( uid ) {
  44338. const queryPool = this._getQueryPool( uid );
  44339. return queryPool.getTimestamp( uid );
  44340. }
  44341. /**
  44342. * Returns `true` if a timestamp for the given uid is available.
  44343. *
  44344. * @param {string} uid - The unique identifier.
  44345. * @return {boolean} Whether the timestamp is available or not.
  44346. */
  44347. hasTimestamp( uid ) {
  44348. const queryPool = this._getQueryPool( uid );
  44349. return queryPool.hasTimestamp( uid );
  44350. }
  44351. /**
  44352. * Returns `true` if the given 3D object is fully occluded by other
  44353. * 3D objects in the scene. Backends must implement this method by using
  44354. * a Occlusion Query API.
  44355. *
  44356. * @abstract
  44357. * @param {RenderContext} renderContext - The render context.
  44358. * @param {Object3D} object - The 3D object to test.
  44359. * @return {boolean} Whether the 3D object is fully occluded or not.
  44360. */
  44361. isOccluded( /*renderContext, object*/ ) {}
  44362. /**
  44363. * Resolves the time stamp for the given render context and type.
  44364. *
  44365. * @async
  44366. * @abstract
  44367. * @param {string} [type='render'] - The type of the time stamp.
  44368. * @return {Promise<number>} A Promise that resolves with the time stamp.
  44369. */
  44370. async resolveTimestampsAsync( type = 'render' ) {
  44371. if ( ! this.trackTimestamp ) {
  44372. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  44373. return;
  44374. }
  44375. const queryPool = this.timestampQueryPool[ type ];
  44376. if ( ! queryPool ) {
  44377. return;
  44378. }
  44379. const duration = await queryPool.resolveQueriesAsync();
  44380. this.renderer.info[ type ].timestamp = duration;
  44381. return duration;
  44382. }
  44383. /**
  44384. * This method performs a readback operation by moving buffer data from
  44385. * a storage buffer attribute from the GPU to the CPU.
  44386. *
  44387. * @async
  44388. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  44389. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  44390. */
  44391. async getArrayBufferAsync( /* attribute */ ) {}
  44392. /**
  44393. * Checks if the given feature is supported by the backend.
  44394. *
  44395. * @async
  44396. * @abstract
  44397. * @param {string} name - The feature's name.
  44398. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  44399. */
  44400. async hasFeatureAsync( /*name*/ ) { }
  44401. /**
  44402. * Checks if the given feature is supported by the backend.
  44403. *
  44404. * @abstract
  44405. * @param {string} name - The feature's name.
  44406. * @return {boolean} Whether the feature is supported or not.
  44407. */
  44408. hasFeature( /*name*/ ) {}
  44409. /**
  44410. * Returns the maximum anisotropy texture filtering value.
  44411. *
  44412. * @abstract
  44413. * @return {number} The maximum anisotropy texture filtering value.
  44414. */
  44415. getMaxAnisotropy() {}
  44416. /**
  44417. * Returns the drawing buffer size.
  44418. *
  44419. * @return {Vector2} The drawing buffer size.
  44420. */
  44421. getDrawingBufferSize() {
  44422. _vector2 = _vector2 || new Vector2();
  44423. return this.renderer.getDrawingBufferSize( _vector2 );
  44424. }
  44425. /**
  44426. * Defines the scissor test.
  44427. *
  44428. * @abstract
  44429. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  44430. */
  44431. setScissorTest( /*boolean*/ ) { }
  44432. /**
  44433. * Returns the clear color and alpha into a single
  44434. * color object.
  44435. *
  44436. * @return {Color4} The clear color.
  44437. */
  44438. getClearColor() {
  44439. const renderer = this.renderer;
  44440. _color4 = _color4 || new Color4();
  44441. renderer.getClearColor( _color4 );
  44442. _color4.getRGB( _color4 );
  44443. return _color4;
  44444. }
  44445. /**
  44446. * Returns the DOM element. If no DOM element exists, the backend
  44447. * creates a new one.
  44448. *
  44449. * @return {HTMLCanvasElement} The DOM element.
  44450. */
  44451. getDomElement() {
  44452. let domElement = this.domElement;
  44453. if ( domElement === null ) {
  44454. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  44455. // OffscreenCanvas does not have setAttribute, see #22811
  44456. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  44457. this.domElement = domElement;
  44458. }
  44459. return domElement;
  44460. }
  44461. /**
  44462. * Sets a dictionary for the given object into the
  44463. * internal data structure.
  44464. *
  44465. * @param {Object} object - The object.
  44466. * @param {Object} value - The dictionary to set.
  44467. */
  44468. set( object, value ) {
  44469. this.data.set( object, value );
  44470. }
  44471. /**
  44472. * Returns the dictionary for the given object.
  44473. *
  44474. * @param {Object} object - The object.
  44475. * @return {Object} The object's dictionary.
  44476. */
  44477. get( object ) {
  44478. let map = this.data.get( object );
  44479. if ( map === undefined ) {
  44480. map = {};
  44481. this.data.set( object, map );
  44482. }
  44483. return map;
  44484. }
  44485. /**
  44486. * Checks if the given object has a dictionary
  44487. * with data defined.
  44488. *
  44489. * @param {Object} object - The object.
  44490. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  44491. */
  44492. has( object ) {
  44493. return this.data.has( object );
  44494. }
  44495. /**
  44496. * Deletes an object from the internal data structure.
  44497. *
  44498. * @param {Object} object - The object to delete.
  44499. */
  44500. delete( object ) {
  44501. this.data.delete( object );
  44502. }
  44503. /**
  44504. * Frees internal resources.
  44505. *
  44506. * @abstract
  44507. */
  44508. dispose() { }
  44509. }
  44510. let _id$1 = 0;
  44511. /**
  44512. * This module is internally used in context of compute shaders.
  44513. * This type of shader is not natively supported in WebGL 2 and
  44514. * thus implemented via Transform Feedback. `DualAttributeData`
  44515. * manages the related data.
  44516. *
  44517. * @private
  44518. */
  44519. class DualAttributeData {
  44520. constructor( attributeData, dualBuffer ) {
  44521. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  44522. this.type = attributeData.type;
  44523. this.bufferType = attributeData.bufferType;
  44524. this.pbo = attributeData.pbo;
  44525. this.byteLength = attributeData.byteLength;
  44526. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  44527. this.version = attributeData.version;
  44528. this.isInteger = attributeData.isInteger;
  44529. this.activeBufferIndex = 0;
  44530. this.baseId = attributeData.id;
  44531. }
  44532. get id() {
  44533. return `${ this.baseId }|${ this.activeBufferIndex }`;
  44534. }
  44535. get bufferGPU() {
  44536. return this.buffers[ this.activeBufferIndex ];
  44537. }
  44538. get transformBuffer() {
  44539. return this.buffers[ this.activeBufferIndex ^ 1 ];
  44540. }
  44541. switchBuffers() {
  44542. this.activeBufferIndex ^= 1;
  44543. }
  44544. }
  44545. /**
  44546. * A WebGL 2 backend utility module for managing shader attributes.
  44547. *
  44548. * @private
  44549. */
  44550. class WebGLAttributeUtils {
  44551. /**
  44552. * Constructs a new utility object.
  44553. *
  44554. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44555. */
  44556. constructor( backend ) {
  44557. /**
  44558. * A reference to the WebGL 2 backend.
  44559. *
  44560. * @type {WebGLBackend}
  44561. */
  44562. this.backend = backend;
  44563. }
  44564. /**
  44565. * Creates the GPU buffer for the given buffer attribute.
  44566. *
  44567. * @param {BufferAttribute} attribute - The buffer attribute.
  44568. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  44569. */
  44570. createAttribute( attribute, bufferType ) {
  44571. const backend = this.backend;
  44572. const { gl } = backend;
  44573. const array = attribute.array;
  44574. const usage = attribute.usage || gl.STATIC_DRAW;
  44575. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  44576. const bufferData = backend.get( bufferAttribute );
  44577. let bufferGPU = bufferData.bufferGPU;
  44578. if ( bufferGPU === undefined ) {
  44579. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  44580. bufferData.bufferGPU = bufferGPU;
  44581. bufferData.bufferType = bufferType;
  44582. bufferData.version = bufferAttribute.version;
  44583. }
  44584. //attribute.onUploadCallback();
  44585. let type;
  44586. if ( array instanceof Float32Array ) {
  44587. type = gl.FLOAT;
  44588. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  44589. type = gl.HALF_FLOAT;
  44590. } else if ( array instanceof Uint16Array ) {
  44591. if ( attribute.isFloat16BufferAttribute ) {
  44592. type = gl.HALF_FLOAT;
  44593. } else {
  44594. type = gl.UNSIGNED_SHORT;
  44595. }
  44596. } else if ( array instanceof Int16Array ) {
  44597. type = gl.SHORT;
  44598. } else if ( array instanceof Uint32Array ) {
  44599. type = gl.UNSIGNED_INT;
  44600. } else if ( array instanceof Int32Array ) {
  44601. type = gl.INT;
  44602. } else if ( array instanceof Int8Array ) {
  44603. type = gl.BYTE;
  44604. } else if ( array instanceof Uint8Array ) {
  44605. type = gl.UNSIGNED_BYTE;
  44606. } else if ( array instanceof Uint8ClampedArray ) {
  44607. type = gl.UNSIGNED_BYTE;
  44608. } else {
  44609. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  44610. }
  44611. let attributeData = {
  44612. bufferGPU,
  44613. bufferType,
  44614. type,
  44615. byteLength: array.byteLength,
  44616. bytesPerElement: array.BYTES_PER_ELEMENT,
  44617. version: attribute.version,
  44618. pbo: attribute.pbo,
  44619. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  44620. id: _id$1 ++
  44621. };
  44622. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  44623. // create buffer for transform feedback use
  44624. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  44625. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  44626. }
  44627. backend.set( attribute, attributeData );
  44628. }
  44629. /**
  44630. * Updates the GPU buffer of the given buffer attribute.
  44631. *
  44632. * @param {BufferAttribute} attribute - The buffer attribute.
  44633. */
  44634. updateAttribute( attribute ) {
  44635. const backend = this.backend;
  44636. const { gl } = backend;
  44637. const array = attribute.array;
  44638. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  44639. const bufferData = backend.get( bufferAttribute );
  44640. const bufferType = bufferData.bufferType;
  44641. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  44642. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  44643. if ( updateRanges.length === 0 ) {
  44644. // Not using update ranges
  44645. gl.bufferSubData( bufferType, 0, array );
  44646. } else {
  44647. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  44648. const range = updateRanges[ i ];
  44649. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  44650. array, range.start, range.count );
  44651. }
  44652. bufferAttribute.clearUpdateRanges();
  44653. }
  44654. gl.bindBuffer( bufferType, null );
  44655. bufferData.version = bufferAttribute.version;
  44656. }
  44657. /**
  44658. * Destroys the GPU buffer of the given buffer attribute.
  44659. *
  44660. * @param {BufferAttribute} attribute - The buffer attribute.
  44661. */
  44662. destroyAttribute( attribute ) {
  44663. const backend = this.backend;
  44664. const { gl } = backend;
  44665. if ( attribute.isInterleavedBufferAttribute ) {
  44666. backend.delete( attribute.data );
  44667. }
  44668. const attributeData = backend.get( attribute );
  44669. gl.deleteBuffer( attributeData.bufferGPU );
  44670. backend.delete( attribute );
  44671. }
  44672. /**
  44673. * This method performs a readback operation by moving buffer data from
  44674. * a storage buffer attribute from the GPU to the CPU.
  44675. *
  44676. * @async
  44677. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  44678. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  44679. */
  44680. async getArrayBufferAsync( attribute ) {
  44681. const backend = this.backend;
  44682. const { gl } = backend;
  44683. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  44684. const { bufferGPU } = backend.get( bufferAttribute );
  44685. const array = attribute.array;
  44686. const byteLength = array.byteLength;
  44687. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  44688. const writeBuffer = gl.createBuffer();
  44689. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  44690. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  44691. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  44692. await backend.utils._clientWaitAsync();
  44693. const dstBuffer = new attribute.array.constructor( array.length );
  44694. // Ensure the buffer is bound before reading
  44695. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  44696. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  44697. gl.deleteBuffer( writeBuffer );
  44698. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  44699. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  44700. return dstBuffer.buffer;
  44701. }
  44702. /**
  44703. * Creates a WebGL buffer with the given data.
  44704. *
  44705. * @private
  44706. * @param {WebGL2RenderingContext} gl - The rendering context.
  44707. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  44708. * @param {TypedArray} array - The array of the buffer attribute.
  44709. * @param {GLenum} usage - The usage.
  44710. * @return {WebGLBuffer} The WebGL buffer.
  44711. */
  44712. _createBuffer( gl, bufferType, array, usage ) {
  44713. const bufferGPU = gl.createBuffer();
  44714. gl.bindBuffer( bufferType, bufferGPU );
  44715. gl.bufferData( bufferType, array, usage );
  44716. gl.bindBuffer( bufferType, null );
  44717. return bufferGPU;
  44718. }
  44719. }
  44720. let equationToGL, factorToGL;
  44721. /**
  44722. * A WebGL 2 backend utility module for managing the WebGL state.
  44723. *
  44724. * The major goal of this module is to reduce the number of state changes
  44725. * by caching the WEbGL state with a series of variables. In this way, the
  44726. * renderer only executes state change commands when necessary which
  44727. * improves the overall performance.
  44728. *
  44729. * @private
  44730. */
  44731. class WebGLState {
  44732. /**
  44733. * Constructs a new utility object.
  44734. *
  44735. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44736. */
  44737. constructor( backend ) {
  44738. /**
  44739. * A reference to the WebGL 2 backend.
  44740. *
  44741. * @type {WebGLBackend}
  44742. */
  44743. this.backend = backend;
  44744. /**
  44745. * A reference to the rendering context.
  44746. *
  44747. * @type {WebGL2RenderingContext}
  44748. */
  44749. this.gl = this.backend.gl;
  44750. // Below properties are intended to cache
  44751. // the WebGL state and are not explicitly
  44752. // documented for convenience reasons.
  44753. this.enabled = {};
  44754. this.currentFlipSided = null;
  44755. this.currentCullFace = null;
  44756. this.currentProgram = null;
  44757. this.currentBlendingEnabled = false;
  44758. this.currentBlending = null;
  44759. this.currentBlendSrc = null;
  44760. this.currentBlendDst = null;
  44761. this.currentBlendSrcAlpha = null;
  44762. this.currentBlendDstAlpha = null;
  44763. this.currentPremultipledAlpha = null;
  44764. this.currentPolygonOffsetFactor = null;
  44765. this.currentPolygonOffsetUnits = null;
  44766. this.currentColorMask = null;
  44767. this.currentDepthFunc = null;
  44768. this.currentDepthMask = null;
  44769. this.currentStencilFunc = null;
  44770. this.currentStencilRef = null;
  44771. this.currentStencilFuncMask = null;
  44772. this.currentStencilFail = null;
  44773. this.currentStencilZFail = null;
  44774. this.currentStencilZPass = null;
  44775. this.currentStencilMask = null;
  44776. this.currentLineWidth = null;
  44777. this.currentClippingPlanes = 0;
  44778. this.currentVAO = null;
  44779. this.currentIndex = null;
  44780. this.currentBoundFramebuffers = {};
  44781. this.currentDrawbuffers = new WeakMap();
  44782. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  44783. this.currentTextureSlot = null;
  44784. this.currentBoundTextures = {};
  44785. this.currentBoundBufferBases = {};
  44786. this._init();
  44787. }
  44788. /**
  44789. * Inits the state of the utility.
  44790. *
  44791. * @private
  44792. */
  44793. _init() {
  44794. const gl = this.gl;
  44795. // Store only WebGL constants here.
  44796. equationToGL = {
  44797. [ AddEquation ]: gl.FUNC_ADD,
  44798. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  44799. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  44800. };
  44801. factorToGL = {
  44802. [ ZeroFactor ]: gl.ZERO,
  44803. [ OneFactor ]: gl.ONE,
  44804. [ SrcColorFactor ]: gl.SRC_COLOR,
  44805. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  44806. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  44807. [ DstColorFactor ]: gl.DST_COLOR,
  44808. [ DstAlphaFactor ]: gl.DST_ALPHA,
  44809. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  44810. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  44811. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  44812. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  44813. };
  44814. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  44815. const viewportParam = gl.getParameter( gl.VIEWPORT );
  44816. this.currentScissor = new Vector4().fromArray( scissorParam );
  44817. this.currentViewport = new Vector4().fromArray( viewportParam );
  44818. this._tempVec4 = new Vector4();
  44819. }
  44820. /**
  44821. * Enables the given WebGL capability.
  44822. *
  44823. * This method caches the capability state so
  44824. * `gl.enable()` is only called when necessary.
  44825. *
  44826. * @param {GLenum} id - The capability to enable.
  44827. */
  44828. enable( id ) {
  44829. const { enabled } = this;
  44830. if ( enabled[ id ] !== true ) {
  44831. this.gl.enable( id );
  44832. enabled[ id ] = true;
  44833. }
  44834. }
  44835. /**
  44836. * Disables the given WebGL capability.
  44837. *
  44838. * This method caches the capability state so
  44839. * `gl.disable()` is only called when necessary.
  44840. *
  44841. * @param {GLenum} id - The capability to enable.
  44842. */
  44843. disable( id ) {
  44844. const { enabled } = this;
  44845. if ( enabled[ id ] !== false ) {
  44846. this.gl.disable( id );
  44847. enabled[ id ] = false;
  44848. }
  44849. }
  44850. /**
  44851. * Specifies whether polygons are front- or back-facing
  44852. * by setting the winding orientation.
  44853. *
  44854. * This method caches the state so `gl.frontFace()` is only
  44855. * called when necessary.
  44856. *
  44857. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  44858. */
  44859. setFlipSided( flipSided ) {
  44860. if ( this.currentFlipSided !== flipSided ) {
  44861. const { gl } = this;
  44862. if ( flipSided ) {
  44863. gl.frontFace( gl.CW );
  44864. } else {
  44865. gl.frontFace( gl.CCW );
  44866. }
  44867. this.currentFlipSided = flipSided;
  44868. }
  44869. }
  44870. /**
  44871. * Specifies whether or not front- and/or back-facing
  44872. * polygons can be culled.
  44873. *
  44874. * This method caches the state so `gl.cullFace()` is only
  44875. * called when necessary.
  44876. *
  44877. * @param {number} cullFace - Defines which polygons are candidates for culling.
  44878. */
  44879. setCullFace( cullFace ) {
  44880. const { gl } = this;
  44881. if ( cullFace !== CullFaceNone ) {
  44882. this.enable( gl.CULL_FACE );
  44883. if ( cullFace !== this.currentCullFace ) {
  44884. if ( cullFace === CullFaceBack ) {
  44885. gl.cullFace( gl.BACK );
  44886. } else if ( cullFace === CullFaceFront ) {
  44887. gl.cullFace( gl.FRONT );
  44888. } else {
  44889. gl.cullFace( gl.FRONT_AND_BACK );
  44890. }
  44891. }
  44892. } else {
  44893. this.disable( gl.CULL_FACE );
  44894. }
  44895. this.currentCullFace = cullFace;
  44896. }
  44897. /**
  44898. * Specifies the width of line primitives.
  44899. *
  44900. * This method caches the state so `gl.lineWidth()` is only
  44901. * called when necessary.
  44902. *
  44903. * @param {number} width - The line width.
  44904. */
  44905. setLineWidth( width ) {
  44906. const { currentLineWidth, gl } = this;
  44907. if ( width !== currentLineWidth ) {
  44908. gl.lineWidth( width );
  44909. this.currentLineWidth = width;
  44910. }
  44911. }
  44912. /**
  44913. * Defines the blending.
  44914. *
  44915. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  44916. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  44917. *
  44918. * @param {number} blending - The blending type.
  44919. * @param {number} blendEquation - The blending equation.
  44920. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  44921. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  44922. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  44923. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  44924. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  44925. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  44926. */
  44927. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  44928. const { gl } = this;
  44929. if ( blending === NoBlending ) {
  44930. if ( this.currentBlendingEnabled === true ) {
  44931. this.disable( gl.BLEND );
  44932. this.currentBlendingEnabled = false;
  44933. }
  44934. return;
  44935. }
  44936. if ( this.currentBlendingEnabled === false ) {
  44937. this.enable( gl.BLEND );
  44938. this.currentBlendingEnabled = true;
  44939. }
  44940. if ( blending !== CustomBlending ) {
  44941. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  44942. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  44943. gl.blendEquation( gl.FUNC_ADD );
  44944. this.currentBlendEquation = AddEquation;
  44945. this.currentBlendEquationAlpha = AddEquation;
  44946. }
  44947. if ( premultipliedAlpha ) {
  44948. switch ( blending ) {
  44949. case NormalBlending:
  44950. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  44951. break;
  44952. case AdditiveBlending:
  44953. gl.blendFunc( gl.ONE, gl.ONE );
  44954. break;
  44955. case SubtractiveBlending:
  44956. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  44957. break;
  44958. case MultiplyBlending:
  44959. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  44960. break;
  44961. default:
  44962. error( 'WebGLState: Invalid blending: ', blending );
  44963. break;
  44964. }
  44965. } else {
  44966. switch ( blending ) {
  44967. case NormalBlending:
  44968. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  44969. break;
  44970. case AdditiveBlending:
  44971. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  44972. break;
  44973. case SubtractiveBlending:
  44974. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  44975. break;
  44976. case MultiplyBlending:
  44977. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  44978. break;
  44979. default:
  44980. error( 'WebGLState: Invalid blending: ', blending );
  44981. break;
  44982. }
  44983. }
  44984. this.currentBlendSrc = null;
  44985. this.currentBlendDst = null;
  44986. this.currentBlendSrcAlpha = null;
  44987. this.currentBlendDstAlpha = null;
  44988. this.currentBlending = blending;
  44989. this.currentPremultipledAlpha = premultipliedAlpha;
  44990. }
  44991. return;
  44992. }
  44993. // custom blending
  44994. blendEquationAlpha = blendEquationAlpha || blendEquation;
  44995. blendSrcAlpha = blendSrcAlpha || blendSrc;
  44996. blendDstAlpha = blendDstAlpha || blendDst;
  44997. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  44998. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  44999. this.currentBlendEquation = blendEquation;
  45000. this.currentBlendEquationAlpha = blendEquationAlpha;
  45001. }
  45002. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  45003. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  45004. this.currentBlendSrc = blendSrc;
  45005. this.currentBlendDst = blendDst;
  45006. this.currentBlendSrcAlpha = blendSrcAlpha;
  45007. this.currentBlendDstAlpha = blendDstAlpha;
  45008. }
  45009. this.currentBlending = blending;
  45010. this.currentPremultipledAlpha = false;
  45011. }
  45012. /**
  45013. * Specifies whether colors can be written when rendering
  45014. * into a framebuffer or not.
  45015. *
  45016. * This method caches the state so `gl.colorMask()` is only
  45017. * called when necessary.
  45018. *
  45019. * @param {boolean} colorMask - The color mask.
  45020. */
  45021. setColorMask( colorMask ) {
  45022. if ( this.currentColorMask !== colorMask ) {
  45023. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  45024. this.currentColorMask = colorMask;
  45025. }
  45026. }
  45027. /**
  45028. * Specifies whether the depth test is enabled or not.
  45029. *
  45030. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  45031. */
  45032. setDepthTest( depthTest ) {
  45033. const { gl } = this;
  45034. if ( depthTest ) {
  45035. this.enable( gl.DEPTH_TEST );
  45036. } else {
  45037. this.disable( gl.DEPTH_TEST );
  45038. }
  45039. }
  45040. /**
  45041. * Specifies whether depth values can be written when rendering
  45042. * into a framebuffer or not.
  45043. *
  45044. * This method caches the state so `gl.depthMask()` is only
  45045. * called when necessary.
  45046. *
  45047. * @param {boolean} depthMask - The depth mask.
  45048. */
  45049. setDepthMask( depthMask ) {
  45050. if ( this.currentDepthMask !== depthMask ) {
  45051. this.gl.depthMask( depthMask );
  45052. this.currentDepthMask = depthMask;
  45053. }
  45054. }
  45055. /**
  45056. * Specifies the depth compare function.
  45057. *
  45058. * This method caches the state so `gl.depthFunc()` is only
  45059. * called when necessary.
  45060. *
  45061. * @param {number} depthFunc - The depth compare function.
  45062. */
  45063. setDepthFunc( depthFunc ) {
  45064. if ( this.currentDepthFunc !== depthFunc ) {
  45065. const { gl } = this;
  45066. switch ( depthFunc ) {
  45067. case NeverDepth:
  45068. gl.depthFunc( gl.NEVER );
  45069. break;
  45070. case AlwaysDepth:
  45071. gl.depthFunc( gl.ALWAYS );
  45072. break;
  45073. case LessDepth:
  45074. gl.depthFunc( gl.LESS );
  45075. break;
  45076. case LessEqualDepth:
  45077. gl.depthFunc( gl.LEQUAL );
  45078. break;
  45079. case EqualDepth:
  45080. gl.depthFunc( gl.EQUAL );
  45081. break;
  45082. case GreaterEqualDepth:
  45083. gl.depthFunc( gl.GEQUAL );
  45084. break;
  45085. case GreaterDepth:
  45086. gl.depthFunc( gl.GREATER );
  45087. break;
  45088. case NotEqualDepth:
  45089. gl.depthFunc( gl.NOTEQUAL );
  45090. break;
  45091. default:
  45092. gl.depthFunc( gl.LEQUAL );
  45093. }
  45094. this.currentDepthFunc = depthFunc;
  45095. }
  45096. }
  45097. /**
  45098. * Specifies the scissor box.
  45099. *
  45100. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  45101. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  45102. * @param {number} width - The width of the viewport.
  45103. * @param {number} height - The height of the viewport.
  45104. *
  45105. */
  45106. scissor( x, y, width, height ) {
  45107. const scissor = this._tempVec4.set( x, y, width, height );
  45108. if ( this.currentScissor.equals( scissor ) === false ) {
  45109. const { gl } = this;
  45110. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  45111. this.currentScissor.copy( scissor );
  45112. }
  45113. }
  45114. /**
  45115. * Specifies the viewport.
  45116. *
  45117. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  45118. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  45119. * @param {number} width - The width of the viewport.
  45120. * @param {number} height - The height of the viewport.
  45121. *
  45122. */
  45123. viewport( x, y, width, height ) {
  45124. const viewport = this._tempVec4.set( x, y, width, height );
  45125. if ( this.currentViewport.equals( viewport ) === false ) {
  45126. const { gl } = this;
  45127. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  45128. this.currentViewport.copy( viewport );
  45129. }
  45130. }
  45131. /**
  45132. * Defines the scissor test.
  45133. *
  45134. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  45135. */
  45136. setScissorTest( boolean ) {
  45137. const gl = this.gl;
  45138. if ( boolean ) {
  45139. gl.enable( gl.SCISSOR_TEST );
  45140. } else {
  45141. gl.disable( gl.SCISSOR_TEST );
  45142. }
  45143. }
  45144. /**
  45145. * Specifies whether the stencil test is enabled or not.
  45146. *
  45147. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  45148. */
  45149. setStencilTest( stencilTest ) {
  45150. const { gl } = this;
  45151. if ( stencilTest ) {
  45152. this.enable( gl.STENCIL_TEST );
  45153. } else {
  45154. this.disable( gl.STENCIL_TEST );
  45155. }
  45156. }
  45157. /**
  45158. * Specifies whether stencil values can be written when rendering
  45159. * into a framebuffer or not.
  45160. *
  45161. * This method caches the state so `gl.stencilMask()` is only
  45162. * called when necessary.
  45163. *
  45164. * @param {boolean} stencilMask - The stencil mask.
  45165. */
  45166. setStencilMask( stencilMask ) {
  45167. if ( this.currentStencilMask !== stencilMask ) {
  45168. this.gl.stencilMask( stencilMask );
  45169. this.currentStencilMask = stencilMask;
  45170. }
  45171. }
  45172. /**
  45173. * Specifies whether the stencil test functions.
  45174. *
  45175. * This method caches the state so `gl.stencilFunc()` is only
  45176. * called when necessary.
  45177. *
  45178. * @param {number} stencilFunc - The stencil compare function.
  45179. * @param {number} stencilRef - The reference value for the stencil test.
  45180. * @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.
  45181. */
  45182. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  45183. if ( this.currentStencilFunc !== stencilFunc ||
  45184. this.currentStencilRef !== stencilRef ||
  45185. this.currentStencilFuncMask !== stencilMask ) {
  45186. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  45187. this.currentStencilFunc = stencilFunc;
  45188. this.currentStencilRef = stencilRef;
  45189. this.currentStencilFuncMask = stencilMask;
  45190. }
  45191. }
  45192. /**
  45193. * Specifies whether the stencil test operation.
  45194. *
  45195. * This method caches the state so `gl.stencilOp()` is only
  45196. * called when necessary.
  45197. *
  45198. * @param {number} stencilFail - The function to use when the stencil test fails.
  45199. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  45200. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  45201. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  45202. */
  45203. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  45204. if ( this.currentStencilFail !== stencilFail ||
  45205. this.currentStencilZFail !== stencilZFail ||
  45206. this.currentStencilZPass !== stencilZPass ) {
  45207. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  45208. this.currentStencilFail = stencilFail;
  45209. this.currentStencilZFail = stencilZFail;
  45210. this.currentStencilZPass = stencilZPass;
  45211. }
  45212. }
  45213. /**
  45214. * Configures the WebGL state for the given material.
  45215. *
  45216. * @param {Material} material - The material to configure the state for.
  45217. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  45218. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  45219. */
  45220. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  45221. const { gl } = this;
  45222. material.side === DoubleSide
  45223. ? this.disable( gl.CULL_FACE )
  45224. : this.enable( gl.CULL_FACE );
  45225. let flipSided = ( material.side === BackSide );
  45226. if ( frontFaceCW ) flipSided = ! flipSided;
  45227. this.setFlipSided( flipSided );
  45228. ( material.blending === NormalBlending && material.transparent === false )
  45229. ? this.setBlending( NoBlending )
  45230. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  45231. this.setDepthFunc( material.depthFunc );
  45232. this.setDepthTest( material.depthTest );
  45233. this.setDepthMask( material.depthWrite );
  45234. this.setColorMask( material.colorWrite );
  45235. const stencilWrite = material.stencilWrite;
  45236. this.setStencilTest( stencilWrite );
  45237. if ( stencilWrite ) {
  45238. this.setStencilMask( material.stencilWriteMask );
  45239. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  45240. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  45241. }
  45242. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  45243. material.alphaToCoverage === true && this.backend.renderer.currentSamples > 0
  45244. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  45245. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  45246. if ( hardwareClippingPlanes > 0 ) {
  45247. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  45248. const CLIP_DISTANCE0_WEBGL = 0x3000;
  45249. for ( let i = 0; i < 8; i ++ ) {
  45250. if ( i < hardwareClippingPlanes ) {
  45251. this.enable( CLIP_DISTANCE0_WEBGL + i );
  45252. } else {
  45253. this.disable( CLIP_DISTANCE0_WEBGL + i );
  45254. }
  45255. }
  45256. }
  45257. }
  45258. }
  45259. /**
  45260. * Specifies the polygon offset.
  45261. *
  45262. * This method caches the state so `gl.polygonOffset()` is only
  45263. * called when necessary.
  45264. *
  45265. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  45266. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  45267. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  45268. */
  45269. setPolygonOffset( polygonOffset, factor, units ) {
  45270. const { gl } = this;
  45271. if ( polygonOffset ) {
  45272. this.enable( gl.POLYGON_OFFSET_FILL );
  45273. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  45274. gl.polygonOffset( factor, units );
  45275. this.currentPolygonOffsetFactor = factor;
  45276. this.currentPolygonOffsetUnits = units;
  45277. }
  45278. } else {
  45279. this.disable( gl.POLYGON_OFFSET_FILL );
  45280. }
  45281. }
  45282. /**
  45283. * Defines the usage of the given WebGL program.
  45284. *
  45285. * This method caches the state so `gl.useProgram()` is only
  45286. * called when necessary.
  45287. *
  45288. * @param {WebGLProgram} program - The WebGL program to use.
  45289. * @return {boolean} Whether a program change has been executed or not.
  45290. */
  45291. useProgram( program ) {
  45292. if ( this.currentProgram !== program ) {
  45293. this.gl.useProgram( program );
  45294. this.currentProgram = program;
  45295. return true;
  45296. }
  45297. return false;
  45298. }
  45299. /**
  45300. * Sets the vertex state by binding the given VAO and element buffer.
  45301. *
  45302. * @param {WebGLVertexArrayObject} vao - The VAO.
  45303. * @param {?WebGLBuffer} indexBuffer - The index buffer.
  45304. * @return {boolean} Whether a vertex state has been changed or not.
  45305. */
  45306. setVertexState( vao, indexBuffer = null ) {
  45307. const gl = this.gl;
  45308. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  45309. gl.bindVertexArray( vao );
  45310. if ( indexBuffer !== null ) {
  45311. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  45312. }
  45313. this.currentVAO = vao;
  45314. this.currentIndex = indexBuffer;
  45315. return true;
  45316. }
  45317. return false;
  45318. }
  45319. /**
  45320. * Resets the vertex array state by resetting the VAO and element buffer.
  45321. */
  45322. resetVertexState() {
  45323. const gl = this.gl;
  45324. gl.bindVertexArray( null );
  45325. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  45326. this.currentVAO = null;
  45327. this.currentIndex = null;
  45328. }
  45329. // framebuffer
  45330. /**
  45331. * Binds the given framebuffer.
  45332. *
  45333. * This method caches the state so `gl.bindFramebuffer()` is only
  45334. * called when necessary.
  45335. *
  45336. * @param {number} target - The binding point (target).
  45337. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  45338. * @return {boolean} Whether a bind has been executed or not.
  45339. */
  45340. bindFramebuffer( target, framebuffer ) {
  45341. const { gl, currentBoundFramebuffers } = this;
  45342. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  45343. gl.bindFramebuffer( target, framebuffer );
  45344. currentBoundFramebuffers[ target ] = framebuffer;
  45345. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  45346. if ( target === gl.DRAW_FRAMEBUFFER ) {
  45347. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  45348. }
  45349. if ( target === gl.FRAMEBUFFER ) {
  45350. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  45351. }
  45352. return true;
  45353. }
  45354. return false;
  45355. }
  45356. /**
  45357. * Defines draw buffers to which fragment colors are written into.
  45358. * Configures the MRT setup of custom framebuffers.
  45359. *
  45360. * This method caches the state so `gl.drawBuffers()` is only
  45361. * called when necessary.
  45362. *
  45363. * @param {RenderContext} renderContext - The render context.
  45364. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  45365. */
  45366. drawBuffers( renderContext, framebuffer ) {
  45367. const { gl } = this;
  45368. let drawBuffers = [];
  45369. let needsUpdate = false;
  45370. if ( renderContext.textures !== null ) {
  45371. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  45372. if ( drawBuffers === undefined ) {
  45373. drawBuffers = [];
  45374. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  45375. }
  45376. const textures = renderContext.textures;
  45377. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  45378. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  45379. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  45380. }
  45381. drawBuffers.length = textures.length;
  45382. needsUpdate = true;
  45383. }
  45384. } else {
  45385. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  45386. drawBuffers[ 0 ] = gl.BACK;
  45387. needsUpdate = true;
  45388. }
  45389. }
  45390. if ( needsUpdate ) {
  45391. gl.drawBuffers( drawBuffers );
  45392. }
  45393. }
  45394. // texture
  45395. /**
  45396. * Makes the given texture unit active.
  45397. *
  45398. * This method caches the state so `gl.activeTexture()` is only
  45399. * called when necessary.
  45400. *
  45401. * @param {number} webglSlot - The texture unit to make active.
  45402. */
  45403. activeTexture( webglSlot ) {
  45404. const { gl, currentTextureSlot, maxTextures } = this;
  45405. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  45406. if ( currentTextureSlot !== webglSlot ) {
  45407. gl.activeTexture( webglSlot );
  45408. this.currentTextureSlot = webglSlot;
  45409. }
  45410. }
  45411. /**
  45412. * Binds the given WebGL texture to a target.
  45413. *
  45414. * This method caches the state so `gl.bindTexture()` is only
  45415. * called when necessary.
  45416. *
  45417. * @param {number} webglType - The binding point (target).
  45418. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  45419. * @param {number} webglSlot - The texture.
  45420. */
  45421. bindTexture( webglType, webglTexture, webglSlot ) {
  45422. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  45423. if ( webglSlot === undefined ) {
  45424. if ( currentTextureSlot === null ) {
  45425. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  45426. } else {
  45427. webglSlot = currentTextureSlot;
  45428. }
  45429. }
  45430. let boundTexture = currentBoundTextures[ webglSlot ];
  45431. if ( boundTexture === undefined ) {
  45432. boundTexture = { type: undefined, texture: undefined };
  45433. currentBoundTextures[ webglSlot ] = boundTexture;
  45434. }
  45435. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  45436. if ( currentTextureSlot !== webglSlot ) {
  45437. gl.activeTexture( webglSlot );
  45438. this.currentTextureSlot = webglSlot;
  45439. }
  45440. gl.bindTexture( webglType, webglTexture );
  45441. boundTexture.type = webglType;
  45442. boundTexture.texture = webglTexture;
  45443. }
  45444. }
  45445. /**
  45446. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  45447. *
  45448. * This method caches the state so `gl.bindBufferBase()` is only
  45449. * called when necessary.
  45450. *
  45451. * @param {number} target - The target for the bind operation.
  45452. * @param {number} index - The index of the target.
  45453. * @param {WebGLBuffer} buffer - The WebGL buffer.
  45454. * @return {boolean} Whether a bind has been executed or not.
  45455. */
  45456. bindBufferBase( target, index, buffer ) {
  45457. const { gl } = this;
  45458. const key = `${target}-${index}`;
  45459. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  45460. gl.bindBufferBase( target, index, buffer );
  45461. this.currentBoundBufferBases[ key ] = buffer;
  45462. return true;
  45463. }
  45464. return false;
  45465. }
  45466. /**
  45467. * Unbinds the current bound texture.
  45468. *
  45469. * This method caches the state so `gl.bindTexture()` is only
  45470. * called when necessary.
  45471. */
  45472. unbindTexture() {
  45473. const { gl, currentTextureSlot, currentBoundTextures } = this;
  45474. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  45475. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  45476. gl.bindTexture( boundTexture.type, null );
  45477. boundTexture.type = undefined;
  45478. boundTexture.texture = undefined;
  45479. }
  45480. }
  45481. }
  45482. /**
  45483. * A WebGL 2 backend utility module with common helpers.
  45484. *
  45485. * @private
  45486. */
  45487. class WebGLUtils {
  45488. /**
  45489. * Constructs a new utility object.
  45490. *
  45491. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45492. */
  45493. constructor( backend ) {
  45494. /**
  45495. * A reference to the WebGL 2 backend.
  45496. *
  45497. * @type {WebGLBackend}
  45498. */
  45499. this.backend = backend;
  45500. /**
  45501. * A reference to the rendering context.
  45502. *
  45503. * @type {WebGL2RenderingContext}
  45504. */
  45505. this.gl = this.backend.gl;
  45506. /**
  45507. * A reference to a backend module holding extension-related
  45508. * utility functions.
  45509. *
  45510. * @type {WebGLExtensions}
  45511. */
  45512. this.extensions = backend.extensions;
  45513. }
  45514. /**
  45515. * Converts the given three.js constant into a WebGL constant.
  45516. * The method currently supports the conversion of texture formats
  45517. * and types.
  45518. *
  45519. * @param {number} p - The three.js constant.
  45520. * @param {string} [colorSpace=NoColorSpace] - The color space.
  45521. * @return {?number} The corresponding WebGL constant.
  45522. */
  45523. convert( p, colorSpace = NoColorSpace ) {
  45524. const { gl, extensions } = this;
  45525. let extension;
  45526. const transfer = ColorManagement.getTransfer( colorSpace );
  45527. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  45528. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  45529. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  45530. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  45531. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  45532. if ( p === ByteType ) return gl.BYTE;
  45533. if ( p === ShortType ) return gl.SHORT;
  45534. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  45535. if ( p === IntType ) return gl.INT;
  45536. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  45537. if ( p === FloatType ) return gl.FLOAT;
  45538. if ( p === HalfFloatType ) {
  45539. return gl.HALF_FLOAT;
  45540. }
  45541. if ( p === AlphaFormat ) return gl.ALPHA;
  45542. if ( p === RGBFormat ) return gl.RGB;
  45543. if ( p === RGBAFormat ) return gl.RGBA;
  45544. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  45545. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  45546. // WebGL2 formats.
  45547. if ( p === RedFormat ) return gl.RED;
  45548. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  45549. if ( p === RGFormat ) return gl.RG;
  45550. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  45551. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  45552. // S3TC
  45553. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  45554. if ( transfer === SRGBTransfer ) {
  45555. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  45556. if ( extension !== null ) {
  45557. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  45558. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  45559. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  45560. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  45561. } else {
  45562. return null;
  45563. }
  45564. } else {
  45565. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  45566. if ( extension !== null ) {
  45567. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  45568. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  45569. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  45570. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  45571. } else {
  45572. return null;
  45573. }
  45574. }
  45575. }
  45576. // PVRTC
  45577. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  45578. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  45579. if ( extension !== null ) {
  45580. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  45581. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  45582. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  45583. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  45584. } else {
  45585. return null;
  45586. }
  45587. }
  45588. // ETC
  45589. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  45590. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  45591. if ( extension !== null ) {
  45592. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  45593. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  45594. } else {
  45595. return null;
  45596. }
  45597. }
  45598. // ASTC
  45599. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  45600. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  45601. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  45602. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  45603. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  45604. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  45605. if ( extension !== null ) {
  45606. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  45607. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  45608. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  45609. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  45610. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  45611. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  45612. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  45613. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  45614. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  45615. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  45616. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  45617. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  45618. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  45619. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  45620. } else {
  45621. return null;
  45622. }
  45623. }
  45624. // BPTC
  45625. if ( p === RGBA_BPTC_Format ) {
  45626. extension = extensions.get( 'EXT_texture_compression_bptc' );
  45627. if ( extension !== null ) {
  45628. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  45629. } else {
  45630. return null;
  45631. }
  45632. }
  45633. // RGTC
  45634. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  45635. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  45636. if ( extension !== null ) {
  45637. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  45638. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  45639. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  45640. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  45641. } else {
  45642. return null;
  45643. }
  45644. }
  45645. //
  45646. if ( p === UnsignedInt248Type ) {
  45647. return gl.UNSIGNED_INT_24_8;
  45648. }
  45649. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  45650. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  45651. }
  45652. /**
  45653. * This method can be used to synchronize the CPU with the GPU by waiting until
  45654. * ongoing GPU commands have been completed.
  45655. *
  45656. * @private
  45657. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  45658. */
  45659. _clientWaitAsync() {
  45660. const { gl } = this;
  45661. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  45662. gl.flush();
  45663. return new Promise( ( resolve, reject ) => {
  45664. function test() {
  45665. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  45666. if ( res === gl.WAIT_FAILED ) {
  45667. gl.deleteSync( sync );
  45668. reject();
  45669. return;
  45670. }
  45671. if ( res === gl.TIMEOUT_EXPIRED ) {
  45672. requestAnimationFrame( test );
  45673. return;
  45674. }
  45675. gl.deleteSync( sync );
  45676. resolve();
  45677. }
  45678. test();
  45679. } );
  45680. }
  45681. }
  45682. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  45683. /**
  45684. * A WebGL 2 backend utility module for managing textures.
  45685. *
  45686. * @private
  45687. */
  45688. class WebGLTextureUtils {
  45689. /**
  45690. * Constructs a new utility object.
  45691. *
  45692. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45693. */
  45694. constructor( backend ) {
  45695. /**
  45696. * A reference to the WebGL 2 backend.
  45697. *
  45698. * @type {WebGLBackend}
  45699. */
  45700. this.backend = backend;
  45701. /**
  45702. * A reference to the rendering context.
  45703. *
  45704. * @type {WebGL2RenderingContext}
  45705. */
  45706. this.gl = backend.gl;
  45707. /**
  45708. * A reference to a backend module holding extension-related
  45709. * utility functions.
  45710. *
  45711. * @type {WebGLExtensions}
  45712. */
  45713. this.extensions = backend.extensions;
  45714. /**
  45715. * A dictionary for managing default textures. The key
  45716. * is the binding point (target), the value the WEbGL texture object.
  45717. *
  45718. * @type {Object<GLenum,WebGLTexture>}
  45719. */
  45720. this.defaultTextures = {};
  45721. /**
  45722. * A scratch framebuffer used for attaching the source texture in
  45723. * {@link copyTextureToTexture}.
  45724. *
  45725. * @private
  45726. * @type {?WebGLFramebuffer}
  45727. */
  45728. this._srcFramebuffer = null;
  45729. /**
  45730. * A scratch framebuffer used for attaching the destination texture in
  45731. * {@link copyTextureToTexture}.
  45732. *
  45733. * @private
  45734. * @type {?WebGLFramebuffer}
  45735. */
  45736. this._dstFramebuffer = null;
  45737. if ( initialized === false ) {
  45738. this._init();
  45739. initialized = true;
  45740. }
  45741. }
  45742. /**
  45743. * Inits the state of the utility.
  45744. *
  45745. * @private
  45746. */
  45747. _init() {
  45748. const gl = this.gl;
  45749. // Store only WebGL constants here.
  45750. wrappingToGL = {
  45751. [ RepeatWrapping ]: gl.REPEAT,
  45752. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  45753. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  45754. };
  45755. filterToGL = {
  45756. [ NearestFilter ]: gl.NEAREST,
  45757. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  45758. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  45759. [ LinearFilter ]: gl.LINEAR,
  45760. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  45761. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  45762. };
  45763. compareToGL = {
  45764. [ NeverCompare ]: gl.NEVER,
  45765. [ AlwaysCompare ]: gl.ALWAYS,
  45766. [ LessCompare ]: gl.LESS,
  45767. [ LessEqualCompare ]: gl.LEQUAL,
  45768. [ EqualCompare ]: gl.EQUAL,
  45769. [ GreaterEqualCompare ]: gl.GEQUAL,
  45770. [ GreaterCompare ]: gl.GREATER,
  45771. [ NotEqualCompare ]: gl.NOTEQUAL
  45772. };
  45773. }
  45774. /**
  45775. * Returns the native texture type for the given texture.
  45776. *
  45777. * @param {Texture} texture - The texture.
  45778. * @return {GLenum} The native texture type.
  45779. */
  45780. getGLTextureType( texture ) {
  45781. const { gl } = this;
  45782. let glTextureType;
  45783. if ( texture.isCubeTexture === true ) {
  45784. glTextureType = gl.TEXTURE_CUBE_MAP;
  45785. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  45786. glTextureType = gl.TEXTURE_2D_ARRAY;
  45787. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  45788. glTextureType = gl.TEXTURE_3D;
  45789. } else {
  45790. glTextureType = gl.TEXTURE_2D;
  45791. }
  45792. return glTextureType;
  45793. }
  45794. /**
  45795. * Returns the native texture type for the given texture.
  45796. *
  45797. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  45798. * @param {GLenum} glFormat - The WebGL format.
  45799. * @param {GLenum} glType - The WebGL type.
  45800. * @param {string} colorSpace - The texture's color space.
  45801. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  45802. * @return {GLenum} The internal format.
  45803. */
  45804. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  45805. const { gl, extensions } = this;
  45806. if ( internalFormatName !== null ) {
  45807. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  45808. warn( 'WebGLBackend: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  45809. }
  45810. let internalFormat = glFormat;
  45811. if ( glFormat === gl.RED ) {
  45812. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  45813. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  45814. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  45815. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  45816. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  45817. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  45818. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  45819. if ( glType === gl.INT ) internalFormat = gl.R32I;
  45820. }
  45821. if ( glFormat === gl.RED_INTEGER ) {
  45822. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  45823. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  45824. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  45825. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  45826. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  45827. if ( glType === gl.INT ) internalFormat = gl.R32I;
  45828. }
  45829. if ( glFormat === gl.RG ) {
  45830. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  45831. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  45832. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  45833. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  45834. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  45835. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  45836. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  45837. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  45838. }
  45839. if ( glFormat === gl.RG_INTEGER ) {
  45840. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  45841. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  45842. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  45843. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  45844. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  45845. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  45846. }
  45847. if ( glFormat === gl.RGB ) {
  45848. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  45849. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  45850. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  45851. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  45852. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  45853. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  45854. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  45855. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  45856. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  45857. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  45858. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  45859. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  45860. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  45861. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  45862. if ( glType === gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = gl.R11F_G11F_B10F;
  45863. }
  45864. if ( glFormat === gl.RGB_INTEGER ) {
  45865. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  45866. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  45867. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  45868. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  45869. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  45870. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  45871. }
  45872. if ( glFormat === gl.RGBA ) {
  45873. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  45874. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  45875. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  45876. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  45877. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  45878. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  45879. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  45880. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  45881. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  45882. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  45883. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  45884. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  45885. }
  45886. if ( glFormat === gl.RGBA_INTEGER ) {
  45887. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  45888. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  45889. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  45890. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  45891. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  45892. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  45893. }
  45894. if ( glFormat === gl.DEPTH_COMPONENT ) {
  45895. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  45896. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  45897. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  45898. }
  45899. if ( glFormat === gl.DEPTH_STENCIL ) {
  45900. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  45901. }
  45902. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  45903. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  45904. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  45905. extensions.get( 'EXT_color_buffer_float' );
  45906. }
  45907. return internalFormat;
  45908. }
  45909. /**
  45910. * Sets the texture parameters for the given texture.
  45911. *
  45912. * @param {GLenum} textureType - The texture type.
  45913. * @param {Texture} texture - The texture.
  45914. */
  45915. setTextureParameters( textureType, texture ) {
  45916. const { gl, extensions, backend } = this;
  45917. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  45918. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  45919. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  45920. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  45921. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  45922. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  45923. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  45924. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  45925. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  45926. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  45927. // WebGL 2 does not support wrapping for depth 2D array textures
  45928. if ( ! texture.isArrayTexture ) {
  45929. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  45930. }
  45931. }
  45932. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  45933. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  45934. // follow WebGPU backend mapping for texture filtering
  45935. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  45936. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  45937. if ( texture.compareFunction ) {
  45938. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  45939. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  45940. }
  45941. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  45942. if ( texture.magFilter === NearestFilter ) return;
  45943. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  45944. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  45945. if ( texture.anisotropy > 1 ) {
  45946. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  45947. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  45948. }
  45949. }
  45950. }
  45951. /**
  45952. * Creates a default texture for the given texture that can be used
  45953. * as a placeholder until the actual texture is ready for usage.
  45954. *
  45955. * @param {Texture} texture - The texture to create a default texture for.
  45956. */
  45957. createDefaultTexture( texture ) {
  45958. const { gl, backend, defaultTextures } = this;
  45959. const glTextureType = this.getGLTextureType( texture );
  45960. let textureGPU = defaultTextures[ glTextureType ];
  45961. if ( textureGPU === undefined ) {
  45962. textureGPU = gl.createTexture();
  45963. backend.state.bindTexture( glTextureType, textureGPU );
  45964. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  45965. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  45966. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  45967. defaultTextures[ glTextureType ] = textureGPU;
  45968. }
  45969. backend.set( texture, {
  45970. textureGPU,
  45971. glTextureType
  45972. } );
  45973. }
  45974. /**
  45975. * Defines a texture on the GPU for the given texture object.
  45976. *
  45977. * @param {Texture} texture - The texture.
  45978. * @param {Object} [options={}] - Optional configuration parameter.
  45979. * @return {undefined}
  45980. */
  45981. createTexture( texture, options ) {
  45982. const { gl, backend } = this;
  45983. const { levels, width, height, depth } = options;
  45984. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  45985. const glType = backend.utils.convert( texture.type );
  45986. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  45987. const textureGPU = gl.createTexture();
  45988. const glTextureType = this.getGLTextureType( texture );
  45989. backend.state.bindTexture( glTextureType, textureGPU );
  45990. this.setTextureParameters( glTextureType, texture );
  45991. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  45992. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  45993. } else if ( texture.isData3DTexture ) {
  45994. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  45995. } else if ( ! texture.isVideoTexture ) {
  45996. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  45997. }
  45998. backend.set( texture, {
  45999. textureGPU,
  46000. glTextureType,
  46001. glFormat,
  46002. glType,
  46003. glInternalFormat
  46004. } );
  46005. }
  46006. /**
  46007. * Uploads texture buffer data to the GPU memory.
  46008. *
  46009. * @param {WebGLBuffer} buffer - The buffer data.
  46010. * @param {Texture} texture - The texture,
  46011. */
  46012. copyBufferToTexture( buffer, texture ) {
  46013. const { gl, backend } = this;
  46014. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  46015. const { width, height } = texture.source.data;
  46016. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  46017. backend.state.bindTexture( glTextureType, textureGPU );
  46018. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  46019. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  46020. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  46021. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  46022. backend.state.unbindTexture();
  46023. // debug
  46024. // const framebuffer = gl.createFramebuffer();
  46025. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  46026. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  46027. // const readout = new Float32Array( width * height * 4 );
  46028. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  46029. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  46030. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  46031. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  46032. // log( readout );
  46033. }
  46034. /**
  46035. * Uploads the updated texture data to the GPU.
  46036. *
  46037. * @param {Texture} texture - The texture.
  46038. * @param {Object} [options={}] - Optional configuration parameter.
  46039. */
  46040. updateTexture( texture, options ) {
  46041. const { gl } = this;
  46042. const { width, height } = options;
  46043. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  46044. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  46045. return;
  46046. this.backend.state.bindTexture( glTextureType, textureGPU );
  46047. this.setTextureParameters( glTextureType, texture );
  46048. if ( texture.isCompressedTexture ) {
  46049. const mipmaps = texture.mipmaps;
  46050. const image = options.image;
  46051. for ( let i = 0; i < mipmaps.length; i ++ ) {
  46052. const mipmap = mipmaps[ i ];
  46053. if ( texture.isCompressedArrayTexture ) {
  46054. if ( texture.format !== gl.RGBA ) {
  46055. if ( glFormat !== null ) {
  46056. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  46057. } else {
  46058. warn( 'WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  46059. }
  46060. } else {
  46061. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  46062. }
  46063. } else {
  46064. if ( glFormat !== null ) {
  46065. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  46066. } else {
  46067. warn( 'WebGLBackend: Unsupported compressed texture format' );
  46068. }
  46069. }
  46070. }
  46071. } else if ( texture.isCubeTexture ) {
  46072. const images = options.images;
  46073. const mipmaps = texture.mipmaps;
  46074. for ( let i = 0; i < 6; i ++ ) {
  46075. const image = getImage( images[ i ] );
  46076. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  46077. for ( let j = 0; j < mipmaps.length; j ++ ) {
  46078. const mipmap = mipmaps[ j ];
  46079. const image = getImage( mipmap.images[ i ] );
  46080. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, image.width, image.height, glFormat, glType, image );
  46081. }
  46082. }
  46083. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  46084. const image = options.image;
  46085. if ( texture.layerUpdates.size > 0 ) {
  46086. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  46087. for ( const layerIndex of texture.layerUpdates ) {
  46088. const layerData = image.data.subarray(
  46089. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  46090. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  46091. );
  46092. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  46093. }
  46094. texture.clearLayerUpdates();
  46095. } else {
  46096. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  46097. }
  46098. } else if ( texture.isData3DTexture ) {
  46099. const image = options.image;
  46100. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  46101. } else if ( texture.isVideoTexture ) {
  46102. texture.update();
  46103. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  46104. } else {
  46105. const mipmaps = texture.mipmaps;
  46106. if ( mipmaps.length > 0 ) {
  46107. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  46108. const mipmap = mipmaps[ i ];
  46109. const image = getImage( mipmap );
  46110. gl.texSubImage2D( glTextureType, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, image );
  46111. }
  46112. } else {
  46113. const image = getImage( options.image );
  46114. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  46115. }
  46116. }
  46117. }
  46118. /**
  46119. * Generates mipmaps for the given texture.
  46120. *
  46121. * @param {Texture} texture - The texture.
  46122. */
  46123. generateMipmaps( texture ) {
  46124. const { gl, backend } = this;
  46125. const { textureGPU, glTextureType } = backend.get( texture );
  46126. backend.state.bindTexture( glTextureType, textureGPU );
  46127. gl.generateMipmap( glTextureType );
  46128. }
  46129. /**
  46130. * Deallocates the render buffers of the given render target.
  46131. *
  46132. * @param {RenderTarget} renderTarget - The render target.
  46133. */
  46134. deallocateRenderBuffers( renderTarget ) {
  46135. const { gl, backend } = this;
  46136. // remove framebuffer reference
  46137. if ( renderTarget ) {
  46138. const renderContextData = backend.get( renderTarget );
  46139. renderContextData.renderBufferStorageSetup = undefined;
  46140. if ( renderContextData.framebuffers ) {
  46141. for ( const cacheKey in renderContextData.framebuffers ) {
  46142. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  46143. }
  46144. delete renderContextData.framebuffers;
  46145. }
  46146. if ( renderContextData.depthRenderbuffer ) {
  46147. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  46148. delete renderContextData.depthRenderbuffer;
  46149. }
  46150. if ( renderContextData.stencilRenderbuffer ) {
  46151. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  46152. delete renderContextData.stencilRenderbuffer;
  46153. }
  46154. if ( renderContextData.msaaFrameBuffer ) {
  46155. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  46156. delete renderContextData.msaaFrameBuffer;
  46157. }
  46158. if ( renderContextData.msaaRenderbuffers ) {
  46159. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  46160. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  46161. }
  46162. delete renderContextData.msaaRenderbuffers;
  46163. }
  46164. }
  46165. }
  46166. /**
  46167. * Destroys the GPU data for the given texture object.
  46168. *
  46169. * @param {Texture} texture - The texture.
  46170. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  46171. */
  46172. destroyTexture( texture, isDefaultTexture = false ) {
  46173. const { gl, backend } = this;
  46174. const { textureGPU, renderTarget } = backend.get( texture );
  46175. this.deallocateRenderBuffers( renderTarget );
  46176. if ( isDefaultTexture === false ) {
  46177. gl.deleteTexture( textureGPU );
  46178. }
  46179. backend.delete( texture );
  46180. }
  46181. /**
  46182. * Copies data of the given source texture to the given destination texture.
  46183. *
  46184. * @param {Texture} srcTexture - The source texture.
  46185. * @param {Texture} dstTexture - The destination texture.
  46186. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  46187. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  46188. * @param {number} [srcLevel=0] - The source mip level to copy from.
  46189. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  46190. */
  46191. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  46192. const { gl, backend } = this;
  46193. const { state } = this.backend;
  46194. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  46195. state.bindTexture( glTextureType, dstTextureGPU );
  46196. // gather the necessary dimensions to copy
  46197. let width, height, depth, minX, minY, minZ;
  46198. let dstX, dstY, dstZ;
  46199. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  46200. if ( srcRegion !== null ) {
  46201. width = srcRegion.max.x - srcRegion.min.x;
  46202. height = srcRegion.max.y - srcRegion.min.y;
  46203. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  46204. minX = srcRegion.min.x;
  46205. minY = srcRegion.min.y;
  46206. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  46207. } else {
  46208. const levelScale = Math.pow( 2, - srcLevel );
  46209. width = Math.floor( image.width * levelScale );
  46210. height = Math.floor( image.height * levelScale );
  46211. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  46212. depth = image.depth;
  46213. } else if ( srcTexture.isData3DTexture ) {
  46214. depth = Math.floor( image.depth * levelScale );
  46215. } else {
  46216. depth = 1;
  46217. }
  46218. minX = 0;
  46219. minY = 0;
  46220. minZ = 0;
  46221. }
  46222. if ( dstPosition !== null ) {
  46223. dstX = dstPosition.x;
  46224. dstY = dstPosition.y;
  46225. dstZ = dstPosition.z;
  46226. } else {
  46227. dstX = 0;
  46228. dstY = 0;
  46229. dstZ = 0;
  46230. }
  46231. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  46232. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  46233. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  46234. // used for copying data from cpu
  46235. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  46236. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  46237. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  46238. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  46239. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  46240. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  46241. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  46242. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  46243. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  46244. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  46245. // set up the src texture
  46246. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture || dstTexture.isArrayTexture;
  46247. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  46248. if ( srcTexture.isDepthTexture ) {
  46249. const srcTextureData = backend.get( srcTexture );
  46250. const dstTextureData = backend.get( dstTexture );
  46251. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  46252. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  46253. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  46254. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  46255. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  46256. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  46257. for ( let i = 0; i < depth; i ++ ) {
  46258. // if the source or destination are a 3d target then a layer needs to be bound
  46259. if ( isSrc3D ) {
  46260. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  46261. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  46262. }
  46263. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST );
  46264. }
  46265. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  46266. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  46267. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || backend.has( srcTexture ) ) {
  46268. // get the appropriate frame buffers
  46269. const srcTextureData = backend.get( srcTexture );
  46270. if ( this._srcFramebuffer === null ) this._srcFramebuffer = gl.createFramebuffer();
  46271. if ( this._dstFramebuffer === null ) this._dstFramebuffer = gl.createFramebuffer();
  46272. // bind the frame buffer targets
  46273. state.bindFramebuffer( gl.READ_FRAMEBUFFER, this._srcFramebuffer );
  46274. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, this._dstFramebuffer );
  46275. for ( let i = 0; i < depth; i ++ ) {
  46276. // assign the correct layers and mip maps to the frame buffers
  46277. if ( isSrc3D ) {
  46278. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  46279. } else {
  46280. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, srcTextureData.textureGPU, srcLevel );
  46281. }
  46282. if ( isDst3D ) {
  46283. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  46284. } else {
  46285. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dstTextureGPU, dstLevel );
  46286. }
  46287. // copy the data using the fastest function that can achieve the copy
  46288. if ( srcLevel !== 0 ) {
  46289. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST );
  46290. } else if ( isDst3D ) {
  46291. gl.copyTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  46292. } else {
  46293. gl.copyTexSubImage2D( glTextureType, dstLevel, dstX, dstY, minX, minY, width, height );
  46294. }
  46295. }
  46296. // unbind read, draw buffers
  46297. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  46298. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  46299. } else {
  46300. if ( isDst3D ) {
  46301. // copy data into the 3d texture
  46302. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  46303. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  46304. } else if ( dstTexture.isCompressedArrayTexture ) {
  46305. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  46306. } else {
  46307. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  46308. }
  46309. } else {
  46310. // copy data into the 2d texture
  46311. if ( srcTexture.isDataTexture ) {
  46312. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  46313. } else if ( srcTexture.isCompressedTexture ) {
  46314. gl.compressedTexSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  46315. } else {
  46316. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  46317. }
  46318. }
  46319. }
  46320. // reset values
  46321. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  46322. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  46323. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  46324. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  46325. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  46326. // Generate mipmaps only when copying level 0
  46327. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  46328. gl.generateMipmap( glTextureType );
  46329. }
  46330. state.unbindTexture();
  46331. }
  46332. /**
  46333. * Copies the current bound framebuffer to the given texture.
  46334. *
  46335. * @param {Texture} texture - The destination texture.
  46336. * @param {RenderContext} renderContext - The render context.
  46337. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  46338. */
  46339. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  46340. const { gl } = this;
  46341. const { state } = this.backend;
  46342. const { textureGPU } = this.backend.get( texture );
  46343. const { x, y, z: width, w: height } = rectangle;
  46344. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  46345. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  46346. if ( requireDrawFrameBuffer ) {
  46347. const partial = ( x !== 0 || y !== 0 );
  46348. let mask;
  46349. let attachment;
  46350. if ( texture.isDepthTexture === true ) {
  46351. mask = gl.DEPTH_BUFFER_BIT;
  46352. attachment = gl.DEPTH_ATTACHMENT;
  46353. if ( renderContext.stencil ) {
  46354. mask |= gl.STENCIL_BUFFER_BIT;
  46355. }
  46356. } else {
  46357. mask = gl.COLOR_BUFFER_BIT;
  46358. attachment = gl.COLOR_ATTACHMENT0;
  46359. }
  46360. if ( partial ) {
  46361. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  46362. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  46363. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  46364. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  46365. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  46366. const flippedY = srcHeight - y - height;
  46367. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  46368. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  46369. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  46370. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  46371. state.unbindTexture();
  46372. } else {
  46373. const fb = gl.createFramebuffer();
  46374. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  46375. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  46376. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  46377. gl.deleteFramebuffer( fb );
  46378. }
  46379. } else {
  46380. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  46381. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  46382. state.unbindTexture();
  46383. }
  46384. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  46385. this.backend._setFramebuffer( renderContext );
  46386. }
  46387. /**
  46388. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  46389. *
  46390. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  46391. * @param {RenderContext} renderContext - The render context.
  46392. * @param {number} samples - The MSAA sample count.
  46393. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  46394. */
  46395. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  46396. const { gl } = this;
  46397. const renderTarget = renderContext.renderTarget;
  46398. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  46399. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  46400. if ( depthBuffer && ! stencilBuffer ) {
  46401. let glInternalFormat = gl.DEPTH_COMPONENT24;
  46402. if ( useMultisampledRTT === true ) {
  46403. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  46404. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  46405. } else if ( samples > 0 ) {
  46406. if ( depthTexture && depthTexture.isDepthTexture ) {
  46407. if ( depthTexture.type === gl.FLOAT ) {
  46408. glInternalFormat = gl.DEPTH_COMPONENT32F;
  46409. }
  46410. }
  46411. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  46412. } else {
  46413. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  46414. }
  46415. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  46416. } else if ( depthBuffer && stencilBuffer ) {
  46417. if ( samples > 0 ) {
  46418. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  46419. } else {
  46420. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  46421. }
  46422. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  46423. }
  46424. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  46425. }
  46426. /**
  46427. * Returns texture data as a typed array.
  46428. *
  46429. * @async
  46430. * @param {Texture} texture - The texture to copy.
  46431. * @param {number} x - The x coordinate of the copy origin.
  46432. * @param {number} y - The y coordinate of the copy origin.
  46433. * @param {number} width - The width of the copy.
  46434. * @param {number} height - The height of the copy.
  46435. * @param {number} faceIndex - The face index.
  46436. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  46437. */
  46438. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  46439. const { backend, gl } = this;
  46440. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  46441. const fb = gl.createFramebuffer();
  46442. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  46443. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  46444. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  46445. const typedArrayType = this._getTypedArrayType( glType );
  46446. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  46447. const elementCount = width * height;
  46448. const byteLength = elementCount * bytesPerTexel;
  46449. const buffer = gl.createBuffer();
  46450. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  46451. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  46452. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  46453. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  46454. await backend.utils._clientWaitAsync();
  46455. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  46456. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  46457. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  46458. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  46459. gl.deleteFramebuffer( fb );
  46460. return dstBuffer;
  46461. }
  46462. /**
  46463. * Returns the corresponding typed array type for the given WebGL data type.
  46464. *
  46465. * @private
  46466. * @param {GLenum} glType - The WebGL data type.
  46467. * @return {TypedArray.constructor} The typed array type.
  46468. */
  46469. _getTypedArrayType( glType ) {
  46470. const { gl } = this;
  46471. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  46472. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  46473. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  46474. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  46475. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  46476. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  46477. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  46478. if ( glType === gl.FLOAT ) return Float32Array;
  46479. throw new Error( `Unsupported WebGL type: ${glType}` );
  46480. }
  46481. /**
  46482. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  46483. *
  46484. * @private
  46485. * @param {GLenum} glType - The WebGL data type.
  46486. * @param {GLenum} glFormat - The WebGL texture format.
  46487. * @return {number} The bytes-per-texel.
  46488. */
  46489. _getBytesPerTexel( glType, glFormat ) {
  46490. const { gl } = this;
  46491. let bytesPerComponent = 0;
  46492. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  46493. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  46494. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  46495. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  46496. glType === gl.UNSIGNED_SHORT ||
  46497. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  46498. if ( glType === gl.UNSIGNED_INT ||
  46499. glType === gl.FLOAT ) bytesPerComponent = 4;
  46500. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  46501. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  46502. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  46503. }
  46504. /**
  46505. * Frees the internal resources.
  46506. */
  46507. dispose() {
  46508. const { gl } = this;
  46509. if ( this._srcFramebuffer !== null ) gl.deleteFramebuffer( this._srcFramebuffer );
  46510. if ( this._dstFramebuffer !== null ) gl.deleteFramebuffer( this._dstFramebuffer );
  46511. }
  46512. }
  46513. function getImage( source ) {
  46514. if ( source.isDataTexture ) {
  46515. return source.image.data;
  46516. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  46517. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  46518. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  46519. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  46520. return source;
  46521. }
  46522. return source.data;
  46523. }
  46524. /**
  46525. * A WebGL 2 backend utility module for managing extensions.
  46526. *
  46527. * @private
  46528. */
  46529. class WebGLExtensions {
  46530. /**
  46531. * Constructs a new utility object.
  46532. *
  46533. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46534. */
  46535. constructor( backend ) {
  46536. /**
  46537. * A reference to the WebGL 2 backend.
  46538. *
  46539. * @type {WebGLBackend}
  46540. */
  46541. this.backend = backend;
  46542. /**
  46543. * A reference to the rendering context.
  46544. *
  46545. * @type {WebGL2RenderingContext}
  46546. */
  46547. this.gl = this.backend.gl;
  46548. /**
  46549. * A list with all the supported WebGL extensions.
  46550. *
  46551. * @type {Array<string>}
  46552. */
  46553. this.availableExtensions = this.gl.getSupportedExtensions();
  46554. /**
  46555. * A dictionary with requested WebGL extensions.
  46556. * The key is the name of the extension, the value
  46557. * the requested extension object.
  46558. *
  46559. * @type {Object<string,Object>}
  46560. */
  46561. this.extensions = {};
  46562. }
  46563. /**
  46564. * Returns the extension object for the given extension name.
  46565. *
  46566. * @param {string} name - The extension name.
  46567. * @return {Object} The extension object.
  46568. */
  46569. get( name ) {
  46570. let extension = this.extensions[ name ];
  46571. if ( extension === undefined ) {
  46572. extension = this.gl.getExtension( name );
  46573. this.extensions[ name ] = extension;
  46574. }
  46575. return extension;
  46576. }
  46577. /**
  46578. * Returns `true` if the requested extension is available.
  46579. *
  46580. * @param {string} name - The extension name.
  46581. * @return {boolean} Whether the given extension is available or not.
  46582. */
  46583. has( name ) {
  46584. return this.availableExtensions.includes( name );
  46585. }
  46586. }
  46587. /**
  46588. * A WebGL 2 backend utility module for managing the device's capabilities.
  46589. *
  46590. * @private
  46591. */
  46592. class WebGLCapabilities {
  46593. /**
  46594. * Constructs a new utility object.
  46595. *
  46596. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46597. */
  46598. constructor( backend ) {
  46599. /**
  46600. * A reference to the WebGL 2 backend.
  46601. *
  46602. * @type {WebGLBackend}
  46603. */
  46604. this.backend = backend;
  46605. /**
  46606. * This value holds the cached max anisotropy value.
  46607. *
  46608. * @type {?number}
  46609. * @default null
  46610. */
  46611. this.maxAnisotropy = null;
  46612. }
  46613. /**
  46614. * Returns the maximum anisotropy texture filtering value. This value
  46615. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  46616. * WebGL extension.
  46617. *
  46618. * @return {number} The maximum anisotropy texture filtering value.
  46619. */
  46620. getMaxAnisotropy() {
  46621. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  46622. const gl = this.backend.gl;
  46623. const extensions = this.backend.extensions;
  46624. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  46625. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  46626. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  46627. } else {
  46628. this.maxAnisotropy = 0;
  46629. }
  46630. return this.maxAnisotropy;
  46631. }
  46632. }
  46633. const GLFeatureName = {
  46634. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  46635. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  46636. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  46637. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  46638. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  46639. 'WEBGL_compressed_texture_s3tc': 'texture-compression-s3tc',
  46640. 'EXT_texture_compression_bptc': 'texture-compression-bc',
  46641. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  46642. 'OVR_multiview2': 'OVR_multiview2'
  46643. };
  46644. class WebGLBufferRenderer {
  46645. constructor( backend ) {
  46646. this.gl = backend.gl;
  46647. this.extensions = backend.extensions;
  46648. this.info = backend.renderer.info;
  46649. this.mode = null;
  46650. this.index = 0;
  46651. this.type = null;
  46652. this.object = null;
  46653. }
  46654. render( start, count ) {
  46655. const { gl, mode, object, type, info, index } = this;
  46656. if ( index !== 0 ) {
  46657. gl.drawElements( mode, count, type, start );
  46658. } else {
  46659. gl.drawArrays( mode, start, count );
  46660. }
  46661. info.update( object, count, 1 );
  46662. }
  46663. renderInstances( start, count, primcount ) {
  46664. const { gl, mode, type, index, object, info } = this;
  46665. if ( primcount === 0 ) return;
  46666. if ( index !== 0 ) {
  46667. gl.drawElementsInstanced( mode, count, type, start, primcount );
  46668. } else {
  46669. gl.drawArraysInstanced( mode, start, count, primcount );
  46670. }
  46671. info.update( object, count, primcount );
  46672. }
  46673. renderMultiDraw( starts, counts, drawCount ) {
  46674. const { extensions, mode, object, info } = this;
  46675. if ( drawCount === 0 ) return;
  46676. const extension = extensions.get( 'WEBGL_multi_draw' );
  46677. if ( extension === null ) {
  46678. for ( let i = 0; i < drawCount; i ++ ) {
  46679. this.render( starts[ i ], counts[ i ] );
  46680. }
  46681. } else {
  46682. if ( this.index !== 0 ) {
  46683. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  46684. } else {
  46685. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  46686. }
  46687. let elementCount = 0;
  46688. for ( let i = 0; i < drawCount; i ++ ) {
  46689. elementCount += counts[ i ];
  46690. }
  46691. info.update( object, elementCount, 1 );
  46692. }
  46693. }
  46694. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  46695. const { extensions, mode, object, info } = this;
  46696. if ( drawCount === 0 ) return;
  46697. const extension = extensions.get( 'WEBGL_multi_draw' );
  46698. if ( extension === null ) {
  46699. for ( let i = 0; i < drawCount; i ++ ) {
  46700. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  46701. }
  46702. } else {
  46703. if ( this.index !== 0 ) {
  46704. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  46705. } else {
  46706. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  46707. }
  46708. let elementCount = 0;
  46709. for ( let i = 0; i < drawCount; i ++ ) {
  46710. elementCount += counts[ i ] * primcount[ i ];
  46711. }
  46712. info.update( object, elementCount, 1 );
  46713. }
  46714. }
  46715. //
  46716. }
  46717. /**
  46718. * Abstract base class of a timestamp query pool.
  46719. *
  46720. * @abstract
  46721. */
  46722. class TimestampQueryPool {
  46723. /**
  46724. * Creates a new timestamp query pool.
  46725. *
  46726. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  46727. */
  46728. constructor( maxQueries = 256 ) {
  46729. /**
  46730. * Whether to track timestamps or not.
  46731. *
  46732. * @type {boolean}
  46733. * @default true
  46734. */
  46735. this.trackTimestamp = true;
  46736. /**
  46737. * Maximum number of queries this pool can hold.
  46738. *
  46739. * @type {number}
  46740. * @default 256
  46741. */
  46742. this.maxQueries = maxQueries;
  46743. /**
  46744. * How many queries allocated so far.
  46745. *
  46746. * @type {number}
  46747. * @default 0
  46748. */
  46749. this.currentQueryIndex = 0;
  46750. /**
  46751. * Tracks offsets for different contexts.
  46752. *
  46753. * @type {Map<string, number>}
  46754. */
  46755. this.queryOffsets = new Map();
  46756. /**
  46757. * Whether the pool has been disposed or not.
  46758. *
  46759. * @type {boolean}
  46760. * @default false
  46761. */
  46762. this.isDisposed = false;
  46763. /**
  46764. * TODO
  46765. *
  46766. * @type {number}
  46767. * @default 0
  46768. */
  46769. this.lastValue = 0;
  46770. /**
  46771. * Stores all timestamp frames.
  46772. *
  46773. * @type {Array<number>}
  46774. */
  46775. this.frames = [];
  46776. /**
  46777. * TODO
  46778. *
  46779. * @type {boolean}
  46780. * @default false
  46781. */
  46782. this.pendingResolve = false;
  46783. /**
  46784. * Stores the latest timestamp for each render context.
  46785. *
  46786. * @type {Map<string, number>}
  46787. */
  46788. this.timestamps = new Map();
  46789. }
  46790. /**
  46791. * Returns all timestamp frames.
  46792. *
  46793. * @return {Array<number>} The timestamp frames.
  46794. */
  46795. getTimestampFrames() {
  46796. return this.frames;
  46797. }
  46798. /**
  46799. * Returns the timestamp for a given render context.
  46800. *
  46801. * @param {string} uid - A unique identifier for the render context.
  46802. * @return {?number} The timestamp, or undefined if not available.
  46803. */
  46804. getTimestamp( uid ) {
  46805. let timestamp = this.timestamps.get( uid );
  46806. if ( timestamp === undefined ) {
  46807. warn( `TimestampQueryPool: No timestamp available for uid ${ uid }.` );
  46808. timestamp = 0;
  46809. }
  46810. return timestamp;
  46811. }
  46812. /**
  46813. * Returns whether a timestamp is available for a given render context.
  46814. *
  46815. * @param {string} uid - A unique identifier for the render context.
  46816. * @return {boolean} True if a timestamp is available, false otherwise.
  46817. */
  46818. hasTimestamp( uid ) {
  46819. return this.timestamps.has( uid );
  46820. }
  46821. /**
  46822. * Allocate queries for a specific uid.
  46823. *
  46824. * @abstract
  46825. * @param {string} uid - A unique identifier for the render context.
  46826. * @param {number} frameId - The current frame identifier.
  46827. * @returns {?number}
  46828. */
  46829. allocateQueriesForContext( /* uid, frameId */ ) {}
  46830. /**
  46831. * Resolve all timestamps and return data (or process them).
  46832. *
  46833. * @abstract
  46834. * @async
  46835. * @returns {Promise<number>|number} The resolved timestamp value.
  46836. */
  46837. async resolveQueriesAsync() {}
  46838. /**
  46839. * Dispose of the query pool.
  46840. *
  46841. * @abstract
  46842. */
  46843. dispose() {}
  46844. }
  46845. /**
  46846. * Manages a pool of WebGL timestamp queries for performance measurement.
  46847. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  46848. *
  46849. * @augments TimestampQueryPool
  46850. */
  46851. class WebGLTimestampQueryPool extends TimestampQueryPool {
  46852. /**
  46853. * Creates a new WebGL timestamp query pool.
  46854. *
  46855. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  46856. * @param {string} type - The type identifier for this query pool.
  46857. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  46858. */
  46859. constructor( gl, type, maxQueries = 2048 ) {
  46860. super( maxQueries );
  46861. this.gl = gl;
  46862. this.type = type;
  46863. // Check for timer query extensions
  46864. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  46865. gl.getExtension( 'EXT_disjoint_timer_query' );
  46866. if ( ! this.ext ) {
  46867. warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  46868. this.trackTimestamp = false;
  46869. return;
  46870. }
  46871. // Create query objects
  46872. this.queries = [];
  46873. for ( let i = 0; i < this.maxQueries; i ++ ) {
  46874. this.queries.push( gl.createQuery() );
  46875. }
  46876. this.activeQuery = null;
  46877. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  46878. }
  46879. /**
  46880. * Allocates a pair of queries for a given render context.
  46881. *
  46882. * @param {string} uid - A unique identifier for the render context.
  46883. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  46884. */
  46885. allocateQueriesForContext( uid ) {
  46886. if ( ! this.trackTimestamp ) return null;
  46887. // Check if we have enough space for a new query pair
  46888. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  46889. 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() } ).` );
  46890. return null;
  46891. }
  46892. const baseOffset = this.currentQueryIndex;
  46893. this.currentQueryIndex += 2;
  46894. // Initialize query states
  46895. this.queryStates.set( baseOffset, 'inactive' );
  46896. this.queryOffsets.set( uid, baseOffset );
  46897. return baseOffset;
  46898. }
  46899. /**
  46900. * Begins a timestamp query for the specified render context.
  46901. *
  46902. * @param {string} uid - A unique identifier for the render context.
  46903. */
  46904. beginQuery( uid ) {
  46905. if ( ! this.trackTimestamp || this.isDisposed ) {
  46906. return;
  46907. }
  46908. const baseOffset = this.queryOffsets.get( uid );
  46909. if ( baseOffset == null ) {
  46910. return;
  46911. }
  46912. // Don't start a new query if there's an active one
  46913. if ( this.activeQuery !== null ) {
  46914. return;
  46915. }
  46916. const query = this.queries[ baseOffset ];
  46917. if ( ! query ) {
  46918. return;
  46919. }
  46920. try {
  46921. // Only begin if query is inactive
  46922. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  46923. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  46924. this.activeQuery = baseOffset;
  46925. this.queryStates.set( baseOffset, 'started' );
  46926. }
  46927. } catch ( error ) {
  46928. error( 'Error in beginQuery:', error );
  46929. this.activeQuery = null;
  46930. this.queryStates.set( baseOffset, 'inactive' );
  46931. }
  46932. }
  46933. /**
  46934. * Ends the active timestamp query for the specified render context.
  46935. *
  46936. * @param {string} uid - A unique identifier for the render context.
  46937. */
  46938. endQuery( uid ) {
  46939. if ( ! this.trackTimestamp || this.isDisposed ) {
  46940. return;
  46941. }
  46942. const baseOffset = this.queryOffsets.get( uid );
  46943. if ( baseOffset == null ) {
  46944. return;
  46945. }
  46946. // Only end if this is the active query
  46947. if ( this.activeQuery !== baseOffset ) {
  46948. return;
  46949. }
  46950. try {
  46951. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  46952. this.queryStates.set( baseOffset, 'ended' );
  46953. this.activeQuery = null;
  46954. } catch ( error ) {
  46955. error( 'Error in endQuery:', error );
  46956. // Reset state on error
  46957. this.queryStates.set( baseOffset, 'inactive' );
  46958. this.activeQuery = null;
  46959. }
  46960. }
  46961. /**
  46962. * Asynchronously resolves all completed queries and returns the total duration.
  46963. *
  46964. * @async
  46965. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  46966. */
  46967. async resolveQueriesAsync() {
  46968. if ( ! this.trackTimestamp || this.pendingResolve ) {
  46969. return this.lastValue;
  46970. }
  46971. this.pendingResolve = true;
  46972. try {
  46973. // Wait for all ended queries to complete
  46974. const resolvePromises = new Map();
  46975. for ( const [ uid, baseOffset ] of this.queryOffsets ) {
  46976. const state = this.queryStates.get( baseOffset );
  46977. if ( state === 'ended' ) {
  46978. const query = this.queries[ baseOffset ];
  46979. resolvePromises.set( uid, this.resolveQuery( query ) );
  46980. }
  46981. }
  46982. if ( resolvePromises.size === 0 ) {
  46983. return this.lastValue;
  46984. }
  46985. //
  46986. const framesDuration = {};
  46987. const frames = [];
  46988. for ( const [ uid, promise ] of resolvePromises ) {
  46989. const match = uid.match( /^(.*):f(\d+)$/ );
  46990. const frame = parseInt( match[ 2 ] );
  46991. if ( frames.includes( frame ) === false ) {
  46992. frames.push( frame );
  46993. }
  46994. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  46995. const duration = await promise;
  46996. this.timestamps.set( uid, duration );
  46997. framesDuration[ frame ] += duration;
  46998. }
  46999. // Return the total duration of the last frame
  47000. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  47001. // Store the last valid result
  47002. this.lastValue = totalDuration;
  47003. this.frames = frames;
  47004. // Reset states
  47005. this.currentQueryIndex = 0;
  47006. this.queryOffsets.clear();
  47007. this.queryStates.clear();
  47008. this.activeQuery = null;
  47009. return totalDuration;
  47010. } catch ( error ) {
  47011. error( 'Error resolving queries:', error );
  47012. return this.lastValue;
  47013. } finally {
  47014. this.pendingResolve = false;
  47015. }
  47016. }
  47017. /**
  47018. * Resolves a single query, checking for completion and disjoint operation.
  47019. *
  47020. * @async
  47021. * @param {WebGLQuery} query - The query object to resolve.
  47022. * @returns {Promise<number>} The elapsed time in milliseconds.
  47023. */
  47024. async resolveQuery( query ) {
  47025. return new Promise( ( resolve ) => {
  47026. if ( this.isDisposed ) {
  47027. resolve( this.lastValue );
  47028. return;
  47029. }
  47030. let timeoutId;
  47031. let isResolved = false;
  47032. const cleanup = () => {
  47033. if ( timeoutId ) {
  47034. clearTimeout( timeoutId );
  47035. timeoutId = null;
  47036. }
  47037. };
  47038. const finalizeResolution = ( value ) => {
  47039. if ( ! isResolved ) {
  47040. isResolved = true;
  47041. cleanup();
  47042. resolve( value );
  47043. }
  47044. };
  47045. const checkQuery = () => {
  47046. if ( this.isDisposed ) {
  47047. finalizeResolution( this.lastValue );
  47048. return;
  47049. }
  47050. try {
  47051. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  47052. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  47053. if ( disjoint ) {
  47054. finalizeResolution( this.lastValue );
  47055. return;
  47056. }
  47057. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  47058. if ( ! available ) {
  47059. timeoutId = setTimeout( checkQuery, 1 );
  47060. return;
  47061. }
  47062. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  47063. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  47064. } catch ( error ) {
  47065. error( 'Error checking query:', error );
  47066. resolve( this.lastValue );
  47067. }
  47068. };
  47069. checkQuery();
  47070. } );
  47071. }
  47072. /**
  47073. * Releases all resources held by this query pool.
  47074. * This includes deleting all query objects and clearing internal state.
  47075. */
  47076. dispose() {
  47077. if ( this.isDisposed ) {
  47078. return;
  47079. }
  47080. this.isDisposed = true;
  47081. if ( ! this.trackTimestamp ) return;
  47082. for ( const query of this.queries ) {
  47083. this.gl.deleteQuery( query );
  47084. }
  47085. this.queries = [];
  47086. this.queryStates.clear();
  47087. this.queryOffsets.clear();
  47088. this.lastValue = 0;
  47089. this.activeQuery = null;
  47090. }
  47091. }
  47092. /**
  47093. * A backend implementation targeting WebGL 2.
  47094. *
  47095. * @private
  47096. * @augments Backend
  47097. */
  47098. class WebGLBackend extends Backend {
  47099. /**
  47100. * WebGLBackend options.
  47101. *
  47102. * @typedef {Object} WebGLBackend~Options
  47103. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  47104. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  47105. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  47106. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  47107. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  47108. * @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.
  47109. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  47110. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  47111. */
  47112. /**
  47113. * Constructs a new WebGPU backend.
  47114. *
  47115. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  47116. */
  47117. constructor( parameters = {} ) {
  47118. super( parameters );
  47119. /**
  47120. * This flag can be used for type testing.
  47121. *
  47122. * @type {boolean}
  47123. * @readonly
  47124. * @default true
  47125. */
  47126. this.isWebGLBackend = true;
  47127. /**
  47128. * A reference to a backend module holding shader attribute-related
  47129. * utility functions.
  47130. *
  47131. * @type {?WebGLAttributeUtils}
  47132. * @default null
  47133. */
  47134. this.attributeUtils = null;
  47135. /**
  47136. * A reference to a backend module holding extension-related
  47137. * utility functions.
  47138. *
  47139. * @type {?WebGLExtensions}
  47140. * @default null
  47141. */
  47142. this.extensions = null;
  47143. /**
  47144. * A reference to a backend module holding capability-related
  47145. * utility functions.
  47146. *
  47147. * @type {?WebGLCapabilities}
  47148. * @default null
  47149. */
  47150. this.capabilities = null;
  47151. /**
  47152. * A reference to a backend module holding texture-related
  47153. * utility functions.
  47154. *
  47155. * @type {?WebGLTextureUtils}
  47156. * @default null
  47157. */
  47158. this.textureUtils = null;
  47159. /**
  47160. * A reference to a backend module holding renderer-related
  47161. * utility functions.
  47162. *
  47163. * @type {?WebGLBufferRenderer}
  47164. * @default null
  47165. */
  47166. this.bufferRenderer = null;
  47167. /**
  47168. * A reference to the rendering context.
  47169. *
  47170. * @type {?WebGL2RenderingContext}
  47171. * @default null
  47172. */
  47173. this.gl = null;
  47174. /**
  47175. * A reference to a backend module holding state-related
  47176. * utility functions.
  47177. *
  47178. * @type {?WebGLState}
  47179. * @default null
  47180. */
  47181. this.state = null;
  47182. /**
  47183. * A reference to a backend module holding common
  47184. * utility functions.
  47185. *
  47186. * @type {?WebGLUtils}
  47187. * @default null
  47188. */
  47189. this.utils = null;
  47190. /**
  47191. * Dictionary for caching VAOs.
  47192. *
  47193. * @type {Object<string,WebGLVertexArrayObject>}
  47194. */
  47195. this.vaoCache = {};
  47196. /**
  47197. * Dictionary for caching transform feedback objects.
  47198. *
  47199. * @type {Object<string,WebGLTransformFeedback>}
  47200. */
  47201. this.transformFeedbackCache = {};
  47202. /**
  47203. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  47204. * Only relevant when using compute shaders.
  47205. *
  47206. * @type {boolean}
  47207. * @default false
  47208. */
  47209. this.discard = false;
  47210. /**
  47211. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  47212. * device does not support the extension.
  47213. *
  47214. * @type {?EXTDisjointTimerQueryWebGL2}
  47215. * @default null
  47216. */
  47217. this.disjoint = null;
  47218. /**
  47219. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  47220. * device does not support the extension.
  47221. *
  47222. * @type {?KHRParallelShaderCompile}
  47223. * @default null
  47224. */
  47225. this.parallel = null;
  47226. /**
  47227. * A reference to the current render context.
  47228. *
  47229. * @private
  47230. * @type {RenderContext}
  47231. * @default null
  47232. */
  47233. this._currentContext = null;
  47234. /**
  47235. * A unique collection of bindings.
  47236. *
  47237. * @private
  47238. * @type {WeakSet<Array<BindGroup>>}
  47239. */
  47240. this._knownBindings = new WeakSet();
  47241. /**
  47242. * Whether the device supports framebuffers invalidation or not.
  47243. *
  47244. * @private
  47245. * @type {boolean}
  47246. */
  47247. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  47248. /**
  47249. * The target framebuffer when rendering with
  47250. * the WebXR device API.
  47251. *
  47252. * @private
  47253. * @type {?WebGLFramebuffer}
  47254. * @default null
  47255. */
  47256. this._xrFramebuffer = null;
  47257. }
  47258. /**
  47259. * Initializes the backend so it is ready for usage.
  47260. *
  47261. * @param {Renderer} renderer - The renderer.
  47262. */
  47263. init( renderer ) {
  47264. super.init( renderer );
  47265. //
  47266. const parameters = this.parameters;
  47267. const contextAttributes = {
  47268. antialias: renderer.currentSamples > 0,
  47269. alpha: true, // always true for performance reasons
  47270. depth: renderer.depth,
  47271. stencil: renderer.stencil
  47272. };
  47273. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  47274. function onContextLost( event ) {
  47275. event.preventDefault();
  47276. const contextLossInfo = {
  47277. api: 'WebGL',
  47278. message: event.statusMessage || 'Unknown reason',
  47279. reason: null,
  47280. originalEvent: event
  47281. };
  47282. renderer.onDeviceLost( contextLossInfo );
  47283. }
  47284. this._onContextLost = onContextLost;
  47285. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  47286. this.gl = glContext;
  47287. this.extensions = new WebGLExtensions( this );
  47288. this.capabilities = new WebGLCapabilities( this );
  47289. this.attributeUtils = new WebGLAttributeUtils( this );
  47290. this.textureUtils = new WebGLTextureUtils( this );
  47291. this.bufferRenderer = new WebGLBufferRenderer( this );
  47292. this.state = new WebGLState( this );
  47293. this.utils = new WebGLUtils( this );
  47294. this.extensions.get( 'EXT_color_buffer_float' );
  47295. this.extensions.get( 'WEBGL_clip_cull_distance' );
  47296. this.extensions.get( 'OES_texture_float_linear' );
  47297. this.extensions.get( 'EXT_color_buffer_half_float' );
  47298. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  47299. this.extensions.get( 'WEBGL_render_shared_exponent' );
  47300. this.extensions.get( 'WEBGL_multi_draw' );
  47301. this.extensions.get( 'OVR_multiview2' );
  47302. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  47303. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  47304. }
  47305. /**
  47306. * The coordinate system of the backend.
  47307. *
  47308. * @type {number}
  47309. * @readonly
  47310. */
  47311. get coordinateSystem() {
  47312. return WebGLCoordinateSystem;
  47313. }
  47314. /**
  47315. * This method performs a readback operation by moving buffer data from
  47316. * a storage buffer attribute from the GPU to the CPU.
  47317. *
  47318. * @async
  47319. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  47320. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  47321. */
  47322. async getArrayBufferAsync( attribute ) {
  47323. return await this.attributeUtils.getArrayBufferAsync( attribute );
  47324. }
  47325. /**
  47326. * Ensures the backend is XR compatible.
  47327. *
  47328. * @async
  47329. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  47330. */
  47331. async makeXRCompatible() {
  47332. const attributes = this.gl.getContextAttributes();
  47333. if ( attributes.xrCompatible !== true ) {
  47334. await this.gl.makeXRCompatible();
  47335. }
  47336. }
  47337. /**
  47338. * Sets the XR rendering destination.
  47339. *
  47340. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  47341. */
  47342. setXRTarget( xrFramebuffer ) {
  47343. this._xrFramebuffer = xrFramebuffer;
  47344. }
  47345. /**
  47346. * Configures the given XR render target with external textures.
  47347. *
  47348. * This method is only relevant when using the WebXR Layers API.
  47349. *
  47350. * @param {XRRenderTarget} renderTarget - The XR render target.
  47351. * @param {WebGLTexture} colorTexture - A native color texture.
  47352. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  47353. */
  47354. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  47355. const gl = this.gl;
  47356. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  47357. if ( depthTexture !== null ) {
  47358. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  47359. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  47360. // The multisample_render_to_texture extension doesn't work properly if there
  47361. // are midframe flushes and an external depth texture.
  47362. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  47363. warn( 'WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  47364. }
  47365. renderTarget._autoAllocateDepthBuffer = false;
  47366. }
  47367. }
  47368. /**
  47369. * Inits a time stamp query for the given render context.
  47370. *
  47371. * @param {string} type - The type of the timestamp query.
  47372. * @param {string} uid - A unique identifier for the timestamp query.
  47373. */
  47374. initTimestampQuery( type, uid ) {
  47375. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  47376. if ( ! this.timestampQueryPool[ type ] ) {
  47377. // TODO: Variable maxQueries?
  47378. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  47379. }
  47380. const timestampQueryPool = this.timestampQueryPool[ type ];
  47381. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  47382. if ( baseOffset !== null ) {
  47383. timestampQueryPool.beginQuery( uid );
  47384. }
  47385. }
  47386. // timestamp utils
  47387. /**
  47388. * Prepares the timestamp buffer.
  47389. *
  47390. * @param {string} type - The type of the timestamp query.
  47391. * @param {string} uid - A unique identifier for the timestamp query.
  47392. */
  47393. prepareTimestampBuffer( type, uid ) {
  47394. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  47395. const timestampQueryPool = this.timestampQueryPool[ type ];
  47396. timestampQueryPool.endQuery( uid );
  47397. }
  47398. /**
  47399. * Returns the backend's rendering context.
  47400. *
  47401. * @return {WebGL2RenderingContext} The rendering context.
  47402. */
  47403. getContext() {
  47404. return this.gl;
  47405. }
  47406. /**
  47407. * This method is executed at the beginning of a render call and prepares
  47408. * the WebGL state for upcoming render calls
  47409. *
  47410. * @param {RenderContext} renderContext - The render context.
  47411. */
  47412. beginRender( renderContext ) {
  47413. const { state } = this;
  47414. const renderContextData = this.get( renderContext );
  47415. //
  47416. if ( renderContext.viewport ) {
  47417. this.updateViewport( renderContext );
  47418. } else {
  47419. const { width, height } = this.getDrawingBufferSize();
  47420. state.viewport( 0, 0, width, height );
  47421. }
  47422. if ( renderContext.scissor ) {
  47423. const { x, y, width, height } = renderContext.scissorValue;
  47424. state.scissor( x, renderContext.height - height - y, width, height );
  47425. }
  47426. //
  47427. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  47428. renderContextData.previousContext = this._currentContext;
  47429. this._currentContext = renderContext;
  47430. this._setFramebuffer( renderContext );
  47431. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  47432. const occlusionQueryCount = renderContext.occlusionQueryCount;
  47433. if ( occlusionQueryCount > 0 ) {
  47434. // Get a reference to the array of objects with queries. The renderContextData property
  47435. // can be changed by another render pass before the async reading of all previous queries complete
  47436. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  47437. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  47438. renderContextData.lastOcclusionObject = null;
  47439. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  47440. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  47441. renderContextData.occlusionQueryIndex = 0;
  47442. }
  47443. }
  47444. /**
  47445. * This method is executed at the end of a render call and finalizes work
  47446. * after draw calls.
  47447. *
  47448. * @param {RenderContext} renderContext - The render context.
  47449. */
  47450. finishRender( renderContext ) {
  47451. const { gl, state } = this;
  47452. const renderContextData = this.get( renderContext );
  47453. const previousContext = renderContextData.previousContext;
  47454. state.resetVertexState();
  47455. const occlusionQueryCount = renderContext.occlusionQueryCount;
  47456. if ( occlusionQueryCount > 0 ) {
  47457. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  47458. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  47459. }
  47460. this.resolveOccludedAsync( renderContext );
  47461. }
  47462. const textures = renderContext.textures;
  47463. if ( textures !== null ) {
  47464. for ( let i = 0; i < textures.length; i ++ ) {
  47465. const texture = textures[ i ];
  47466. if ( texture.generateMipmaps ) {
  47467. this.generateMipmaps( texture );
  47468. }
  47469. }
  47470. }
  47471. this._currentContext = previousContext;
  47472. this._resolveRenderTarget( renderContext );
  47473. if ( previousContext !== null ) {
  47474. this._setFramebuffer( previousContext );
  47475. if ( previousContext.viewport ) {
  47476. this.updateViewport( previousContext );
  47477. } else {
  47478. const { width, height } = this.getDrawingBufferSize();
  47479. state.viewport( 0, 0, width, height );
  47480. }
  47481. }
  47482. this.prepareTimestampBuffer( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  47483. }
  47484. /**
  47485. * This method processes the result of occlusion queries and writes it
  47486. * into render context data.
  47487. *
  47488. * @async
  47489. * @param {RenderContext} renderContext - The render context.
  47490. */
  47491. resolveOccludedAsync( renderContext ) {
  47492. const renderContextData = this.get( renderContext );
  47493. // handle occlusion query results
  47494. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  47495. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  47496. const occluded = new WeakSet();
  47497. const { gl } = this;
  47498. renderContextData.currentOcclusionQueryObjects = null;
  47499. renderContextData.currentOcclusionQueries = null;
  47500. const check = () => {
  47501. let completed = 0;
  47502. // check all queries and requeue as appropriate
  47503. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  47504. const query = currentOcclusionQueries[ i ];
  47505. if ( query === null ) continue;
  47506. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  47507. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  47508. currentOcclusionQueries[ i ] = null;
  47509. gl.deleteQuery( query );
  47510. completed ++;
  47511. }
  47512. }
  47513. if ( completed < currentOcclusionQueries.length ) {
  47514. requestAnimationFrame( check );
  47515. } else {
  47516. renderContextData.occluded = occluded;
  47517. }
  47518. };
  47519. check();
  47520. }
  47521. }
  47522. /**
  47523. * Returns `true` if the given 3D object is fully occluded by other
  47524. * 3D objects in the scene.
  47525. *
  47526. * @param {RenderContext} renderContext - The render context.
  47527. * @param {Object3D} object - The 3D object to test.
  47528. * @return {boolean} Whether the 3D object is fully occluded or not.
  47529. */
  47530. isOccluded( renderContext, object ) {
  47531. const renderContextData = this.get( renderContext );
  47532. return renderContextData.occluded && renderContextData.occluded.has( object );
  47533. }
  47534. /**
  47535. * Updates the viewport with the values from the given render context.
  47536. *
  47537. * @param {RenderContext} renderContext - The render context.
  47538. */
  47539. updateViewport( renderContext ) {
  47540. const { state } = this;
  47541. const { x, y, width, height } = renderContext.viewportValue;
  47542. state.viewport( x, renderContext.height - height - y, width, height );
  47543. }
  47544. /**
  47545. * Defines the scissor test.
  47546. *
  47547. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  47548. */
  47549. setScissorTest( boolean ) {
  47550. const state = this.state;
  47551. state.setScissorTest( boolean );
  47552. }
  47553. /**
  47554. * Returns the clear color and alpha into a single
  47555. * color object.
  47556. *
  47557. * @return {Color4} The clear color.
  47558. */
  47559. getClearColor() {
  47560. const clearColor = super.getClearColor();
  47561. // Since the canvas is always created with alpha: true,
  47562. // WebGL must always premultiply the clear color.
  47563. clearColor.r *= clearColor.a;
  47564. clearColor.g *= clearColor.a;
  47565. clearColor.b *= clearColor.a;
  47566. return clearColor;
  47567. }
  47568. /**
  47569. * Performs a clear operation.
  47570. *
  47571. * @param {boolean} color - Whether the color buffer should be cleared or not.
  47572. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  47573. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  47574. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  47575. * @param {boolean} [setFrameBuffer=true] - Controls whether the intermediate framebuffer should be set or not.
  47576. * @param {boolean} [resolveRenderTarget=true] - Controls whether an active render target should be resolved
  47577. * or not. Only relevant for explicit clears.
  47578. */
  47579. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true, resolveRenderTarget = true ) {
  47580. const { gl, renderer } = this;
  47581. if ( descriptor === null ) {
  47582. const clearColor = this.getClearColor();
  47583. descriptor = {
  47584. textures: null,
  47585. clearColorValue: clearColor
  47586. };
  47587. }
  47588. //
  47589. let clear = 0;
  47590. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  47591. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  47592. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  47593. if ( clear !== 0 ) {
  47594. let clearColor;
  47595. if ( descriptor.clearColorValue ) {
  47596. clearColor = descriptor.clearColorValue;
  47597. } else {
  47598. clearColor = this.getClearColor();
  47599. }
  47600. const clearDepth = renderer.getClearDepth();
  47601. const clearStencil = renderer.getClearStencil();
  47602. if ( depth ) this.state.setDepthMask( true );
  47603. if ( descriptor.textures === null ) {
  47604. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  47605. gl.clear( clear );
  47606. } else {
  47607. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  47608. if ( color ) {
  47609. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  47610. if ( i === 0 ) {
  47611. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  47612. } else {
  47613. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  47614. }
  47615. }
  47616. }
  47617. if ( depth && stencil ) {
  47618. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  47619. } else if ( depth ) {
  47620. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  47621. } else if ( stencil ) {
  47622. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  47623. }
  47624. if ( setFrameBuffer && resolveRenderTarget ) this._resolveRenderTarget( descriptor );
  47625. }
  47626. }
  47627. }
  47628. /**
  47629. * This method is executed at the beginning of a compute call and
  47630. * prepares the state for upcoming compute tasks.
  47631. *
  47632. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47633. */
  47634. beginCompute( computeGroup ) {
  47635. const { state, gl } = this;
  47636. //
  47637. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  47638. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  47639. }
  47640. /**
  47641. * Executes a compute command for the given compute node.
  47642. *
  47643. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  47644. * @param {Node} computeNode - The compute node.
  47645. * @param {Array<BindGroup>} bindings - The bindings.
  47646. * @param {ComputePipeline} pipeline - The compute pipeline.
  47647. * @param {?number} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  47648. */
  47649. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  47650. const { state, gl } = this;
  47651. if ( this.discard === false ) {
  47652. // required here to handle async behaviour of render.compute()
  47653. gl.enable( gl.RASTERIZER_DISCARD );
  47654. this.discard = true;
  47655. }
  47656. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  47657. const vaoKey = this._getVaoKey( attributes );
  47658. const vaoGPU = this.vaoCache[ vaoKey ];
  47659. if ( vaoGPU === undefined ) {
  47660. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  47661. } else {
  47662. state.setVertexState( vaoGPU );
  47663. }
  47664. state.useProgram( programGPU );
  47665. this._bindUniforms( bindings );
  47666. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  47667. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  47668. gl.beginTransformFeedback( gl.POINTS );
  47669. count = ( count !== null ) ? count : computeNode.count;
  47670. if ( Array.isArray( count ) ) {
  47671. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  47672. count = count[ 0 ];
  47673. } else if ( count && typeof count === 'object' && count.isIndirectStorageBufferAttribute ) {
  47674. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute' );
  47675. count = computeNode.count;
  47676. }
  47677. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  47678. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  47679. } else {
  47680. gl.drawArrays( gl.POINTS, 0, count );
  47681. }
  47682. gl.endTransformFeedback();
  47683. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  47684. // switch active buffers
  47685. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  47686. const dualAttributeData = transformBuffers[ i ];
  47687. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  47688. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  47689. }
  47690. dualAttributeData.switchBuffers();
  47691. }
  47692. }
  47693. /**
  47694. * This method is executed at the end of a compute call and
  47695. * finalizes work after compute tasks.
  47696. *
  47697. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47698. */
  47699. finishCompute( computeGroup ) {
  47700. const gl = this.gl;
  47701. this.discard = false;
  47702. gl.disable( gl.RASTERIZER_DISCARD );
  47703. this.prepareTimestampBuffer( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  47704. if ( this._currentContext ) {
  47705. this._setFramebuffer( this._currentContext );
  47706. }
  47707. }
  47708. /**
  47709. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  47710. *
  47711. * @param {RenderContext} renderContext - The render context.
  47712. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  47713. *
  47714. * @private
  47715. */
  47716. _isRenderCameraDepthArray( renderContext ) {
  47717. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  47718. }
  47719. /**
  47720. * Executes a draw command for the given render object.
  47721. *
  47722. * @param {RenderObject} renderObject - The render object to draw.
  47723. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  47724. */
  47725. draw( renderObject/*, info*/ ) {
  47726. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  47727. const { programGPU } = this.get( pipeline );
  47728. const { gl, state } = this;
  47729. const contextData = this.get( context );
  47730. const drawParams = renderObject.getDrawParameters();
  47731. if ( drawParams === null ) return;
  47732. //
  47733. this._bindUniforms( renderObject.getBindings() );
  47734. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  47735. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  47736. state.useProgram( programGPU );
  47737. // vertex state
  47738. const attributes = renderObject.getAttributes();
  47739. const attributesData = this.get( attributes );
  47740. let vaoGPU = attributesData.vaoGPU;
  47741. if ( vaoGPU === undefined ) {
  47742. const vaoKey = this._getVaoKey( attributes );
  47743. vaoGPU = this.vaoCache[ vaoKey ];
  47744. if ( vaoGPU === undefined ) {
  47745. vaoGPU = this._createVao( attributes );
  47746. this.vaoCache[ vaoKey ] = vaoGPU;
  47747. attributesData.vaoGPU = vaoGPU;
  47748. }
  47749. }
  47750. const index = renderObject.getIndex();
  47751. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  47752. state.setVertexState( vaoGPU, indexGPU );
  47753. //
  47754. const lastObject = contextData.lastOcclusionObject;
  47755. if ( lastObject !== object && lastObject !== undefined ) {
  47756. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  47757. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  47758. contextData.occlusionQueryIndex ++;
  47759. }
  47760. if ( object.occlusionTest === true ) {
  47761. const query = gl.createQuery();
  47762. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  47763. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  47764. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  47765. }
  47766. contextData.lastOcclusionObject = object;
  47767. }
  47768. //
  47769. const renderer = this.bufferRenderer;
  47770. if ( object.isPoints ) renderer.mode = gl.POINTS;
  47771. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  47772. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  47773. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  47774. else {
  47775. if ( material.wireframe === true ) {
  47776. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  47777. renderer.mode = gl.LINES;
  47778. } else {
  47779. renderer.mode = gl.TRIANGLES;
  47780. }
  47781. }
  47782. //
  47783. const { vertexCount, instanceCount } = drawParams;
  47784. let { firstVertex } = drawParams;
  47785. renderer.object = object;
  47786. if ( index !== null ) {
  47787. firstVertex *= index.array.BYTES_PER_ELEMENT;
  47788. const indexData = this.get( index );
  47789. renderer.index = index.count;
  47790. renderer.type = indexData.type;
  47791. } else {
  47792. renderer.index = 0;
  47793. }
  47794. const draw = () => {
  47795. if ( object.isBatchedMesh ) {
  47796. if ( object._multiDrawInstances !== null ) {
  47797. // @deprecated, r174
  47798. warnOnce( 'WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  47799. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  47800. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  47801. warnOnce( 'WebGLBackend: WEBGL_multi_draw not supported.' );
  47802. } else {
  47803. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  47804. }
  47805. } else if ( instanceCount > 1 ) {
  47806. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  47807. } else {
  47808. renderer.render( firstVertex, vertexCount );
  47809. }
  47810. };
  47811. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  47812. const cameraData = this.get( renderObject.camera );
  47813. const cameras = renderObject.camera.cameras;
  47814. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  47815. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  47816. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  47817. const indexesGPU = [];
  47818. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  47819. const bufferGPU = gl.createBuffer();
  47820. data[ 0 ] = i;
  47821. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  47822. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  47823. indexesGPU.push( bufferGPU );
  47824. }
  47825. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  47826. }
  47827. const cameraIndexData = this.get( cameraIndex );
  47828. const pixelRatio = this.renderer.getPixelRatio();
  47829. const renderTarget = this._currentContext.renderTarget;
  47830. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  47831. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  47832. if ( isRenderCameraDepthArray ) {
  47833. // Clear the depth texture
  47834. const textureData = this.get( renderTarget.depthTexture );
  47835. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  47836. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  47837. const { stencilBuffer } = renderTarget;
  47838. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  47839. this.renderer._activeCubeFace = i;
  47840. this._currentContext.activeCubeFace = i;
  47841. this._setFramebuffer( this._currentContext );
  47842. this.clear( false, true, stencilBuffer, this._currentContext, false, false );
  47843. }
  47844. this.renderer._activeCubeFace = prevActiveCubeFace;
  47845. this._currentContext.activeCubeFace = prevActiveCubeFace;
  47846. }
  47847. }
  47848. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  47849. const subCamera = cameras[ i ];
  47850. if ( object.layers.test( subCamera.layers ) ) {
  47851. if ( isRenderCameraDepthArray ) {
  47852. // Update the active layer
  47853. this.renderer._activeCubeFace = i;
  47854. this._currentContext.activeCubeFace = i;
  47855. this._setFramebuffer( this._currentContext );
  47856. }
  47857. const vp = subCamera.viewport;
  47858. if ( vp !== undefined ) {
  47859. const x = vp.x * pixelRatio;
  47860. const y = vp.y * pixelRatio;
  47861. const width = vp.width * pixelRatio;
  47862. const height = vp.height * pixelRatio;
  47863. state.viewport(
  47864. Math.floor( x ),
  47865. Math.floor( renderObject.context.height - height - y ),
  47866. Math.floor( width ),
  47867. Math.floor( height )
  47868. );
  47869. }
  47870. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  47871. draw();
  47872. }
  47873. this._currentContext.activeCubeFace = prevActiveCubeFace;
  47874. this.renderer._activeCubeFace = prevActiveCubeFace;
  47875. }
  47876. } else {
  47877. draw();
  47878. }
  47879. }
  47880. /**
  47881. * Explain why always null is returned.
  47882. *
  47883. * @param {RenderObject} renderObject - The render object.
  47884. * @return {boolean} Whether the render pipeline requires an update or not.
  47885. */
  47886. needsRenderUpdate( /*renderObject*/ ) {
  47887. return false;
  47888. }
  47889. /**
  47890. * Explain why no cache key is computed.
  47891. *
  47892. * @param {RenderObject} renderObject - The render object.
  47893. * @return {string} The cache key.
  47894. */
  47895. getRenderCacheKey( /*renderObject*/ ) {
  47896. return '';
  47897. }
  47898. // textures
  47899. /**
  47900. * Creates a default texture for the given texture that can be used
  47901. * as a placeholder until the actual texture is ready for usage.
  47902. *
  47903. * @param {Texture} texture - The texture to create a default texture for.
  47904. */
  47905. createDefaultTexture( texture ) {
  47906. this.textureUtils.createDefaultTexture( texture );
  47907. }
  47908. /**
  47909. * Defines a texture on the GPU for the given texture object.
  47910. *
  47911. * @param {Texture} texture - The texture.
  47912. * @param {Object} [options={}] - Optional configuration parameter.
  47913. */
  47914. createTexture( texture, options ) {
  47915. this.textureUtils.createTexture( texture, options );
  47916. }
  47917. /**
  47918. * Uploads the updated texture data to the GPU.
  47919. *
  47920. * @param {Texture} texture - The texture.
  47921. * @param {Object} [options={}] - Optional configuration parameter.
  47922. */
  47923. updateTexture( texture, options ) {
  47924. this.textureUtils.updateTexture( texture, options );
  47925. }
  47926. /**
  47927. * Generates mipmaps for the given texture.
  47928. *
  47929. * @param {Texture} texture - The texture.
  47930. */
  47931. generateMipmaps( texture ) {
  47932. this.textureUtils.generateMipmaps( texture );
  47933. }
  47934. /**
  47935. * Destroys the GPU data for the given texture object.
  47936. *
  47937. * @param {Texture} texture - The texture.
  47938. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  47939. */
  47940. destroyTexture( texture, isDefaultTexture = false ) {
  47941. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  47942. }
  47943. /**
  47944. * Returns texture data as a typed array.
  47945. *
  47946. * @async
  47947. * @param {Texture} texture - The texture to copy.
  47948. * @param {number} x - The x coordinate of the copy origin.
  47949. * @param {number} y - The y coordinate of the copy origin.
  47950. * @param {number} width - The width of the copy.
  47951. * @param {number} height - The height of the copy.
  47952. * @param {number} faceIndex - The face index.
  47953. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47954. */
  47955. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  47956. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  47957. }
  47958. /**
  47959. * This method does nothing since WebGL 2 has no concept of samplers.
  47960. *
  47961. * @param {Texture} texture - The texture to update the sampler for.
  47962. * @return {string} The current sampler key.
  47963. */
  47964. updateSampler( /*texture*/ ) {
  47965. return '';
  47966. }
  47967. // node builder
  47968. /**
  47969. * Returns a node builder for the given render object.
  47970. *
  47971. * @param {RenderObject} object - The render object.
  47972. * @param {Renderer} renderer - The renderer.
  47973. * @return {GLSLNodeBuilder} The node builder.
  47974. */
  47975. createNodeBuilder( object, renderer ) {
  47976. return new GLSLNodeBuilder( object, renderer );
  47977. }
  47978. // program
  47979. /**
  47980. * Creates a shader program from the given programmable stage.
  47981. *
  47982. * @param {ProgrammableStage} program - The programmable stage.
  47983. */
  47984. createProgram( program ) {
  47985. const gl = this.gl;
  47986. const { stage, code } = program;
  47987. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  47988. gl.shaderSource( shader, code );
  47989. gl.compileShader( shader );
  47990. this.set( program, {
  47991. shaderGPU: shader
  47992. } );
  47993. }
  47994. /**
  47995. * Destroys the shader program of the given programmable stage.
  47996. *
  47997. * @param {ProgrammableStage} program - The programmable stage.
  47998. */
  47999. destroyProgram( program ) {
  48000. this.delete( program );
  48001. }
  48002. /**
  48003. * Creates a render pipeline for the given render object.
  48004. *
  48005. * @param {RenderObject} renderObject - The render object.
  48006. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  48007. */
  48008. createRenderPipeline( renderObject, promises ) {
  48009. const gl = this.gl;
  48010. const pipeline = renderObject.pipeline;
  48011. // Program
  48012. const { fragmentProgram, vertexProgram } = pipeline;
  48013. const programGPU = gl.createProgram();
  48014. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  48015. const vertexShader = this.get( vertexProgram ).shaderGPU;
  48016. gl.attachShader( programGPU, fragmentShader );
  48017. gl.attachShader( programGPU, vertexShader );
  48018. gl.linkProgram( programGPU );
  48019. this.set( pipeline, {
  48020. programGPU,
  48021. fragmentShader,
  48022. vertexShader
  48023. } );
  48024. if ( promises !== null && this.parallel ) {
  48025. const p = new Promise( ( resolve /*, reject*/ ) => {
  48026. const parallel = this.parallel;
  48027. const checkStatus = () => {
  48028. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  48029. this._completeCompile( renderObject, pipeline );
  48030. resolve();
  48031. } else {
  48032. requestAnimationFrame( checkStatus );
  48033. }
  48034. };
  48035. checkStatus();
  48036. } );
  48037. promises.push( p );
  48038. return;
  48039. }
  48040. this._completeCompile( renderObject, pipeline );
  48041. }
  48042. /**
  48043. * Formats the source code of error messages.
  48044. *
  48045. * @private
  48046. * @param {string} string - The code.
  48047. * @param {number} errorLine - The error line.
  48048. * @return {string} The formatted code.
  48049. */
  48050. _handleSource( string, errorLine ) {
  48051. const lines = string.split( '\n' );
  48052. const lines2 = [];
  48053. const from = Math.max( errorLine - 6, 0 );
  48054. const to = Math.min( errorLine + 6, lines.length );
  48055. for ( let i = from; i < to; i ++ ) {
  48056. const line = i + 1;
  48057. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  48058. }
  48059. return lines2.join( '\n' );
  48060. }
  48061. /**
  48062. * Gets the shader compilation errors from the info log.
  48063. *
  48064. * @private
  48065. * @param {WebGL2RenderingContext} gl - The rendering context.
  48066. * @param {WebGLShader} shader - The WebGL shader object.
  48067. * @param {string} type - The shader type.
  48068. * @return {string} The shader errors.
  48069. */
  48070. _getShaderErrors( gl, shader, type ) {
  48071. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  48072. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  48073. const errors = shaderInfoLog.trim();
  48074. if ( status && errors === '' ) return '';
  48075. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  48076. if ( errorMatches ) {
  48077. const errorLine = parseInt( errorMatches[ 1 ] );
  48078. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  48079. } else {
  48080. return errors;
  48081. }
  48082. }
  48083. /**
  48084. * Logs shader compilation errors.
  48085. *
  48086. * @private
  48087. * @param {WebGLProgram} programGPU - The WebGL program.
  48088. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  48089. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  48090. */
  48091. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  48092. if ( this.renderer.debug.checkShaderErrors ) {
  48093. const gl = this.gl;
  48094. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  48095. const programLog = programInfoLog.trim();
  48096. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  48097. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  48098. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  48099. } else {
  48100. // default error reporting
  48101. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  48102. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  48103. error(
  48104. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  48105. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  48106. 'Program Info Log: ' + programLog + '\n' +
  48107. vertexErrors + '\n' +
  48108. fragmentErrors
  48109. );
  48110. }
  48111. } else if ( programLog !== '' ) {
  48112. warn( 'WebGLProgram: Program Info Log:', programLog );
  48113. }
  48114. }
  48115. }
  48116. /**
  48117. * Completes the shader program setup for the given render object.
  48118. *
  48119. * @private
  48120. * @param {RenderObject} renderObject - The render object.
  48121. * @param {RenderPipeline} pipeline - The render pipeline.
  48122. */
  48123. _completeCompile( renderObject, pipeline ) {
  48124. const { state, gl } = this;
  48125. const pipelineData = this.get( pipeline );
  48126. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  48127. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  48128. this._logProgramError( programGPU, fragmentShader, vertexShader );
  48129. }
  48130. state.useProgram( programGPU );
  48131. // Bindings
  48132. const bindings = renderObject.getBindings();
  48133. this._setupBindings( bindings, programGPU );
  48134. //
  48135. this.set( pipeline, {
  48136. programGPU
  48137. } );
  48138. }
  48139. /**
  48140. * Creates a compute pipeline for the given compute node.
  48141. *
  48142. * @param {ComputePipeline} computePipeline - The compute pipeline.
  48143. * @param {Array<BindGroup>} bindings - The bindings.
  48144. */
  48145. createComputePipeline( computePipeline, bindings ) {
  48146. const { state, gl } = this;
  48147. // Program
  48148. const fragmentProgram = {
  48149. stage: 'fragment',
  48150. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  48151. };
  48152. this.createProgram( fragmentProgram );
  48153. const { computeProgram } = computePipeline;
  48154. const programGPU = gl.createProgram();
  48155. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  48156. const vertexShader = this.get( computeProgram ).shaderGPU;
  48157. const transforms = computeProgram.transforms;
  48158. const transformVaryingNames = [];
  48159. const transformAttributeNodes = [];
  48160. for ( let i = 0; i < transforms.length; i ++ ) {
  48161. const transform = transforms[ i ];
  48162. transformVaryingNames.push( transform.varyingName );
  48163. transformAttributeNodes.push( transform.attributeNode );
  48164. }
  48165. gl.attachShader( programGPU, fragmentShader );
  48166. gl.attachShader( programGPU, vertexShader );
  48167. gl.transformFeedbackVaryings(
  48168. programGPU,
  48169. transformVaryingNames,
  48170. gl.SEPARATE_ATTRIBS
  48171. );
  48172. gl.linkProgram( programGPU );
  48173. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  48174. this._logProgramError( programGPU, fragmentShader, vertexShader );
  48175. }
  48176. state.useProgram( programGPU );
  48177. // Bindings
  48178. this._setupBindings( bindings, programGPU );
  48179. const attributeNodes = computeProgram.attributes;
  48180. const attributes = [];
  48181. const transformBuffers = [];
  48182. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  48183. const attribute = attributeNodes[ i ].node.attribute;
  48184. attributes.push( attribute );
  48185. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  48186. }
  48187. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  48188. const attribute = transformAttributeNodes[ i ].attribute;
  48189. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  48190. const attributeData = this.get( attribute );
  48191. transformBuffers.push( attributeData );
  48192. }
  48193. //
  48194. this.set( computePipeline, {
  48195. programGPU,
  48196. transformBuffers,
  48197. attributes
  48198. } );
  48199. }
  48200. /**
  48201. * Creates bindings from the given bind group definition.
  48202. *
  48203. * @param {BindGroup} bindGroup - The bind group.
  48204. * @param {Array<BindGroup>} bindings - Array of bind groups.
  48205. * @param {number} cacheIndex - The cache index.
  48206. * @param {number} version - The version.
  48207. */
  48208. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  48209. if ( this._knownBindings.has( bindings ) === false ) {
  48210. this._knownBindings.add( bindings );
  48211. let uniformBuffers = 0;
  48212. let textures = 0;
  48213. for ( const bindGroup of bindings ) {
  48214. this.set( bindGroup, {
  48215. textures: textures,
  48216. uniformBuffers: uniformBuffers
  48217. } );
  48218. for ( const binding of bindGroup.bindings ) {
  48219. if ( binding.isUniformBuffer ) uniformBuffers ++;
  48220. if ( binding.isSampledTexture ) textures ++;
  48221. }
  48222. }
  48223. }
  48224. this.updateBindings( bindGroup, bindings );
  48225. }
  48226. /**
  48227. * Updates the given bind group definition.
  48228. *
  48229. * @param {BindGroup} bindGroup - The bind group.
  48230. * @param {Array<BindGroup>} bindings - Array of bind groups.
  48231. * @param {number} cacheIndex - The cache index.
  48232. * @param {number} version - The version.
  48233. */
  48234. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  48235. const { gl } = this;
  48236. const bindGroupData = this.get( bindGroup );
  48237. let i = bindGroupData.uniformBuffers;
  48238. let t = bindGroupData.textures;
  48239. for ( const binding of bindGroup.bindings ) {
  48240. const map = this.get( binding );
  48241. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  48242. const data = binding.buffer;
  48243. let { bufferGPU } = this.get( data );
  48244. if ( bufferGPU === undefined ) {
  48245. // create
  48246. bufferGPU = gl.createBuffer();
  48247. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  48248. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  48249. this.set( data, { bufferGPU } );
  48250. } else {
  48251. // update
  48252. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  48253. gl.bufferSubData( gl.UNIFORM_BUFFER, 0, data );
  48254. }
  48255. map.index = i ++;
  48256. map.bufferGPU = bufferGPU;
  48257. this.set( binding, map );
  48258. } else if ( binding.isSampledTexture ) {
  48259. const { textureGPU, glTextureType } = this.get( binding.texture );
  48260. map.index = t ++;
  48261. map.textureGPU = textureGPU;
  48262. map.glTextureType = glTextureType;
  48263. this.set( binding, map );
  48264. }
  48265. }
  48266. }
  48267. /**
  48268. * Updates a buffer binding.
  48269. *
  48270. * @param {Buffer} binding - The buffer binding to update.
  48271. */
  48272. updateBinding( binding ) {
  48273. const gl = this.gl;
  48274. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  48275. const bindingData = this.get( binding );
  48276. const bufferGPU = bindingData.bufferGPU;
  48277. const data = binding.buffer;
  48278. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  48279. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  48280. }
  48281. }
  48282. // attributes
  48283. /**
  48284. * Creates the GPU buffer of an indexed shader attribute.
  48285. *
  48286. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  48287. */
  48288. createIndexAttribute( attribute ) {
  48289. const gl = this.gl;
  48290. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  48291. }
  48292. /**
  48293. * Creates the GPU buffer of a shader attribute.
  48294. *
  48295. * @param {BufferAttribute} attribute - The buffer attribute.
  48296. */
  48297. createAttribute( attribute ) {
  48298. if ( this.has( attribute ) ) return;
  48299. const gl = this.gl;
  48300. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  48301. }
  48302. /**
  48303. * Creates the GPU buffer of a storage attribute.
  48304. *
  48305. * @param {BufferAttribute} attribute - The buffer attribute.
  48306. */
  48307. createStorageAttribute( attribute ) {
  48308. if ( this.has( attribute ) ) return;
  48309. const gl = this.gl;
  48310. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  48311. }
  48312. /**
  48313. * Updates the GPU buffer of a shader attribute.
  48314. *
  48315. * @param {BufferAttribute} attribute - The buffer attribute to update.
  48316. */
  48317. updateAttribute( attribute ) {
  48318. this.attributeUtils.updateAttribute( attribute );
  48319. }
  48320. /**
  48321. * Destroys the GPU buffer of a shader attribute.
  48322. *
  48323. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  48324. */
  48325. destroyAttribute( attribute ) {
  48326. this.attributeUtils.destroyAttribute( attribute );
  48327. }
  48328. /**
  48329. * Checks if the given feature is supported by the backend.
  48330. *
  48331. * @param {string} name - The feature's name.
  48332. * @return {boolean} Whether the feature is supported or not.
  48333. */
  48334. hasFeature( name ) {
  48335. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  48336. const extensions = this.extensions;
  48337. for ( let i = 0; i < keysMatching.length; i ++ ) {
  48338. if ( extensions.has( keysMatching[ i ] ) ) return true;
  48339. }
  48340. return false;
  48341. }
  48342. /**
  48343. * Returns the maximum anisotropy texture filtering value.
  48344. *
  48345. * @return {number} The maximum anisotropy texture filtering value.
  48346. */
  48347. getMaxAnisotropy() {
  48348. return this.capabilities.getMaxAnisotropy();
  48349. }
  48350. /**
  48351. * Copies data of the given source texture to the given destination texture.
  48352. *
  48353. * @param {Texture} srcTexture - The source texture.
  48354. * @param {Texture} dstTexture - The destination texture.
  48355. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  48356. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  48357. * @param {number} [srcLevel=0] - The source mip level to copy from.
  48358. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  48359. */
  48360. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  48361. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  48362. }
  48363. /**
  48364. * Copies the current bound framebuffer to the given texture.
  48365. *
  48366. * @param {Texture} texture - The destination texture.
  48367. * @param {RenderContext} renderContext - The render context.
  48368. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  48369. */
  48370. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  48371. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  48372. }
  48373. /**
  48374. * Configures the active framebuffer from the given render context.
  48375. *
  48376. * @private
  48377. * @param {RenderContext} descriptor - The render context.
  48378. */
  48379. _setFramebuffer( descriptor ) {
  48380. const { gl, state } = this;
  48381. let currentFrameBuffer = null;
  48382. if ( descriptor.textures !== null ) {
  48383. const renderTarget = descriptor.renderTarget;
  48384. const renderTargetContextData = this.get( renderTarget );
  48385. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  48386. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  48387. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  48388. const isRenderTargetArray = renderTarget.depth > 1;
  48389. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  48390. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  48391. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  48392. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  48393. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  48394. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  48395. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  48396. const cacheKey = getCacheKey( descriptor );
  48397. let fb;
  48398. if ( isCube ) {
  48399. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  48400. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  48401. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  48402. fb = this._xrFramebuffer;
  48403. } else {
  48404. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  48405. fb = renderTargetContextData.framebuffers[ cacheKey ];
  48406. }
  48407. if ( fb === undefined ) {
  48408. fb = gl.createFramebuffer();
  48409. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  48410. const textures = descriptor.textures;
  48411. const depthInvalidationArray = [];
  48412. if ( isCube ) {
  48413. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  48414. const { textureGPU } = this.get( textures[ 0 ] );
  48415. const cubeFace = this.renderer._activeCubeFace;
  48416. const mipLevel = this.renderer._activeMipmapLevel;
  48417. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, mipLevel );
  48418. } else {
  48419. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  48420. for ( let i = 0; i < textures.length; i ++ ) {
  48421. const texture = textures[ i ];
  48422. const textureData = this.get( texture );
  48423. textureData.renderTarget = descriptor.renderTarget;
  48424. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  48425. const attachment = gl.COLOR_ATTACHMENT0 + i;
  48426. if ( renderTarget.multiview ) {
  48427. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  48428. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  48429. const layer = this.renderer._activeCubeFace;
  48430. const mipLevel = this.renderer._activeMipmapLevel;
  48431. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, mipLevel, layer );
  48432. } else {
  48433. if ( useMultisampledRTT ) {
  48434. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  48435. } else {
  48436. const mipLevel = this.renderer._activeMipmapLevel;
  48437. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, mipLevel );
  48438. }
  48439. }
  48440. }
  48441. }
  48442. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  48443. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  48444. const renderbuffer = gl.createRenderbuffer();
  48445. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  48446. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  48447. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  48448. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  48449. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  48450. } else {
  48451. if ( descriptor.depthTexture !== null ) {
  48452. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  48453. const textureData = this.get( descriptor.depthTexture );
  48454. textureData.renderTarget = descriptor.renderTarget;
  48455. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  48456. if ( renderTarget.multiview ) {
  48457. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  48458. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  48459. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  48460. } else {
  48461. if ( descriptor.depthTexture.isArrayTexture ) {
  48462. const layer = this.renderer._activeCubeFace;
  48463. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  48464. } else {
  48465. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  48466. }
  48467. }
  48468. }
  48469. }
  48470. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  48471. } else {
  48472. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  48473. if ( isRenderCameraDepthArray ) {
  48474. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  48475. const layer = this.renderer._activeCubeFace;
  48476. const depthData = this.get( descriptor.depthTexture );
  48477. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  48478. gl.framebufferTextureLayer(
  48479. gl.FRAMEBUFFER,
  48480. depthStyle,
  48481. depthData.textureGPU,
  48482. 0,
  48483. layer
  48484. );
  48485. }
  48486. // rebind external XR textures
  48487. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  48488. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  48489. // rebind color
  48490. const textureData = this.get( descriptor.textures[ 0 ] );
  48491. if ( renderTarget.multiview ) {
  48492. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  48493. } else if ( useMultisampledRTT ) {
  48494. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  48495. } else {
  48496. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  48497. }
  48498. // rebind depth
  48499. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  48500. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  48501. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  48502. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  48503. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  48504. } else {
  48505. const textureData = this.get( descriptor.depthTexture );
  48506. if ( renderTarget.multiview ) {
  48507. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  48508. } else if ( useMultisampledRTT ) {
  48509. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  48510. } else {
  48511. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  48512. }
  48513. }
  48514. }
  48515. }
  48516. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  48517. if ( msaaFb === undefined ) {
  48518. const invalidationArray = [];
  48519. msaaFb = gl.createFramebuffer();
  48520. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  48521. const msaaRenderbuffers = [];
  48522. const textures = descriptor.textures;
  48523. for ( let i = 0; i < textures.length; i ++ ) {
  48524. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  48525. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  48526. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  48527. const texture = descriptor.textures[ i ];
  48528. const textureData = this.get( texture );
  48529. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  48530. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  48531. }
  48532. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  48533. renderTargetContextData.msaaFrameBuffer = msaaFb;
  48534. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  48535. if ( depthBuffer && depthRenderbuffer === undefined ) {
  48536. depthRenderbuffer = gl.createRenderbuffer();
  48537. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  48538. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  48539. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  48540. invalidationArray.push( depthStyle );
  48541. }
  48542. renderTargetContextData.invalidationArray = invalidationArray;
  48543. }
  48544. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  48545. } else {
  48546. currentFrameBuffer = fb;
  48547. }
  48548. state.drawBuffers( descriptor, fb );
  48549. }
  48550. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  48551. }
  48552. /**
  48553. * Computes the VAO key for the given index and attributes.
  48554. *
  48555. * @private
  48556. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  48557. * @return {string} The VAO key.
  48558. */
  48559. _getVaoKey( attributes ) {
  48560. let key = '';
  48561. for ( let i = 0; i < attributes.length; i ++ ) {
  48562. const attributeData = this.get( attributes[ i ] );
  48563. key += ':' + attributeData.id;
  48564. }
  48565. return key;
  48566. }
  48567. /**
  48568. * Creates a VAO from the index and attributes.
  48569. *
  48570. * @private
  48571. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  48572. * @return {Object} The VAO data.
  48573. */
  48574. _createVao( attributes ) {
  48575. const { gl } = this;
  48576. const vaoGPU = gl.createVertexArray();
  48577. gl.bindVertexArray( vaoGPU );
  48578. for ( let i = 0; i < attributes.length; i ++ ) {
  48579. const attribute = attributes[ i ];
  48580. const attributeData = this.get( attribute );
  48581. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  48582. gl.enableVertexAttribArray( i );
  48583. let stride, offset;
  48584. if ( attribute.isInterleavedBufferAttribute === true ) {
  48585. stride = attribute.data.stride * attributeData.bytesPerElement;
  48586. offset = attribute.offset * attributeData.bytesPerElement;
  48587. } else {
  48588. stride = 0;
  48589. offset = 0;
  48590. }
  48591. if ( attributeData.isInteger ) {
  48592. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  48593. } else {
  48594. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  48595. }
  48596. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  48597. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  48598. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  48599. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  48600. }
  48601. }
  48602. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  48603. return vaoGPU;
  48604. }
  48605. /**
  48606. * Creates a transform feedback from the given transform buffers.
  48607. *
  48608. * @private
  48609. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  48610. * @return {WebGLTransformFeedback} The transform feedback.
  48611. */
  48612. _getTransformFeedback( transformBuffers ) {
  48613. let key = '';
  48614. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  48615. key += ':' + transformBuffers[ i ].id;
  48616. }
  48617. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  48618. if ( transformFeedbackGPU !== undefined ) {
  48619. return transformFeedbackGPU;
  48620. }
  48621. const { gl } = this;
  48622. transformFeedbackGPU = gl.createTransformFeedback();
  48623. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  48624. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  48625. const attributeData = transformBuffers[ i ];
  48626. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  48627. }
  48628. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  48629. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  48630. return transformFeedbackGPU;
  48631. }
  48632. /**
  48633. * Setups the given bindings.
  48634. *
  48635. * @private
  48636. * @param {Array<BindGroup>} bindings - The bindings.
  48637. * @param {WebGLProgram} programGPU - The WebGL program.
  48638. */
  48639. _setupBindings( bindings, programGPU ) {
  48640. const gl = this.gl;
  48641. for ( const bindGroup of bindings ) {
  48642. for ( const binding of bindGroup.bindings ) {
  48643. const bindingData = this.get( binding );
  48644. const index = bindingData.index;
  48645. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  48646. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  48647. gl.uniformBlockBinding( programGPU, location, index );
  48648. } else if ( binding.isSampledTexture ) {
  48649. const location = gl.getUniformLocation( programGPU, binding.name );
  48650. gl.uniform1i( location, index );
  48651. }
  48652. }
  48653. }
  48654. }
  48655. /**
  48656. * Binds the given uniforms.
  48657. *
  48658. * @private
  48659. * @param {Array<BindGroup>} bindings - The bindings.
  48660. */
  48661. _bindUniforms( bindings ) {
  48662. const { gl, state } = this;
  48663. for ( const bindGroup of bindings ) {
  48664. for ( const binding of bindGroup.bindings ) {
  48665. const bindingData = this.get( binding );
  48666. const index = bindingData.index;
  48667. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  48668. // TODO USE bindBufferRange to group multiple uniform buffers
  48669. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  48670. } else if ( binding.isSampledTexture ) {
  48671. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  48672. }
  48673. }
  48674. }
  48675. }
  48676. /**
  48677. * The method ensures multisampled render targets are resolved.
  48678. *
  48679. * @private
  48680. * @param {RenderContext} renderContext - The render context.
  48681. */
  48682. _resolveRenderTarget( renderContext ) {
  48683. const { gl, state } = this;
  48684. const renderTarget = renderContext.renderTarget;
  48685. if ( renderContext.textures !== null && renderTarget ) {
  48686. const renderTargetContextData = this.get( renderTarget );
  48687. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  48688. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  48689. let mask = gl.COLOR_BUFFER_BIT;
  48690. if ( renderTarget.resolveDepthBuffer ) {
  48691. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  48692. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  48693. }
  48694. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  48695. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  48696. const textures = renderContext.textures;
  48697. const isMRT = textures.length > 1;
  48698. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  48699. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  48700. if ( isMRT ) {
  48701. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  48702. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  48703. for ( let i = 0; i < textures.length; i ++ ) {
  48704. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  48705. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  48706. }
  48707. }
  48708. for ( let i = 0; i < textures.length; i ++ ) {
  48709. if ( isMRT ) {
  48710. // configure attachment for resolve
  48711. const { textureGPU } = this.get( textures[ i ] );
  48712. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  48713. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  48714. }
  48715. if ( renderContext.scissor ) {
  48716. const { x, y, width, height } = renderContext.scissorValue;
  48717. const viewY = renderContext.height - height - y;
  48718. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  48719. } else {
  48720. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  48721. }
  48722. }
  48723. if ( isMRT ) {
  48724. // restore attachments
  48725. for ( let i = 0; i < textures.length; i ++ ) {
  48726. const { textureGPU } = this.get( textures[ i ] );
  48727. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  48728. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  48729. }
  48730. }
  48731. if ( this._supportsInvalidateFramebuffer === true ) {
  48732. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  48733. }
  48734. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  48735. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  48736. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  48737. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  48738. }
  48739. }
  48740. }
  48741. /**
  48742. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  48743. * should be used when MSAA is enabled.
  48744. *
  48745. * @private
  48746. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  48747. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  48748. */
  48749. _useMultisampledExtension( renderTarget ) {
  48750. if ( renderTarget.multiview === true ) {
  48751. return true;
  48752. }
  48753. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  48754. }
  48755. /**
  48756. * Frees internal resources.
  48757. */
  48758. dispose() {
  48759. if ( this.textureUtils !== null ) this.textureUtils.dispose();
  48760. const extension = this.extensions.get( 'WEBGL_lose_context' );
  48761. if ( extension ) extension.loseContext();
  48762. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  48763. }
  48764. }
  48765. const GPUPrimitiveTopology = {
  48766. PointList: 'point-list',
  48767. LineList: 'line-list',
  48768. LineStrip: 'line-strip',
  48769. TriangleList: 'triangle-list',
  48770. TriangleStrip: 'triangle-strip',
  48771. };
  48772. const GPUCompareFunction = {
  48773. Never: 'never',
  48774. Less: 'less',
  48775. Equal: 'equal',
  48776. LessEqual: 'less-equal',
  48777. Greater: 'greater',
  48778. NotEqual: 'not-equal',
  48779. GreaterEqual: 'greater-equal',
  48780. Always: 'always'
  48781. };
  48782. const GPUStoreOp = {
  48783. Store: 'store'};
  48784. const GPULoadOp = {
  48785. Load: 'load',
  48786. Clear: 'clear'
  48787. };
  48788. const GPUFrontFace = {
  48789. CCW: 'ccw',
  48790. CW: 'cw'
  48791. };
  48792. const GPUCullMode = {
  48793. None: 'none',
  48794. Back: 'back'
  48795. };
  48796. const GPUIndexFormat = {
  48797. Uint16: 'uint16',
  48798. Uint32: 'uint32'
  48799. };
  48800. const GPUTextureFormat = {
  48801. // 8-bit formats
  48802. R8Unorm: 'r8unorm',
  48803. R8Snorm: 'r8snorm',
  48804. R8Uint: 'r8uint',
  48805. R8Sint: 'r8sint',
  48806. // 16-bit formats
  48807. R16Uint: 'r16uint',
  48808. R16Sint: 'r16sint',
  48809. R16Float: 'r16float',
  48810. RG8Unorm: 'rg8unorm',
  48811. RG8Snorm: 'rg8snorm',
  48812. RG8Uint: 'rg8uint',
  48813. RG8Sint: 'rg8sint',
  48814. // 32-bit formats
  48815. R32Uint: 'r32uint',
  48816. R32Sint: 'r32sint',
  48817. R32Float: 'r32float',
  48818. RG16Uint: 'rg16uint',
  48819. RG16Sint: 'rg16sint',
  48820. RG16Float: 'rg16float',
  48821. RGBA8Unorm: 'rgba8unorm',
  48822. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  48823. RGBA8Snorm: 'rgba8snorm',
  48824. RGBA8Uint: 'rgba8uint',
  48825. RGBA8Sint: 'rgba8sint',
  48826. BGRA8Unorm: 'bgra8unorm',
  48827. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  48828. // Packed 32-bit formats
  48829. RGB9E5UFloat: 'rgb9e5ufloat',
  48830. RGB10A2Unorm: 'rgb10a2unorm',
  48831. RG11B10UFloat: 'rg11b10ufloat',
  48832. // 64-bit formats
  48833. RG32Uint: 'rg32uint',
  48834. RG32Sint: 'rg32sint',
  48835. RG32Float: 'rg32float',
  48836. RGBA16Uint: 'rgba16uint',
  48837. RGBA16Sint: 'rgba16sint',
  48838. RGBA16Float: 'rgba16float',
  48839. // 128-bit formats
  48840. RGBA32Uint: 'rgba32uint',
  48841. RGBA32Sint: 'rgba32sint',
  48842. RGBA32Float: 'rgba32float',
  48843. Depth16Unorm: 'depth16unorm',
  48844. Depth24Plus: 'depth24plus',
  48845. Depth24PlusStencil8: 'depth24plus-stencil8',
  48846. Depth32Float: 'depth32float',
  48847. // 'depth32float-stencil8' extension
  48848. Depth32FloatStencil8: 'depth32float-stencil8',
  48849. // BC compressed formats usable if 'texture-compression-bc' is both
  48850. // supported by the device/user agent and enabled in requestDevice.
  48851. BC1RGBAUnorm: 'bc1-rgba-unorm',
  48852. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  48853. BC2RGBAUnorm: 'bc2-rgba-unorm',
  48854. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  48855. BC3RGBAUnorm: 'bc3-rgba-unorm',
  48856. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  48857. BC4RUnorm: 'bc4-r-unorm',
  48858. BC4RSnorm: 'bc4-r-snorm',
  48859. BC5RGUnorm: 'bc5-rg-unorm',
  48860. BC5RGSnorm: 'bc5-rg-snorm',
  48861. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  48862. BC6HRGBFloat: 'bc6h-rgb-float',
  48863. BC7RGBAUnorm: 'bc7-rgba-unorm',
  48864. BC7RGBAUnormSRGB: 'bc7-rgba-unorm-srgb',
  48865. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  48866. // supported by the device/user agent and enabled in requestDevice.
  48867. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  48868. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  48869. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  48870. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  48871. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  48872. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  48873. EACR11Unorm: 'eac-r11unorm',
  48874. EACR11Snorm: 'eac-r11snorm',
  48875. EACRG11Unorm: 'eac-rg11unorm',
  48876. EACRG11Snorm: 'eac-rg11snorm',
  48877. // ASTC compressed formats usable if 'texture-compression-astc' is both
  48878. // supported by the device/user agent and enabled in requestDevice.
  48879. ASTC4x4Unorm: 'astc-4x4-unorm',
  48880. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  48881. ASTC5x4Unorm: 'astc-5x4-unorm',
  48882. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  48883. ASTC5x5Unorm: 'astc-5x5-unorm',
  48884. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  48885. ASTC6x5Unorm: 'astc-6x5-unorm',
  48886. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  48887. ASTC6x6Unorm: 'astc-6x6-unorm',
  48888. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  48889. ASTC8x5Unorm: 'astc-8x5-unorm',
  48890. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  48891. ASTC8x6Unorm: 'astc-8x6-unorm',
  48892. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  48893. ASTC8x8Unorm: 'astc-8x8-unorm',
  48894. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  48895. ASTC10x5Unorm: 'astc-10x5-unorm',
  48896. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  48897. ASTC10x6Unorm: 'astc-10x6-unorm',
  48898. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  48899. ASTC10x8Unorm: 'astc-10x8-unorm',
  48900. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  48901. ASTC10x10Unorm: 'astc-10x10-unorm',
  48902. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  48903. ASTC12x10Unorm: 'astc-12x10-unorm',
  48904. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  48905. ASTC12x12Unorm: 'astc-12x12-unorm',
  48906. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  48907. };
  48908. const GPUAddressMode = {
  48909. ClampToEdge: 'clamp-to-edge',
  48910. Repeat: 'repeat',
  48911. MirrorRepeat: 'mirror-repeat'
  48912. };
  48913. const GPUFilterMode = {
  48914. Linear: 'linear',
  48915. Nearest: 'nearest'
  48916. };
  48917. const GPUBlendFactor = {
  48918. Zero: 'zero',
  48919. One: 'one',
  48920. Src: 'src',
  48921. OneMinusSrc: 'one-minus-src',
  48922. SrcAlpha: 'src-alpha',
  48923. OneMinusSrcAlpha: 'one-minus-src-alpha',
  48924. Dst: 'dst',
  48925. OneMinusDst: 'one-minus-dst',
  48926. DstAlpha: 'dst-alpha',
  48927. OneMinusDstAlpha: 'one-minus-dst-alpha',
  48928. SrcAlphaSaturated: 'src-alpha-saturated',
  48929. Constant: 'constant',
  48930. OneMinusConstant: 'one-minus-constant'
  48931. };
  48932. const GPUBlendOperation = {
  48933. Add: 'add',
  48934. Subtract: 'subtract',
  48935. ReverseSubtract: 'reverse-subtract',
  48936. Min: 'min',
  48937. Max: 'max'
  48938. };
  48939. const GPUColorWriteFlags = {
  48940. None: 0,
  48941. All: 0xF
  48942. };
  48943. const GPUStencilOperation = {
  48944. Keep: 'keep',
  48945. Zero: 'zero',
  48946. Replace: 'replace',
  48947. Invert: 'invert',
  48948. IncrementClamp: 'increment-clamp',
  48949. DecrementClamp: 'decrement-clamp',
  48950. IncrementWrap: 'increment-wrap',
  48951. DecrementWrap: 'decrement-wrap'
  48952. };
  48953. const GPUBufferBindingType = {
  48954. Storage: 'storage',
  48955. ReadOnlyStorage: 'read-only-storage'
  48956. };
  48957. const GPUStorageTextureAccess = {
  48958. WriteOnly: 'write-only',
  48959. ReadOnly: 'read-only',
  48960. ReadWrite: 'read-write',
  48961. };
  48962. const GPUSamplerBindingType = {
  48963. NonFiltering: 'non-filtering',
  48964. Comparison: 'comparison'
  48965. };
  48966. const GPUTextureSampleType = {
  48967. Float: 'float',
  48968. UnfilterableFloat: 'unfilterable-float',
  48969. Depth: 'depth',
  48970. SInt: 'sint',
  48971. UInt: 'uint'
  48972. };
  48973. const GPUTextureDimension = {
  48974. TwoD: '2d',
  48975. ThreeD: '3d'
  48976. };
  48977. const GPUTextureViewDimension = {
  48978. TwoD: '2d',
  48979. TwoDArray: '2d-array',
  48980. Cube: 'cube',
  48981. ThreeD: '3d'
  48982. };
  48983. const GPUTextureAspect = {
  48984. All: 'all'};
  48985. const GPUInputStepMode = {
  48986. Vertex: 'vertex',
  48987. Instance: 'instance'
  48988. };
  48989. const GPUFeatureName = {
  48990. CoreFeaturesAndLimits: 'core-features-and-limits',
  48991. DepthClipControl: 'depth-clip-control',
  48992. Depth32FloatStencil8: 'depth32float-stencil8',
  48993. TextureCompressionBC: 'texture-compression-bc',
  48994. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  48995. TextureCompressionETC2: 'texture-compression-etc2',
  48996. TextureCompressionASTC: 'texture-compression-astc',
  48997. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  48998. TimestampQuery: 'timestamp-query',
  48999. IndirectFirstInstance: 'indirect-first-instance',
  49000. ShaderF16: 'shader-f16',
  49001. RG11B10UFloat: 'rg11b10ufloat-renderable',
  49002. BGRA8UNormStorage: 'bgra8unorm-storage',
  49003. Float32Filterable: 'float32-filterable',
  49004. Float32Blendable: 'float32-blendable',
  49005. ClipDistances: 'clip-distances',
  49006. DualSourceBlending: 'dual-source-blending',
  49007. Subgroups: 'subgroups',
  49008. TextureFormatsTier1: 'texture-formats-tier1',
  49009. TextureFormatsTier2: 'texture-formats-tier2'
  49010. };
  49011. const GPUFeatureMap = {
  49012. 'texture-compression-s3tc': 'texture-compression-bc',
  49013. 'texture-compression-etc1': 'texture-compression-etc2'
  49014. };
  49015. /**
  49016. * A special form of sampler binding type.
  49017. * It's texture value is managed by a node object.
  49018. *
  49019. * @private
  49020. * @augments Sampler
  49021. */
  49022. class NodeSampler extends Sampler {
  49023. /**
  49024. * Constructs a new node-based sampler.
  49025. *
  49026. * @param {string} name - The samplers's name.
  49027. * @param {TextureNode} textureNode - The texture node.
  49028. * @param {UniformGroupNode} groupNode - The uniform group node.
  49029. */
  49030. constructor( name, textureNode, groupNode ) {
  49031. super( name, textureNode ? textureNode.value : null );
  49032. /**
  49033. * The texture node.
  49034. *
  49035. * @type {TextureNode}
  49036. */
  49037. this.textureNode = textureNode;
  49038. /**
  49039. * The uniform group node.
  49040. *
  49041. * @type {UniformGroupNode}
  49042. */
  49043. this.groupNode = groupNode;
  49044. }
  49045. /**
  49046. * Updates the texture value of this sampler.
  49047. *
  49048. * @return {boolean} Whether the sampler needs an update or not.
  49049. */
  49050. update() {
  49051. const { textureNode } = this;
  49052. if ( this.texture !== textureNode.value ) {
  49053. this.texture = textureNode.value;
  49054. return true;
  49055. }
  49056. return super.update();
  49057. }
  49058. }
  49059. /**
  49060. * Represents a storage buffer binding type.
  49061. *
  49062. * @private
  49063. * @augments Buffer
  49064. */
  49065. class StorageBuffer extends Buffer {
  49066. /**
  49067. * Constructs a new uniform buffer.
  49068. *
  49069. * @param {string} name - The buffer's name.
  49070. * @param {BufferAttribute} attribute - The buffer attribute.
  49071. */
  49072. constructor( name, attribute ) {
  49073. super( name, attribute ? attribute.array : null );
  49074. /**
  49075. * This flag can be used for type testing.
  49076. *
  49077. * @type {BufferAttribute}
  49078. */
  49079. this.attribute = attribute;
  49080. /**
  49081. * This flag can be used for type testing.
  49082. *
  49083. * @type {boolean}
  49084. * @readonly
  49085. * @default true
  49086. */
  49087. this.isStorageBuffer = true;
  49088. }
  49089. }
  49090. let _id = 0;
  49091. /**
  49092. * A special form of storage buffer binding type.
  49093. * It's buffer value is managed by a node object.
  49094. *
  49095. * @private
  49096. * @augments StorageBuffer
  49097. */
  49098. class NodeStorageBuffer extends StorageBuffer {
  49099. /**
  49100. * Constructs a new node-based storage buffer.
  49101. *
  49102. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  49103. * @param {UniformGroupNode} groupNode - The uniform group node.
  49104. */
  49105. constructor( nodeUniform, groupNode ) {
  49106. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  49107. /**
  49108. * The node uniform.
  49109. *
  49110. * @type {StorageBufferNode}
  49111. */
  49112. this.nodeUniform = nodeUniform;
  49113. /**
  49114. * The access type.
  49115. *
  49116. * @type {string}
  49117. */
  49118. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  49119. /**
  49120. * The uniform group node.
  49121. *
  49122. * @type {UniformGroupNode}
  49123. */
  49124. this.groupNode = groupNode;
  49125. }
  49126. /**
  49127. * The storage buffer.
  49128. *
  49129. * @type {BufferAttribute}
  49130. */
  49131. get buffer() {
  49132. return this.nodeUniform.value;
  49133. }
  49134. }
  49135. /**
  49136. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  49137. *
  49138. * @private
  49139. */
  49140. class WebGPUTexturePassUtils extends DataMap {
  49141. /**
  49142. * Constructs a new utility object.
  49143. *
  49144. * @param {GPUDevice} device - The WebGPU device.
  49145. */
  49146. constructor( device ) {
  49147. super();
  49148. /**
  49149. * The WebGPU device.
  49150. *
  49151. * @type {GPUDevice}
  49152. */
  49153. this.device = device;
  49154. const mipmapVertexSource = `
  49155. struct VarysStruct {
  49156. @builtin( position ) Position: vec4<f32>,
  49157. @location( 0 ) vTex : vec2<f32>
  49158. };
  49159. @vertex
  49160. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  49161. var Varys : VarysStruct;
  49162. var pos = array< vec2<f32>, 4 >(
  49163. vec2<f32>( -1.0, 1.0 ),
  49164. vec2<f32>( 1.0, 1.0 ),
  49165. vec2<f32>( -1.0, -1.0 ),
  49166. vec2<f32>( 1.0, -1.0 )
  49167. );
  49168. var tex = array< vec2<f32>, 4 >(
  49169. vec2<f32>( 0.0, 0.0 ),
  49170. vec2<f32>( 1.0, 0.0 ),
  49171. vec2<f32>( 0.0, 1.0 ),
  49172. vec2<f32>( 1.0, 1.0 )
  49173. );
  49174. Varys.vTex = tex[ vertexIndex ];
  49175. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  49176. return Varys;
  49177. }
  49178. `;
  49179. const mipmapFragmentSource = `
  49180. @group( 0 ) @binding( 0 )
  49181. var imgSampler : sampler;
  49182. @group( 0 ) @binding( 1 )
  49183. var img : texture_2d<f32>;
  49184. @fragment
  49185. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  49186. return textureSample( img, imgSampler, vTex );
  49187. }
  49188. `;
  49189. const flipYFragmentSource = `
  49190. @group( 0 ) @binding( 0 )
  49191. var imgSampler : sampler;
  49192. @group( 0 ) @binding( 1 )
  49193. var img : texture_2d<f32>;
  49194. @fragment
  49195. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  49196. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  49197. }
  49198. `;
  49199. /**
  49200. * The mipmap GPU sampler.
  49201. *
  49202. * @type {GPUSampler}
  49203. */
  49204. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  49205. /**
  49206. * The flipY GPU sampler.
  49207. *
  49208. * @type {GPUSampler}
  49209. */
  49210. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  49211. /**
  49212. * A cache for GPU render pipelines used for copy/transfer passes.
  49213. * Every texture format requires a unique pipeline.
  49214. *
  49215. * @type {Object<string,GPURenderPipeline>}
  49216. */
  49217. this.transferPipelines = {};
  49218. /**
  49219. * A cache for GPU render pipelines used for flipY passes.
  49220. * Every texture format requires a unique pipeline.
  49221. *
  49222. * @type {Object<string,GPURenderPipeline>}
  49223. */
  49224. this.flipYPipelines = {};
  49225. /**
  49226. * The mipmap vertex shader module.
  49227. *
  49228. * @type {GPUShaderModule}
  49229. */
  49230. this.mipmapVertexShaderModule = device.createShaderModule( {
  49231. label: 'mipmapVertex',
  49232. code: mipmapVertexSource
  49233. } );
  49234. /**
  49235. * The mipmap fragment shader module.
  49236. *
  49237. * @type {GPUShaderModule}
  49238. */
  49239. this.mipmapFragmentShaderModule = device.createShaderModule( {
  49240. label: 'mipmapFragment',
  49241. code: mipmapFragmentSource
  49242. } );
  49243. /**
  49244. * The flipY fragment shader module.
  49245. *
  49246. * @type {GPUShaderModule}
  49247. */
  49248. this.flipYFragmentShaderModule = device.createShaderModule( {
  49249. label: 'flipYFragment',
  49250. code: flipYFragmentSource
  49251. } );
  49252. }
  49253. /**
  49254. * Returns a render pipeline for the internal copy render pass. The pass
  49255. * requires a unique render pipeline for each texture format.
  49256. *
  49257. * @param {string} format - The GPU texture format
  49258. * @return {GPURenderPipeline} The GPU render pipeline.
  49259. */
  49260. getTransferPipeline( format ) {
  49261. let pipeline = this.transferPipelines[ format ];
  49262. if ( pipeline === undefined ) {
  49263. pipeline = this.device.createRenderPipeline( {
  49264. label: `mipmap-${ format }`,
  49265. vertex: {
  49266. module: this.mipmapVertexShaderModule,
  49267. entryPoint: 'main'
  49268. },
  49269. fragment: {
  49270. module: this.mipmapFragmentShaderModule,
  49271. entryPoint: 'main',
  49272. targets: [ { format } ]
  49273. },
  49274. primitive: {
  49275. topology: GPUPrimitiveTopology.TriangleStrip,
  49276. stripIndexFormat: GPUIndexFormat.Uint32
  49277. },
  49278. layout: 'auto'
  49279. } );
  49280. this.transferPipelines[ format ] = pipeline;
  49281. }
  49282. return pipeline;
  49283. }
  49284. /**
  49285. * Returns a render pipeline for the flipY render pass. The pass
  49286. * requires a unique render pipeline for each texture format.
  49287. *
  49288. * @param {string} format - The GPU texture format
  49289. * @return {GPURenderPipeline} The GPU render pipeline.
  49290. */
  49291. getFlipYPipeline( format ) {
  49292. let pipeline = this.flipYPipelines[ format ];
  49293. if ( pipeline === undefined ) {
  49294. pipeline = this.device.createRenderPipeline( {
  49295. label: `flipY-${ format }`,
  49296. vertex: {
  49297. module: this.mipmapVertexShaderModule,
  49298. entryPoint: 'main'
  49299. },
  49300. fragment: {
  49301. module: this.flipYFragmentShaderModule,
  49302. entryPoint: 'main',
  49303. targets: [ { format } ]
  49304. },
  49305. primitive: {
  49306. topology: GPUPrimitiveTopology.TriangleStrip,
  49307. stripIndexFormat: GPUIndexFormat.Uint32
  49308. },
  49309. layout: 'auto'
  49310. } );
  49311. this.flipYPipelines[ format ] = pipeline;
  49312. }
  49313. return pipeline;
  49314. }
  49315. /**
  49316. * Flip the contents of the given GPU texture along its vertical axis.
  49317. *
  49318. * @param {GPUTexture} textureGPU - The GPU texture object.
  49319. * @param {Object} textureGPUDescriptor - The texture descriptor.
  49320. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  49321. */
  49322. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  49323. const format = textureGPUDescriptor.format;
  49324. const { width, height } = textureGPUDescriptor.size;
  49325. const transferPipeline = this.getTransferPipeline( format );
  49326. const flipYPipeline = this.getFlipYPipeline( format );
  49327. const tempTexture = this.device.createTexture( {
  49328. size: { width, height, depthOrArrayLayers: 1 },
  49329. format,
  49330. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  49331. } );
  49332. const srcView = textureGPU.createView( {
  49333. baseMipLevel: 0,
  49334. mipLevelCount: 1,
  49335. dimension: GPUTextureViewDimension.TwoD,
  49336. baseArrayLayer
  49337. } );
  49338. const dstView = tempTexture.createView( {
  49339. baseMipLevel: 0,
  49340. mipLevelCount: 1,
  49341. dimension: GPUTextureViewDimension.TwoD,
  49342. baseArrayLayer: 0
  49343. } );
  49344. const commandEncoder = this.device.createCommandEncoder( {} );
  49345. const pass = ( pipeline, sourceView, destinationView ) => {
  49346. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  49347. const bindGroup = this.device.createBindGroup( {
  49348. layout: bindGroupLayout,
  49349. entries: [ {
  49350. binding: 0,
  49351. resource: this.flipYSampler
  49352. }, {
  49353. binding: 1,
  49354. resource: sourceView
  49355. } ]
  49356. } );
  49357. const passEncoder = commandEncoder.beginRenderPass( {
  49358. colorAttachments: [ {
  49359. view: destinationView,
  49360. loadOp: GPULoadOp.Clear,
  49361. storeOp: GPUStoreOp.Store,
  49362. clearValue: [ 0, 0, 0, 0 ]
  49363. } ]
  49364. } );
  49365. passEncoder.setPipeline( pipeline );
  49366. passEncoder.setBindGroup( 0, bindGroup );
  49367. passEncoder.draw( 4, 1, 0, 0 );
  49368. passEncoder.end();
  49369. };
  49370. pass( transferPipeline, srcView, dstView );
  49371. pass( flipYPipeline, dstView, srcView );
  49372. this.device.queue.submit( [ commandEncoder.finish() ] );
  49373. tempTexture.destroy();
  49374. }
  49375. /**
  49376. * Generates mipmaps for the given GPU texture.
  49377. *
  49378. * @param {GPUTexture} textureGPU - The GPU texture object.
  49379. * @param {Object} textureGPUDescriptor - The texture descriptor.
  49380. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  49381. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  49382. */
  49383. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0, encoder = null ) {
  49384. const textureData = this.get( textureGPU );
  49385. if ( textureData.layers === undefined ) {
  49386. textureData.layers = [];
  49387. }
  49388. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  49389. const commandEncoder = encoder || this.device.createCommandEncoder( { label: 'mipmapEncoder' } );
  49390. this._mipmapRunBundles( commandEncoder, passes );
  49391. if ( encoder === null ) this.device.queue.submit( [ commandEncoder.finish() ] );
  49392. textureData.layers[ baseArrayLayer ] = passes;
  49393. }
  49394. /**
  49395. * Since multiple copy render passes are required to generate mipmaps, the passes
  49396. * are managed as render bundles to improve performance.
  49397. *
  49398. * @param {GPUTexture} textureGPU - The GPU texture object.
  49399. * @param {Object} textureGPUDescriptor - The texture descriptor.
  49400. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  49401. * @return {Array<Object>} An array of render bundles.
  49402. */
  49403. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  49404. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  49405. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  49406. let srcView = textureGPU.createView( {
  49407. baseMipLevel: 0,
  49408. mipLevelCount: 1,
  49409. dimension: GPUTextureViewDimension.TwoD,
  49410. baseArrayLayer
  49411. } );
  49412. const passes = [];
  49413. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  49414. const bindGroup = this.device.createBindGroup( {
  49415. layout: bindGroupLayout,
  49416. entries: [ {
  49417. binding: 0,
  49418. resource: this.mipmapSampler
  49419. }, {
  49420. binding: 1,
  49421. resource: srcView
  49422. } ]
  49423. } );
  49424. const dstView = textureGPU.createView( {
  49425. baseMipLevel: i,
  49426. mipLevelCount: 1,
  49427. dimension: GPUTextureViewDimension.TwoD,
  49428. baseArrayLayer
  49429. } );
  49430. const passDescriptor = {
  49431. colorAttachments: [ {
  49432. view: dstView,
  49433. loadOp: GPULoadOp.Clear,
  49434. storeOp: GPUStoreOp.Store,
  49435. clearValue: [ 0, 0, 0, 0 ]
  49436. } ]
  49437. };
  49438. const passEncoder = this.device.createRenderBundleEncoder( {
  49439. colorFormats: [ textureGPUDescriptor.format ]
  49440. } );
  49441. passEncoder.setPipeline( pipeline );
  49442. passEncoder.setBindGroup( 0, bindGroup );
  49443. passEncoder.draw( 4, 1, 0, 0 );
  49444. passes.push( {
  49445. renderBundles: [ passEncoder.finish() ],
  49446. passDescriptor
  49447. } );
  49448. srcView = dstView;
  49449. }
  49450. return passes;
  49451. }
  49452. /**
  49453. * Executes the render bundles.
  49454. *
  49455. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  49456. * @param {Array<Object>} passes - An array of render bundles.
  49457. */
  49458. _mipmapRunBundles( commandEncoder, passes ) {
  49459. const levels = passes.length;
  49460. for ( let i = 0; i < levels; i ++ ) {
  49461. const pass = passes[ i ];
  49462. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  49463. passEncoder.executeBundles( pass.renderBundles );
  49464. passEncoder.end();
  49465. }
  49466. }
  49467. }
  49468. const _compareToWebGPU = {
  49469. [ NeverCompare ]: 'never',
  49470. [ LessCompare ]: 'less',
  49471. [ EqualCompare ]: 'equal',
  49472. [ LessEqualCompare ]: 'less-equal',
  49473. [ GreaterCompare ]: 'greater',
  49474. [ GreaterEqualCompare ]: 'greater-equal',
  49475. [ AlwaysCompare ]: 'always',
  49476. [ NotEqualCompare ]: 'not-equal'
  49477. };
  49478. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  49479. /**
  49480. * A WebGPU backend utility module for managing textures.
  49481. *
  49482. * @private
  49483. */
  49484. class WebGPUTextureUtils {
  49485. /**
  49486. * Constructs a new utility object.
  49487. *
  49488. * @param {WebGPUBackend} backend - The WebGPU backend.
  49489. */
  49490. constructor( backend ) {
  49491. /**
  49492. * A reference to the WebGPU backend.
  49493. *
  49494. * @type {WebGPUBackend}
  49495. */
  49496. this.backend = backend;
  49497. /**
  49498. * A reference to the pass utils.
  49499. *
  49500. * @type {?WebGPUTexturePassUtils}
  49501. * @default null
  49502. */
  49503. this._passUtils = null;
  49504. /**
  49505. * A dictionary for managing default textures. The key
  49506. * is the texture format, the value the texture object.
  49507. *
  49508. * @type {Object<string,Texture>}
  49509. */
  49510. this.defaultTexture = {};
  49511. /**
  49512. * A dictionary for managing default cube textures. The key
  49513. * is the texture format, the value the texture object.
  49514. *
  49515. * @type {Object<string,CubeTexture>}
  49516. */
  49517. this.defaultCubeTexture = {};
  49518. /**
  49519. * A default video frame.
  49520. *
  49521. * @type {?VideoFrame}
  49522. * @default null
  49523. */
  49524. this.defaultVideoFrame = null;
  49525. /**
  49526. * A cache of shared texture samplers.
  49527. *
  49528. * @type {Map<string, Object>}
  49529. */
  49530. this._samplerCache = new Map();
  49531. }
  49532. /**
  49533. * Creates a GPU sampler for the given texture.
  49534. *
  49535. * @param {Texture} texture - The texture to create the sampler for.
  49536. * @return {string} The current sampler key.
  49537. */
  49538. updateSampler( texture ) {
  49539. const backend = this.backend;
  49540. const samplerKey = texture.minFilter + '-' + texture.magFilter + '-' +
  49541. texture.wrapS + '-' + texture.wrapT + '-' + ( texture.wrapR || '0' ) + '-' +
  49542. texture.anisotropy + '-' + ( texture.compareFunction || 0 );
  49543. let samplerData = this._samplerCache.get( samplerKey );
  49544. if ( samplerData === undefined ) {
  49545. const samplerDescriptorGPU = {
  49546. addressModeU: this._convertAddressMode( texture.wrapS ),
  49547. addressModeV: this._convertAddressMode( texture.wrapT ),
  49548. addressModeW: this._convertAddressMode( texture.wrapR ),
  49549. magFilter: this._convertFilterMode( texture.magFilter ),
  49550. minFilter: this._convertFilterMode( texture.minFilter ),
  49551. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  49552. maxAnisotropy: 1
  49553. };
  49554. // anisotropy can only be used when all filter modes are set to linear.
  49555. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  49556. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  49557. }
  49558. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  49559. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  49560. }
  49561. const sampler = backend.device.createSampler( samplerDescriptorGPU );
  49562. samplerData = { sampler, usedTimes: 0 };
  49563. this._samplerCache.set( samplerKey, samplerData );
  49564. }
  49565. const textureData = backend.get( texture );
  49566. if ( textureData.sampler !== samplerData.sampler ) {
  49567. // check if previous sampler is unused so it can be deleted
  49568. if ( textureData.sampler !== undefined ) {
  49569. const oldSamplerData = this._samplerCache.get( textureData.samplerKey );
  49570. oldSamplerData.usedTimes --;
  49571. if ( oldSamplerData.usedTimes === 0 ) {
  49572. this._samplerCache.delete( textureData.samplerKey );
  49573. }
  49574. }
  49575. // update to new sampler data
  49576. textureData.samplerKey = samplerKey;
  49577. textureData.sampler = samplerData.sampler;
  49578. samplerData.usedTimes ++;
  49579. }
  49580. return samplerKey;
  49581. }
  49582. /**
  49583. * Creates a default texture for the given texture that can be used
  49584. * as a placeholder until the actual texture is ready for usage.
  49585. *
  49586. * @param {Texture} texture - The texture to create a default texture for.
  49587. */
  49588. createDefaultTexture( texture ) {
  49589. let textureGPU;
  49590. const format = getFormat( texture );
  49591. if ( texture.isCubeTexture ) {
  49592. textureGPU = this._getDefaultCubeTextureGPU( format );
  49593. } else {
  49594. textureGPU = this._getDefaultTextureGPU( format );
  49595. }
  49596. this.backend.get( texture ).texture = textureGPU;
  49597. }
  49598. /**
  49599. * Defines a texture on the GPU for the given texture object.
  49600. *
  49601. * @param {Texture} texture - The texture.
  49602. * @param {Object} [options={}] - Optional configuration parameter.
  49603. */
  49604. createTexture( texture, options = {} ) {
  49605. const backend = this.backend;
  49606. const textureData = backend.get( texture );
  49607. if ( textureData.initialized ) {
  49608. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  49609. }
  49610. if ( texture.isExternalTexture ) {
  49611. textureData.texture = texture.sourceTexture;
  49612. textureData.initialized = true;
  49613. return;
  49614. }
  49615. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  49616. if ( options.levels === undefined ) options.levels = 1;
  49617. if ( options.depth === undefined ) options.depth = 1;
  49618. const { width, height, depth, levels } = options;
  49619. if ( texture.isFramebufferTexture ) {
  49620. if ( options.renderTarget ) {
  49621. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  49622. } else {
  49623. options.format = this.backend.utils.getPreferredCanvasFormat();
  49624. }
  49625. }
  49626. const dimension = this._getDimension( texture );
  49627. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  49628. textureData.format = format;
  49629. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  49630. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  49631. if ( texture.isStorageTexture === true ) {
  49632. usage |= GPUTextureUsage.STORAGE_BINDING;
  49633. }
  49634. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true && format !== GPUTextureFormat.RGB9E5UFloat ) {
  49635. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  49636. }
  49637. const textureDescriptorGPU = {
  49638. label: texture.name,
  49639. size: {
  49640. width: width,
  49641. height: height,
  49642. depthOrArrayLayers: depth,
  49643. },
  49644. mipLevelCount: levels,
  49645. sampleCount: primarySamples,
  49646. dimension: dimension,
  49647. format: format,
  49648. usage: usage
  49649. };
  49650. // texture creation
  49651. if ( format === undefined ) {
  49652. warn( 'WebGPURenderer: Texture format not supported.' );
  49653. this.createDefaultTexture( texture );
  49654. return;
  49655. }
  49656. if ( texture.isCubeTexture ) {
  49657. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  49658. }
  49659. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  49660. if ( isMSAA ) {
  49661. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  49662. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  49663. msaaTextureDescriptorGPU.sampleCount = samples;
  49664. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  49665. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  49666. }
  49667. textureData.initialized = true;
  49668. textureData.textureDescriptorGPU = textureDescriptorGPU;
  49669. }
  49670. /**
  49671. * Destroys the GPU data for the given texture object.
  49672. *
  49673. * @param {Texture} texture - The texture.
  49674. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  49675. */
  49676. destroyTexture( texture, isDefaultTexture = false ) {
  49677. const backend = this.backend;
  49678. const textureData = backend.get( texture );
  49679. if ( textureData.texture !== undefined && isDefaultTexture === false ) textureData.texture.destroy();
  49680. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  49681. backend.delete( texture );
  49682. }
  49683. /**
  49684. * Generates mipmaps for the given texture.
  49685. *
  49686. * @param {Texture} texture - The texture.
  49687. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  49688. */
  49689. generateMipmaps( texture, encoder = null ) {
  49690. const textureData = this.backend.get( texture );
  49691. if ( texture.isCubeTexture ) {
  49692. for ( let i = 0; i < 6; i ++ ) {
  49693. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i, encoder );
  49694. }
  49695. } else {
  49696. const depth = texture.image.depth || 1;
  49697. for ( let i = 0; i < depth; i ++ ) {
  49698. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i, encoder );
  49699. }
  49700. }
  49701. }
  49702. /**
  49703. * Returns the color buffer representing the color
  49704. * attachment of the default framebuffer.
  49705. *
  49706. * @return {GPUTexture} The color buffer.
  49707. */
  49708. getColorBuffer() {
  49709. const backend = this.backend;
  49710. const canvasTarget = backend.renderer.getCanvasTarget();
  49711. const { width, height } = backend.getDrawingBufferSize();
  49712. const samples = backend.renderer.currentSamples;
  49713. const colorTexture = canvasTarget.colorTexture;
  49714. const colorTextureData = backend.get( colorTexture );
  49715. if ( colorTexture.width === width && colorTexture.height === height && colorTexture.samples === samples ) {
  49716. return colorTextureData.texture;
  49717. }
  49718. // recreate
  49719. let colorBuffer = colorTextureData.texture;
  49720. if ( colorBuffer ) colorBuffer.destroy();
  49721. colorBuffer = backend.device.createTexture( {
  49722. label: 'colorBuffer',
  49723. size: {
  49724. width: width,
  49725. height: height,
  49726. depthOrArrayLayers: 1
  49727. },
  49728. sampleCount: backend.utils.getSampleCount( backend.renderer.currentSamples ),
  49729. format: backend.utils.getPreferredCanvasFormat(),
  49730. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  49731. } );
  49732. //
  49733. colorTexture.source.width = width;
  49734. colorTexture.source.height = height;
  49735. colorTexture.samples = samples;
  49736. colorTextureData.texture = colorBuffer;
  49737. return colorBuffer;
  49738. }
  49739. /**
  49740. * Returns the depth buffer representing the depth
  49741. * attachment of the default framebuffer.
  49742. *
  49743. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  49744. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  49745. * @return {GPUTexture} The depth buffer.
  49746. */
  49747. getDepthBuffer( depth = true, stencil = false ) {
  49748. const backend = this.backend;
  49749. const canvasTarget = backend.renderer.getCanvasTarget();
  49750. const { width, height } = backend.getDrawingBufferSize();
  49751. const samples = backend.renderer.currentSamples;
  49752. const depthTexture = canvasTarget.depthTexture;
  49753. if ( depthTexture.width === width &&
  49754. depthTexture.height === height &&
  49755. depthTexture.samples === samples &&
  49756. depthTexture.depth === depth &&
  49757. depthTexture.stencil === stencil ) {
  49758. return backend.get( depthTexture ).texture;
  49759. }
  49760. //
  49761. const depthTextureGPU = backend.get( depthTexture ).texture;
  49762. let format, type;
  49763. if ( stencil ) {
  49764. format = DepthStencilFormat;
  49765. type = UnsignedInt248Type;
  49766. } else if ( depth ) {
  49767. format = DepthFormat;
  49768. type = UnsignedIntType;
  49769. }
  49770. if ( depthTextureGPU !== undefined ) {
  49771. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type && depthTexture.samples === samples ) {
  49772. return depthTextureGPU;
  49773. }
  49774. this.destroyTexture( depthTexture );
  49775. }
  49776. // recreate
  49777. depthTexture.name = 'depthBuffer';
  49778. depthTexture.format = format;
  49779. depthTexture.type = type;
  49780. depthTexture.image.width = width;
  49781. depthTexture.image.height = height;
  49782. depthTexture.samples = samples;
  49783. this.createTexture( depthTexture, { width, height } );
  49784. return backend.get( depthTexture ).texture;
  49785. }
  49786. /**
  49787. * Uploads the updated texture data to the GPU.
  49788. *
  49789. * @param {Texture} texture - The texture.
  49790. * @param {Object} [options={}] - Optional configuration parameter.
  49791. */
  49792. updateTexture( texture, options ) {
  49793. const textureData = this.backend.get( texture );
  49794. const mipmaps = texture.mipmaps;
  49795. const { textureDescriptorGPU } = textureData;
  49796. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  49797. return;
  49798. // transfer texture data
  49799. if ( texture.isDataTexture ) {
  49800. if ( mipmaps.length > 0 ) {
  49801. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49802. const mipmap = mipmaps[ i ];
  49803. this._copyBufferToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, 0, i );
  49804. }
  49805. } else {
  49806. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  49807. }
  49808. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  49809. for ( let i = 0; i < options.image.depth; i ++ ) {
  49810. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  49811. }
  49812. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  49813. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  49814. } else if ( texture.isCubeTexture ) {
  49815. this._copyCubeMapToTexture( texture, textureData.texture, textureDescriptorGPU );
  49816. } else {
  49817. if ( mipmaps.length > 0 ) {
  49818. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49819. const mipmap = mipmaps[ i ];
  49820. this._copyImageToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha, i );
  49821. }
  49822. } else {
  49823. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  49824. }
  49825. }
  49826. //
  49827. textureData.version = texture.version;
  49828. }
  49829. /**
  49830. * Returns texture data as a typed array.
  49831. *
  49832. * @async
  49833. * @param {Texture} texture - The texture to copy.
  49834. * @param {number} x - The x coordinate of the copy origin.
  49835. * @param {number} y - The y coordinate of the copy origin.
  49836. * @param {number} width - The width of the copy.
  49837. * @param {number} height - The height of the copy.
  49838. * @param {number} faceIndex - The face index.
  49839. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  49840. */
  49841. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  49842. const device = this.backend.device;
  49843. const textureData = this.backend.get( texture );
  49844. const textureGPU = textureData.texture;
  49845. const format = textureData.textureDescriptorGPU.format;
  49846. const bytesPerTexel = this._getBytesPerTexel( format );
  49847. let bytesPerRow = width * bytesPerTexel;
  49848. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  49849. const readBuffer = device.createBuffer(
  49850. {
  49851. size: ( ( height - 1 ) * bytesPerRow ) + ( width * bytesPerTexel ), // see https://github.com/mrdoob/three.js/issues/31658#issuecomment-3229442010
  49852. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  49853. }
  49854. );
  49855. const encoder = device.createCommandEncoder();
  49856. encoder.copyTextureToBuffer(
  49857. {
  49858. texture: textureGPU,
  49859. origin: { x, y, z: faceIndex },
  49860. },
  49861. {
  49862. buffer: readBuffer,
  49863. bytesPerRow: bytesPerRow
  49864. },
  49865. {
  49866. width: width,
  49867. height: height
  49868. }
  49869. );
  49870. const typedArrayType = this._getTypedArrayType( format );
  49871. device.queue.submit( [ encoder.finish() ] );
  49872. await readBuffer.mapAsync( GPUMapMode.READ );
  49873. const buffer = readBuffer.getMappedRange();
  49874. return new typedArrayType( buffer );
  49875. }
  49876. /**
  49877. * Frees all internal resources.
  49878. */
  49879. dispose() {
  49880. this._samplerCache.clear();
  49881. }
  49882. /**
  49883. * Returns the default GPU texture for the given format.
  49884. *
  49885. * @private
  49886. * @param {string} format - The GPU format.
  49887. * @return {GPUTexture} The GPU texture.
  49888. */
  49889. _getDefaultTextureGPU( format ) {
  49890. let defaultTexture = this.defaultTexture[ format ];
  49891. if ( defaultTexture === undefined ) {
  49892. const texture = new Texture();
  49893. texture.minFilter = NearestFilter;
  49894. texture.magFilter = NearestFilter;
  49895. this.createTexture( texture, { width: 1, height: 1, format } );
  49896. this.defaultTexture[ format ] = defaultTexture = texture;
  49897. }
  49898. return this.backend.get( defaultTexture ).texture;
  49899. }
  49900. /**
  49901. * Returns the default GPU cube texture for the given format.
  49902. *
  49903. * @private
  49904. * @param {string} format - The GPU format.
  49905. * @return {GPUTexture} The GPU texture.
  49906. */
  49907. _getDefaultCubeTextureGPU( format ) {
  49908. let defaultCubeTexture = this.defaultTexture[ format ];
  49909. if ( defaultCubeTexture === undefined ) {
  49910. const texture = new CubeTexture();
  49911. texture.minFilter = NearestFilter;
  49912. texture.magFilter = NearestFilter;
  49913. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  49914. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  49915. }
  49916. return this.backend.get( defaultCubeTexture ).texture;
  49917. }
  49918. /**
  49919. * Uploads cube texture image data to the GPU memory.
  49920. *
  49921. * @private
  49922. * @param {CubeTexture} texture - The cube texture.
  49923. * @param {GPUTexture} textureGPU - The GPU texture.
  49924. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  49925. */
  49926. _copyCubeMapToTexture( texture, textureGPU, textureDescriptorGPU ) {
  49927. const images = texture.images;
  49928. const mipmaps = texture.mipmaps;
  49929. for ( let i = 0; i < 6; i ++ ) {
  49930. const image = images[ i ];
  49931. const flipIndex = texture.flipY === true ? _flipMap[ i ] : i;
  49932. if ( image.isDataTexture ) {
  49933. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY );
  49934. } else {
  49935. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha );
  49936. }
  49937. for ( let j = 0; j < mipmaps.length; j ++ ) {
  49938. const mipmap = mipmaps[ j ];
  49939. const image = mipmap.images[ i ];
  49940. if ( image.isDataTexture ) {
  49941. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, 0, j + 1 );
  49942. } else {
  49943. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha, j + 1 );
  49944. }
  49945. }
  49946. }
  49947. }
  49948. /**
  49949. * Uploads texture image data to the GPU memory.
  49950. *
  49951. * @private
  49952. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  49953. * @param {GPUTexture} textureGPU - The GPU texture.
  49954. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  49955. * @param {number} originDepth - The origin depth.
  49956. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  49957. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  49958. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  49959. */
  49960. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha, mipLevel = 0 ) {
  49961. const device = this.backend.device;
  49962. const width = ( mipLevel > 0 ) ? image.width : textureDescriptorGPU.size.width;
  49963. const height = ( mipLevel > 0 ) ? image.height : textureDescriptorGPU.size.height;
  49964. device.queue.copyExternalImageToTexture(
  49965. {
  49966. source: image,
  49967. flipY: flipY
  49968. }, {
  49969. texture: textureGPU,
  49970. mipLevel: mipLevel,
  49971. origin: { x: 0, y: 0, z: originDepth },
  49972. premultipliedAlpha: premultiplyAlpha
  49973. }, {
  49974. width: width,
  49975. height: height,
  49976. depthOrArrayLayers: 1
  49977. }
  49978. );
  49979. }
  49980. /**
  49981. * Returns the pass utils singleton.
  49982. *
  49983. * @private
  49984. * @return {WebGPUTexturePassUtils} The utils instance.
  49985. */
  49986. _getPassUtils() {
  49987. let passUtils = this._passUtils;
  49988. if ( passUtils === null ) {
  49989. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  49990. }
  49991. return passUtils;
  49992. }
  49993. /**
  49994. * Generates mipmaps for the given GPU texture.
  49995. *
  49996. * @private
  49997. * @param {GPUTexture} textureGPU - The GPU texture object.
  49998. * @param {Object} textureDescriptorGPU - The texture descriptor.
  49999. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  50000. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  50001. */
  50002. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0, encoder = null ) {
  50003. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer, encoder );
  50004. }
  50005. /**
  50006. * Flip the contents of the given GPU texture along its vertical axis.
  50007. *
  50008. * @private
  50009. * @param {GPUTexture} textureGPU - The GPU texture object.
  50010. * @param {Object} textureDescriptorGPU - The texture descriptor.
  50011. * @param {number} [originDepth=0] - The origin depth.
  50012. */
  50013. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  50014. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  50015. }
  50016. /**
  50017. * Uploads texture buffer data to the GPU memory.
  50018. *
  50019. * @private
  50020. * @param {Object} image - An object defining the image buffer data.
  50021. * @param {GPUTexture} textureGPU - The GPU texture.
  50022. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  50023. * @param {number} originDepth - The origin depth.
  50024. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  50025. * @param {number} [depth=0] - The depth offset when copying array or 3D texture data.
  50026. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  50027. */
  50028. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0, mipLevel = 0 ) {
  50029. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  50030. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  50031. const device = this.backend.device;
  50032. const data = image.data;
  50033. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  50034. const bytesPerRow = image.width * bytesPerTexel;
  50035. device.queue.writeTexture(
  50036. {
  50037. texture: textureGPU,
  50038. mipLevel: mipLevel,
  50039. origin: { x: 0, y: 0, z: originDepth }
  50040. },
  50041. data,
  50042. {
  50043. offset: image.width * image.height * bytesPerTexel * depth,
  50044. bytesPerRow
  50045. },
  50046. {
  50047. width: image.width,
  50048. height: image.height,
  50049. depthOrArrayLayers: 1
  50050. } );
  50051. if ( flipY === true ) {
  50052. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  50053. }
  50054. }
  50055. /**
  50056. * Uploads compressed texture data to the GPU memory.
  50057. *
  50058. * @private
  50059. * @param {Array<Object>} mipmaps - An array with mipmap data.
  50060. * @param {GPUTexture} textureGPU - The GPU texture.
  50061. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  50062. */
  50063. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  50064. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  50065. const device = this.backend.device;
  50066. const blockData = this._getBlockData( textureDescriptorGPU.format );
  50067. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  50068. for ( let i = 0; i < mipmaps.length; i ++ ) {
  50069. const mipmap = mipmaps[ i ];
  50070. const width = mipmap.width;
  50071. const height = mipmap.height;
  50072. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  50073. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  50074. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  50075. for ( let j = 0; j < depth; j ++ ) {
  50076. device.queue.writeTexture(
  50077. {
  50078. texture: textureGPU,
  50079. mipLevel: i,
  50080. origin: { x: 0, y: 0, z: j }
  50081. },
  50082. mipmap.data,
  50083. {
  50084. offset: j * bytesPerImage,
  50085. bytesPerRow,
  50086. rowsPerImage: Math.ceil( height / blockData.height )
  50087. },
  50088. {
  50089. width: Math.ceil( width / blockData.width ) * blockData.width,
  50090. height: Math.ceil( height / blockData.height ) * blockData.height,
  50091. depthOrArrayLayers: 1
  50092. }
  50093. );
  50094. }
  50095. }
  50096. }
  50097. /**
  50098. * This method is only relevant for compressed texture formats. It returns a block
  50099. * data descriptor for the given GPU compressed texture format.
  50100. *
  50101. * @private
  50102. * @param {string} format - The GPU compressed texture format.
  50103. * @return {Object} The block data descriptor.
  50104. */
  50105. _getBlockData( format ) {
  50106. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  50107. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  50108. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  50109. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  50110. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  50111. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  50112. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  50113. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  50114. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  50115. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  50116. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  50117. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  50118. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  50119. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  50120. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  50121. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  50122. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  50123. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  50124. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  50125. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  50126. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  50127. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  50128. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  50129. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  50130. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  50131. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  50132. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  50133. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  50134. }
  50135. /**
  50136. * Converts the three.js uv wrapping constants to GPU address mode constants.
  50137. *
  50138. * @private
  50139. * @param {number} value - The three.js constant defining a uv wrapping mode.
  50140. * @return {string} The GPU address mode.
  50141. */
  50142. _convertAddressMode( value ) {
  50143. let addressMode = GPUAddressMode.ClampToEdge;
  50144. if ( value === RepeatWrapping ) {
  50145. addressMode = GPUAddressMode.Repeat;
  50146. } else if ( value === MirroredRepeatWrapping ) {
  50147. addressMode = GPUAddressMode.MirrorRepeat;
  50148. }
  50149. return addressMode;
  50150. }
  50151. /**
  50152. * Converts the three.js filter constants to GPU filter constants.
  50153. *
  50154. * @private
  50155. * @param {number} value - The three.js constant defining a filter mode.
  50156. * @return {string} The GPU filter mode.
  50157. */
  50158. _convertFilterMode( value ) {
  50159. let filterMode = GPUFilterMode.Linear;
  50160. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  50161. filterMode = GPUFilterMode.Nearest;
  50162. }
  50163. return filterMode;
  50164. }
  50165. /**
  50166. * Returns the bytes-per-texel value for the given GPU texture format.
  50167. *
  50168. * @private
  50169. * @param {string} format - The GPU texture format.
  50170. * @return {number} The bytes-per-texel.
  50171. */
  50172. _getBytesPerTexel( format ) {
  50173. // 8-bit formats
  50174. if ( format === GPUTextureFormat.R8Unorm ||
  50175. format === GPUTextureFormat.R8Snorm ||
  50176. format === GPUTextureFormat.R8Uint ||
  50177. format === GPUTextureFormat.R8Sint ) return 1;
  50178. // 16-bit formats
  50179. if ( format === GPUTextureFormat.R16Uint ||
  50180. format === GPUTextureFormat.R16Sint ||
  50181. format === GPUTextureFormat.R16Float ||
  50182. format === GPUTextureFormat.RG8Unorm ||
  50183. format === GPUTextureFormat.RG8Snorm ||
  50184. format === GPUTextureFormat.RG8Uint ||
  50185. format === GPUTextureFormat.RG8Sint ) return 2;
  50186. // 32-bit formats
  50187. if ( format === GPUTextureFormat.R32Uint ||
  50188. format === GPUTextureFormat.R32Sint ||
  50189. format === GPUTextureFormat.R32Float ||
  50190. format === GPUTextureFormat.RG16Uint ||
  50191. format === GPUTextureFormat.RG16Sint ||
  50192. format === GPUTextureFormat.RG16Float ||
  50193. format === GPUTextureFormat.RGBA8Unorm ||
  50194. format === GPUTextureFormat.RGBA8UnormSRGB ||
  50195. format === GPUTextureFormat.RGBA8Snorm ||
  50196. format === GPUTextureFormat.RGBA8Uint ||
  50197. format === GPUTextureFormat.RGBA8Sint ||
  50198. format === GPUTextureFormat.BGRA8Unorm ||
  50199. format === GPUTextureFormat.BGRA8UnormSRGB ||
  50200. // Packed 32-bit formats
  50201. format === GPUTextureFormat.RGB9E5UFloat ||
  50202. format === GPUTextureFormat.RGB10A2Unorm ||
  50203. format === GPUTextureFormat.RG11B10UFloat ||
  50204. format === GPUTextureFormat.Depth32Float ||
  50205. format === GPUTextureFormat.Depth24Plus ||
  50206. format === GPUTextureFormat.Depth24PlusStencil8 ||
  50207. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  50208. // 64-bit formats
  50209. if ( format === GPUTextureFormat.RG32Uint ||
  50210. format === GPUTextureFormat.RG32Sint ||
  50211. format === GPUTextureFormat.RG32Float ||
  50212. format === GPUTextureFormat.RGBA16Uint ||
  50213. format === GPUTextureFormat.RGBA16Sint ||
  50214. format === GPUTextureFormat.RGBA16Float ) return 8;
  50215. // 128-bit formats
  50216. if ( format === GPUTextureFormat.RGBA32Uint ||
  50217. format === GPUTextureFormat.RGBA32Sint ||
  50218. format === GPUTextureFormat.RGBA32Float ) return 16;
  50219. }
  50220. /**
  50221. * Returns the corresponding typed array type for the given GPU texture format.
  50222. *
  50223. * @private
  50224. * @param {string} format - The GPU texture format.
  50225. * @return {TypedArray.constructor} The typed array type.
  50226. */
  50227. _getTypedArrayType( format ) {
  50228. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  50229. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  50230. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  50231. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  50232. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  50233. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  50234. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  50235. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  50236. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  50237. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  50238. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return Uint8Array;
  50239. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  50240. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  50241. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  50242. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  50243. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  50244. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  50245. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  50246. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  50247. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  50248. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  50249. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  50250. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  50251. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  50252. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  50253. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  50254. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  50255. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  50256. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  50257. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  50258. if ( format === GPUTextureFormat.BGRA8Unorm || format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  50259. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  50260. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  50261. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  50262. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  50263. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  50264. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  50265. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  50266. }
  50267. /**
  50268. * Returns the GPU dimensions for the given texture.
  50269. *
  50270. * @private
  50271. * @param {Texture} texture - The texture.
  50272. * @return {string} The GPU dimension.
  50273. */
  50274. _getDimension( texture ) {
  50275. let dimension;
  50276. if ( texture.is3DTexture || texture.isData3DTexture ) {
  50277. dimension = GPUTextureDimension.ThreeD;
  50278. } else {
  50279. dimension = GPUTextureDimension.TwoD;
  50280. }
  50281. return dimension;
  50282. }
  50283. }
  50284. /**
  50285. * Returns the GPU format for the given texture.
  50286. *
  50287. * @param {Texture} texture - The texture.
  50288. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  50289. * It is not necessary to apply the device for most formats.
  50290. * @return {string} The GPU format.
  50291. */
  50292. function getFormat( texture, device = null ) {
  50293. const format = texture.format;
  50294. const type = texture.type;
  50295. const colorSpace = texture.colorSpace;
  50296. const transfer = ColorManagement.getTransfer( colorSpace );
  50297. let formatGPU;
  50298. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  50299. switch ( format ) {
  50300. case RGB_S3TC_DXT1_Format:
  50301. case RGBA_S3TC_DXT1_Format:
  50302. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  50303. break;
  50304. case RGBA_S3TC_DXT3_Format:
  50305. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  50306. break;
  50307. case RGBA_S3TC_DXT5_Format:
  50308. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  50309. break;
  50310. case RED_RGTC1_Format:
  50311. formatGPU = GPUTextureFormat.BC4RUnorm;
  50312. break;
  50313. case SIGNED_RED_RGTC1_Format:
  50314. formatGPU = GPUTextureFormat.BC4RSnorm;
  50315. break;
  50316. case RED_GREEN_RGTC2_Format:
  50317. formatGPU = GPUTextureFormat.BC5RGUnorm;
  50318. break;
  50319. case SIGNED_RED_GREEN_RGTC2_Format:
  50320. formatGPU = GPUTextureFormat.BC5RGSnorm;
  50321. break;
  50322. case RGBA_BPTC_Format:
  50323. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC7RGBAUnormSRGB : GPUTextureFormat.BC7RGBAUnorm;
  50324. break;
  50325. case RGB_ETC2_Format:
  50326. case RGB_ETC1_Format:
  50327. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  50328. break;
  50329. case RGBA_ETC2_EAC_Format:
  50330. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  50331. break;
  50332. case RGBA_ASTC_4x4_Format:
  50333. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  50334. break;
  50335. case RGBA_ASTC_5x4_Format:
  50336. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  50337. break;
  50338. case RGBA_ASTC_5x5_Format:
  50339. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  50340. break;
  50341. case RGBA_ASTC_6x5_Format:
  50342. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  50343. break;
  50344. case RGBA_ASTC_6x6_Format:
  50345. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  50346. break;
  50347. case RGBA_ASTC_8x5_Format:
  50348. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  50349. break;
  50350. case RGBA_ASTC_8x6_Format:
  50351. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  50352. break;
  50353. case RGBA_ASTC_8x8_Format:
  50354. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  50355. break;
  50356. case RGBA_ASTC_10x5_Format:
  50357. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  50358. break;
  50359. case RGBA_ASTC_10x6_Format:
  50360. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  50361. break;
  50362. case RGBA_ASTC_10x8_Format:
  50363. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  50364. break;
  50365. case RGBA_ASTC_10x10_Format:
  50366. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  50367. break;
  50368. case RGBA_ASTC_12x10_Format:
  50369. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  50370. break;
  50371. case RGBA_ASTC_12x12_Format:
  50372. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  50373. break;
  50374. case RGBAFormat:
  50375. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  50376. break;
  50377. default:
  50378. error( 'WebGPURenderer: Unsupported texture format.', format );
  50379. }
  50380. } else {
  50381. switch ( format ) {
  50382. case RGBAFormat:
  50383. switch ( type ) {
  50384. case ByteType:
  50385. formatGPU = GPUTextureFormat.RGBA8Snorm;
  50386. break;
  50387. case ShortType:
  50388. formatGPU = GPUTextureFormat.RGBA16Sint;
  50389. break;
  50390. case UnsignedShortType:
  50391. formatGPU = GPUTextureFormat.RGBA16Uint;
  50392. break;
  50393. case UnsignedIntType:
  50394. formatGPU = GPUTextureFormat.RGBA32Uint;
  50395. break;
  50396. case IntType:
  50397. formatGPU = GPUTextureFormat.RGBA32Sint;
  50398. break;
  50399. case UnsignedByteType:
  50400. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  50401. break;
  50402. case HalfFloatType:
  50403. formatGPU = GPUTextureFormat.RGBA16Float;
  50404. break;
  50405. case FloatType:
  50406. formatGPU = GPUTextureFormat.RGBA32Float;
  50407. break;
  50408. default:
  50409. error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  50410. }
  50411. break;
  50412. case RGBFormat:
  50413. switch ( type ) {
  50414. case UnsignedInt5999Type:
  50415. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  50416. break;
  50417. case UnsignedInt101111Type:
  50418. formatGPU = GPUTextureFormat.RG11B10UFloat;
  50419. break;
  50420. default:
  50421. error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  50422. }
  50423. break;
  50424. case RedFormat:
  50425. switch ( type ) {
  50426. case ByteType:
  50427. formatGPU = GPUTextureFormat.R8Snorm;
  50428. break;
  50429. case ShortType:
  50430. formatGPU = GPUTextureFormat.R16Sint;
  50431. break;
  50432. case UnsignedShortType:
  50433. formatGPU = GPUTextureFormat.R16Uint;
  50434. break;
  50435. case UnsignedIntType:
  50436. formatGPU = GPUTextureFormat.R32Uint;
  50437. break;
  50438. case IntType:
  50439. formatGPU = GPUTextureFormat.R32Sint;
  50440. break;
  50441. case UnsignedByteType:
  50442. formatGPU = GPUTextureFormat.R8Unorm;
  50443. break;
  50444. case HalfFloatType:
  50445. formatGPU = GPUTextureFormat.R16Float;
  50446. break;
  50447. case FloatType:
  50448. formatGPU = GPUTextureFormat.R32Float;
  50449. break;
  50450. default:
  50451. error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  50452. }
  50453. break;
  50454. case RGFormat:
  50455. switch ( type ) {
  50456. case ByteType:
  50457. formatGPU = GPUTextureFormat.RG8Snorm;
  50458. break;
  50459. case ShortType:
  50460. formatGPU = GPUTextureFormat.RG16Sint;
  50461. break;
  50462. case UnsignedShortType:
  50463. formatGPU = GPUTextureFormat.RG16Uint;
  50464. break;
  50465. case UnsignedIntType:
  50466. formatGPU = GPUTextureFormat.RG32Uint;
  50467. break;
  50468. case IntType:
  50469. formatGPU = GPUTextureFormat.RG32Sint;
  50470. break;
  50471. case UnsignedByteType:
  50472. formatGPU = GPUTextureFormat.RG8Unorm;
  50473. break;
  50474. case HalfFloatType:
  50475. formatGPU = GPUTextureFormat.RG16Float;
  50476. break;
  50477. case FloatType:
  50478. formatGPU = GPUTextureFormat.RG32Float;
  50479. break;
  50480. default:
  50481. error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  50482. }
  50483. break;
  50484. case DepthFormat:
  50485. switch ( type ) {
  50486. case UnsignedShortType:
  50487. formatGPU = GPUTextureFormat.Depth16Unorm;
  50488. break;
  50489. case UnsignedIntType:
  50490. formatGPU = GPUTextureFormat.Depth24Plus;
  50491. break;
  50492. case FloatType:
  50493. formatGPU = GPUTextureFormat.Depth32Float;
  50494. break;
  50495. default:
  50496. error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  50497. }
  50498. break;
  50499. case DepthStencilFormat:
  50500. switch ( type ) {
  50501. case UnsignedInt248Type:
  50502. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  50503. break;
  50504. case FloatType:
  50505. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  50506. error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  50507. }
  50508. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  50509. break;
  50510. default:
  50511. error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  50512. }
  50513. break;
  50514. case RedIntegerFormat:
  50515. switch ( type ) {
  50516. case IntType:
  50517. formatGPU = GPUTextureFormat.R32Sint;
  50518. break;
  50519. case UnsignedIntType:
  50520. formatGPU = GPUTextureFormat.R32Uint;
  50521. break;
  50522. default:
  50523. error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  50524. }
  50525. break;
  50526. case RGIntegerFormat:
  50527. switch ( type ) {
  50528. case IntType:
  50529. formatGPU = GPUTextureFormat.RG32Sint;
  50530. break;
  50531. case UnsignedIntType:
  50532. formatGPU = GPUTextureFormat.RG32Uint;
  50533. break;
  50534. default:
  50535. error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  50536. }
  50537. break;
  50538. case RGBAIntegerFormat:
  50539. switch ( type ) {
  50540. case IntType:
  50541. formatGPU = GPUTextureFormat.RGBA32Sint;
  50542. break;
  50543. case UnsignedIntType:
  50544. formatGPU = GPUTextureFormat.RGBA32Uint;
  50545. break;
  50546. default:
  50547. error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  50548. }
  50549. break;
  50550. default:
  50551. error( 'WebGPURenderer: Unsupported texture format.', format );
  50552. }
  50553. }
  50554. return formatGPU;
  50555. }
  50556. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  50557. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  50558. const wgslTypeLib$1 = {
  50559. 'f32': 'float',
  50560. 'i32': 'int',
  50561. 'u32': 'uint',
  50562. 'bool': 'bool',
  50563. 'vec2<f32>': 'vec2',
  50564. 'vec2<i32>': 'ivec2',
  50565. 'vec2<u32>': 'uvec2',
  50566. 'vec2<bool>': 'bvec2',
  50567. 'vec2f': 'vec2',
  50568. 'vec2i': 'ivec2',
  50569. 'vec2u': 'uvec2',
  50570. 'vec2b': 'bvec2',
  50571. 'vec3<f32>': 'vec3',
  50572. 'vec3<i32>': 'ivec3',
  50573. 'vec3<u32>': 'uvec3',
  50574. 'vec3<bool>': 'bvec3',
  50575. 'vec3f': 'vec3',
  50576. 'vec3i': 'ivec3',
  50577. 'vec3u': 'uvec3',
  50578. 'vec3b': 'bvec3',
  50579. 'vec4<f32>': 'vec4',
  50580. 'vec4<i32>': 'ivec4',
  50581. 'vec4<u32>': 'uvec4',
  50582. 'vec4<bool>': 'bvec4',
  50583. 'vec4f': 'vec4',
  50584. 'vec4i': 'ivec4',
  50585. 'vec4u': 'uvec4',
  50586. 'vec4b': 'bvec4',
  50587. 'mat2x2<f32>': 'mat2',
  50588. 'mat2x2f': 'mat2',
  50589. 'mat3x3<f32>': 'mat3',
  50590. 'mat3x3f': 'mat3',
  50591. 'mat4x4<f32>': 'mat4',
  50592. 'mat4x4f': 'mat4',
  50593. 'sampler': 'sampler',
  50594. 'texture_1d': 'texture',
  50595. 'texture_2d': 'texture',
  50596. 'texture_2d_array': 'texture',
  50597. 'texture_multisampled_2d': 'cubeTexture',
  50598. 'texture_depth_2d': 'depthTexture',
  50599. 'texture_depth_2d_array': 'depthTexture',
  50600. 'texture_depth_multisampled_2d': 'depthTexture',
  50601. 'texture_depth_cube': 'depthTexture',
  50602. 'texture_depth_cube_array': 'depthTexture',
  50603. 'texture_3d': 'texture3D',
  50604. 'texture_cube': 'cubeTexture',
  50605. 'texture_cube_array': 'cubeTexture',
  50606. 'texture_storage_1d': 'storageTexture',
  50607. 'texture_storage_2d': 'storageTexture',
  50608. 'texture_storage_2d_array': 'storageTexture',
  50609. 'texture_storage_3d': 'storageTexture'
  50610. };
  50611. const parse = ( source ) => {
  50612. source = source.trim();
  50613. const declaration = source.match( declarationRegexp );
  50614. if ( declaration !== null && declaration.length === 4 ) {
  50615. const inputsCode = declaration[ 2 ];
  50616. const propsMatches = [];
  50617. let match = null;
  50618. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  50619. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  50620. }
  50621. // Process matches to correctly pair names and types
  50622. const inputs = [];
  50623. for ( let i = 0; i < propsMatches.length; i ++ ) {
  50624. const { name, type } = propsMatches[ i ];
  50625. let resolvedType = type;
  50626. if ( resolvedType.startsWith( 'ptr' ) ) {
  50627. resolvedType = 'pointer';
  50628. } else {
  50629. if ( resolvedType.startsWith( 'texture' ) ) {
  50630. resolvedType = type.split( '<' )[ 0 ];
  50631. }
  50632. resolvedType = wgslTypeLib$1[ resolvedType ];
  50633. }
  50634. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  50635. }
  50636. const blockCode = source.substring( declaration[ 0 ].length );
  50637. const outputType = declaration[ 3 ] || 'void';
  50638. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  50639. const type = wgslTypeLib$1[ outputType ] || outputType;
  50640. return {
  50641. type,
  50642. inputs,
  50643. name,
  50644. inputsCode,
  50645. blockCode,
  50646. outputType
  50647. };
  50648. } else {
  50649. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  50650. }
  50651. };
  50652. /**
  50653. * This class represents a WSL node function.
  50654. *
  50655. * @augments NodeFunction
  50656. */
  50657. class WGSLNodeFunction extends NodeFunction {
  50658. /**
  50659. * Constructs a new WGSL node function.
  50660. *
  50661. * @param {string} source - The WGSL source.
  50662. */
  50663. constructor( source ) {
  50664. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  50665. super( type, inputs, name );
  50666. this.inputsCode = inputsCode;
  50667. this.blockCode = blockCode;
  50668. this.outputType = outputType;
  50669. }
  50670. /**
  50671. * This method returns the WGSL code of the node function.
  50672. *
  50673. * @param {string} [name=this.name] - The function's name.
  50674. * @return {string} The shader code.
  50675. */
  50676. getCode( name = this.name ) {
  50677. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  50678. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  50679. }
  50680. }
  50681. /**
  50682. * A WGSL node parser.
  50683. *
  50684. * @augments NodeParser
  50685. */
  50686. class WGSLNodeParser extends NodeParser {
  50687. /**
  50688. * The method parses the given WGSL code an returns a node function.
  50689. *
  50690. * @param {string} source - The WGSL code.
  50691. * @return {WGSLNodeFunction} A node function.
  50692. */
  50693. parseFunction( source ) {
  50694. return new WGSLNodeFunction( source );
  50695. }
  50696. }
  50697. // GPUShaderStage is not defined in browsers not supporting WebGPU
  50698. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  50699. const accessNames = {
  50700. [ NodeAccess.READ_ONLY ]: 'read',
  50701. [ NodeAccess.WRITE_ONLY ]: 'write',
  50702. [ NodeAccess.READ_WRITE ]: 'read_write'
  50703. };
  50704. const wrapNames = {
  50705. [ RepeatWrapping ]: 'repeat',
  50706. [ ClampToEdgeWrapping ]: 'clamp',
  50707. [ MirroredRepeatWrapping ]: 'mirror'
  50708. };
  50709. const gpuShaderStageLib = {
  50710. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  50711. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  50712. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  50713. };
  50714. const supports = {
  50715. instance: true,
  50716. swizzleAssign: false,
  50717. storageBuffer: true
  50718. };
  50719. const wgslFnOpLib = {
  50720. '^^': 'tsl_xor'
  50721. };
  50722. const wgslTypeLib = {
  50723. float: 'f32',
  50724. int: 'i32',
  50725. uint: 'u32',
  50726. bool: 'bool',
  50727. color: 'vec3<f32>',
  50728. vec2: 'vec2<f32>',
  50729. ivec2: 'vec2<i32>',
  50730. uvec2: 'vec2<u32>',
  50731. bvec2: 'vec2<bool>',
  50732. vec3: 'vec3<f32>',
  50733. ivec3: 'vec3<i32>',
  50734. uvec3: 'vec3<u32>',
  50735. bvec3: 'vec3<bool>',
  50736. vec4: 'vec4<f32>',
  50737. ivec4: 'vec4<i32>',
  50738. uvec4: 'vec4<u32>',
  50739. bvec4: 'vec4<bool>',
  50740. mat2: 'mat2x2<f32>',
  50741. mat3: 'mat3x3<f32>',
  50742. mat4: 'mat4x4<f32>'
  50743. };
  50744. const wgslCodeCache = {};
  50745. const wgslPolyfill = {
  50746. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  50747. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  50748. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  50749. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  50750. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  50751. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  50752. 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 ); }' ),
  50753. 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 ); }' ),
  50754. 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 ); }' ),
  50755. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  50756. 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 ); }' ),
  50757. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  50758. biquadraticTexture: new CodeNode( /* wgsl */`
  50759. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  50760. let res = vec2f( iRes );
  50761. let uvScaled = coord * res;
  50762. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  50763. // https://www.shadertoy.com/view/WtyXRy
  50764. let uv = uvWrapping - 0.5;
  50765. let iuv = floor( uv );
  50766. let f = fract( uv );
  50767. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  50768. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  50769. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  50770. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  50771. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  50772. }
  50773. ` )
  50774. };
  50775. const wgslMethods = {
  50776. dFdx: 'dpdx',
  50777. dFdy: '- dpdy',
  50778. mod_float: 'tsl_mod_float',
  50779. mod_vec2: 'tsl_mod_vec2',
  50780. mod_vec3: 'tsl_mod_vec3',
  50781. mod_vec4: 'tsl_mod_vec4',
  50782. equals_bool: 'tsl_equals_bool',
  50783. equals_bvec2: 'tsl_equals_bvec2',
  50784. equals_bvec3: 'tsl_equals_bvec3',
  50785. equals_bvec4: 'tsl_equals_bvec4',
  50786. inversesqrt: 'inverseSqrt',
  50787. bitcast: 'bitcast<f32>'
  50788. };
  50789. //
  50790. let diagnostics = '';
  50791. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  50792. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  50793. }
  50794. /**
  50795. * A node builder targeting WGSL.
  50796. *
  50797. * This module generates WGSL shader code from node materials and also
  50798. * generates the respective bindings and vertex buffer definitions. These
  50799. * data are later used by the renderer to create render and compute pipelines
  50800. * for render objects.
  50801. *
  50802. * @augments NodeBuilder
  50803. */
  50804. class WGSLNodeBuilder extends NodeBuilder {
  50805. /**
  50806. * Constructs a new WGSL node builder renderer.
  50807. *
  50808. * @param {Object3D} object - The 3D object.
  50809. * @param {Renderer} renderer - The renderer.
  50810. */
  50811. constructor( object, renderer ) {
  50812. super( object, renderer, new WGSLNodeParser() );
  50813. /**
  50814. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  50815. * another dictionary which manages UBOs per group ('render','frame','object').
  50816. *
  50817. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  50818. */
  50819. this.uniformGroups = {};
  50820. /**
  50821. * A dictionary that holds for each shader stage a Map of builtins.
  50822. *
  50823. * @type {Object<string,Map<string,Object>>}
  50824. */
  50825. this.builtins = {};
  50826. /**
  50827. * A dictionary that holds for each shader stage a Set of directives.
  50828. *
  50829. * @type {Object<string,Set<string>>}
  50830. */
  50831. this.directives = {};
  50832. /**
  50833. * A map for managing scope arrays. Only relevant for when using
  50834. * {@link WorkgroupInfoNode} in context of compute shaders.
  50835. *
  50836. * @type {Map<string,Object>}
  50837. */
  50838. this.scopedArrays = new Map();
  50839. }
  50840. /**
  50841. * Generates the WGSL snippet for sampled textures.
  50842. *
  50843. * @private
  50844. * @param {Texture} texture - The texture.
  50845. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50846. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50847. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50848. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50849. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50850. * @return {string} The WGSL snippet.
  50851. */
  50852. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  50853. if ( shaderStage === 'fragment' ) {
  50854. if ( depthSnippet ) {
  50855. if ( offsetSnippet ) {
  50856. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  50857. }
  50858. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  50859. } else {
  50860. if ( offsetSnippet ) {
  50861. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  50862. }
  50863. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  50864. }
  50865. } else {
  50866. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  50867. }
  50868. }
  50869. /**
  50870. * Generates the WGSL snippet when sampling textures with explicit mip level.
  50871. *
  50872. * @private
  50873. * @param {Texture} texture - The texture.
  50874. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50875. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50876. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50877. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50878. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50879. * @return {string} The WGSL snippet.
  50880. */
  50881. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  50882. if ( this.isUnfilterable( texture ) === false ) {
  50883. if ( offsetSnippet ) {
  50884. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  50885. }
  50886. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  50887. } else if ( this.isFilteredTexture( texture ) ) {
  50888. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  50889. } else {
  50890. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  50891. }
  50892. }
  50893. /**
  50894. * Generates a wrap function used in context of textures.
  50895. *
  50896. * @param {Texture} texture - The texture to generate the function for.
  50897. * @return {string} The name of the generated function.
  50898. */
  50899. generateWrapFunction( texture ) {
  50900. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.isData3DTexture ? '3d' : '2d' }T`;
  50901. let nodeCode = wgslCodeCache[ functionName ];
  50902. if ( nodeCode === undefined ) {
  50903. const includes = [];
  50904. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  50905. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  50906. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  50907. const addWrapSnippet = ( wrap, axis ) => {
  50908. if ( wrap === RepeatWrapping ) {
  50909. includes.push( wgslPolyfill.repeatWrapping_float );
  50910. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  50911. } else if ( wrap === ClampToEdgeWrapping ) {
  50912. includes.push( wgslPolyfill.clampWrapping_float );
  50913. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  50914. } else if ( wrap === MirroredRepeatWrapping ) {
  50915. includes.push( wgslPolyfill.mirrorWrapping_float );
  50916. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  50917. } else {
  50918. code += `\t\tcoord.${ axis }`;
  50919. warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  50920. }
  50921. };
  50922. addWrapSnippet( texture.wrapS, 'x' );
  50923. code += ',\n';
  50924. addWrapSnippet( texture.wrapT, 'y' );
  50925. if ( texture.isData3DTexture ) {
  50926. code += ',\n';
  50927. addWrapSnippet( texture.wrapR, 'z' );
  50928. }
  50929. code += '\n\t);\n\n}\n';
  50930. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  50931. }
  50932. nodeCode.build( this );
  50933. return functionName;
  50934. }
  50935. /**
  50936. * Generates the array declaration string.
  50937. *
  50938. * @param {string} type - The type.
  50939. * @param {?number} [count] - The count.
  50940. * @return {string} The generated value as a shader string.
  50941. */
  50942. generateArrayDeclaration( type, count ) {
  50943. return `array< ${ this.getType( type ) }, ${ count } >`;
  50944. }
  50945. /**
  50946. * Generates a WGSL variable that holds the texture dimension of the given texture.
  50947. * It also returns information about the number of layers (elements) of an arrayed
  50948. * texture as well as the cube face count of cube textures.
  50949. *
  50950. * @param {Texture} texture - The texture to generate the function for.
  50951. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  50952. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50953. * @return {string} The name of the dimension variable.
  50954. */
  50955. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  50956. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  50957. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  50958. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  50959. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  50960. let textureDimensionsParams;
  50961. let dimensionType;
  50962. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  50963. const isMultisampled = primarySamples > 1;
  50964. if ( texture.isData3DTexture ) {
  50965. dimensionType = 'vec3<u32>';
  50966. } else {
  50967. // Regular 2D textures, depth textures, etc.
  50968. dimensionType = 'vec2<u32>';
  50969. }
  50970. // Build parameters string based on texture type and multisampling
  50971. if ( isMultisampled || texture.isStorageTexture ) {
  50972. textureDimensionsParams = textureProperty;
  50973. } else {
  50974. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  50975. }
  50976. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  50977. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  50978. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  50979. textureData.arrayLayerCount = new VarNode(
  50980. new ExpressionNode(
  50981. `textureNumLayers(${textureProperty})`,
  50982. 'u32'
  50983. )
  50984. );
  50985. }
  50986. // For cube textures, we know it's always 6 faces
  50987. if ( texture.isTextureCube ) {
  50988. textureData.cubeFaceCount = new VarNode(
  50989. new ExpressionNode( '6u', 'u32' )
  50990. );
  50991. }
  50992. }
  50993. return textureDimensionNode.build( this );
  50994. }
  50995. /**
  50996. * Generates the WGSL snippet for a manual filtered texture.
  50997. *
  50998. * @param {Texture} texture - The texture.
  50999. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51000. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51001. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  51002. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  51003. * @return {string} The WGSL snippet.
  51004. */
  51005. generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet = '0u' ) {
  51006. this._include( 'biquadraticTexture' );
  51007. const wrapFunction = this.generateWrapFunction( texture );
  51008. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  51009. if ( offsetSnippet ) {
  51010. uvSnippet = `${ uvSnippet } + vec2<f32>(${ offsetSnippet }) / ${ textureDimension }`;
  51011. }
  51012. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  51013. }
  51014. /**
  51015. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  51016. * Since it's a lookup, no sampling or filtering is applied.
  51017. *
  51018. * @param {Texture} texture - The texture.
  51019. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51020. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51021. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  51022. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  51023. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  51024. * @return {string} The WGSL snippet.
  51025. */
  51026. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet = '0u' ) {
  51027. const wrapFunction = this.generateWrapFunction( texture );
  51028. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  51029. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  51030. if ( offsetSnippet ) {
  51031. uvSnippet = `${ uvSnippet } + ${ vecType }<f32>(${ offsetSnippet }) / ${ vecType }<f32>( ${ textureDimension } )`;
  51032. }
  51033. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  51034. return this.generateTextureLoad( texture, textureProperty, coordSnippet, levelSnippet, depthSnippet, null );
  51035. }
  51036. /**
  51037. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  51038. *
  51039. * @param {Texture} texture - The texture.
  51040. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51041. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51042. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  51043. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  51044. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  51045. * @return {string} The WGSL snippet.
  51046. */
  51047. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  51048. if ( levelSnippet === null ) levelSnippet = '0u';
  51049. if ( offsetSnippet ) {
  51050. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  51051. }
  51052. let snippet;
  51053. if ( depthSnippet ) {
  51054. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  51055. } else {
  51056. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  51057. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  51058. snippet += '.x';
  51059. }
  51060. }
  51061. return snippet;
  51062. }
  51063. /**
  51064. * Generates the WGSL snippet that writes a single texel to a texture.
  51065. *
  51066. * @param {Texture} texture - The texture.
  51067. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51068. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51069. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  51070. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  51071. * @return {string} The WGSL snippet.
  51072. */
  51073. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  51074. let snippet;
  51075. if ( depthSnippet ) {
  51076. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  51077. } else {
  51078. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  51079. }
  51080. return snippet;
  51081. }
  51082. /**
  51083. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  51084. *
  51085. * @param {Texture} texture - The texture.
  51086. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  51087. */
  51088. isSampleCompare( texture ) {
  51089. return texture.isDepthTexture === true && texture.compareFunction !== null;
  51090. }
  51091. /**
  51092. * Returns `true` if the given texture is unfilterable.
  51093. *
  51094. * @param {Texture} texture - The texture.
  51095. * @return {boolean} Whether the given texture is unfilterable or not.
  51096. */
  51097. isUnfilterable( texture ) {
  51098. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  51099. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  51100. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  51101. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  51102. }
  51103. /**
  51104. * Generates the WGSL snippet for sampling/loading the given texture.
  51105. *
  51106. * @param {Texture} texture - The texture.
  51107. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51108. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51109. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  51110. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  51111. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51112. * @return {string} The WGSL snippet.
  51113. */
  51114. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  51115. let snippet = null;
  51116. if ( this.isUnfilterable( texture ) ) {
  51117. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, '0', shaderStage );
  51118. } else {
  51119. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage );
  51120. }
  51121. return snippet;
  51122. }
  51123. /**
  51124. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  51125. *
  51126. * @param {Texture} texture - The texture.
  51127. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51128. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51129. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  51130. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  51131. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  51132. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51133. * @return {string} The WGSL snippet.
  51134. */
  51135. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  51136. if ( shaderStage === 'fragment' ) {
  51137. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  51138. if ( offsetSnippet ) {
  51139. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  51140. }
  51141. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  51142. } else {
  51143. error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  51144. }
  51145. }
  51146. /**
  51147. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  51148. * against a reference value.
  51149. *
  51150. * @param {Texture} texture - The texture.
  51151. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51152. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51153. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  51154. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  51155. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  51156. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51157. * @return {string} The WGSL snippet.
  51158. */
  51159. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  51160. if ( shaderStage === 'fragment' ) {
  51161. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  51162. if ( offsetSnippet ) {
  51163. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  51164. }
  51165. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  51166. }
  51167. if ( offsetSnippet ) {
  51168. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  51169. }
  51170. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  51171. } else {
  51172. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  51173. }
  51174. }
  51175. /**
  51176. * Generates the WGSL snippet when sampling textures with explicit mip level.
  51177. *
  51178. * @param {Texture} texture - The texture.
  51179. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51180. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51181. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  51182. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  51183. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  51184. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51185. * @return {string} The WGSL snippet.
  51186. */
  51187. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  51188. if ( this.isUnfilterable( texture ) === false ) {
  51189. if ( offsetSnippet ) {
  51190. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  51191. }
  51192. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  51193. } else if ( this.isFilteredTexture( texture ) ) {
  51194. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  51195. } else {
  51196. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  51197. }
  51198. }
  51199. /**
  51200. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  51201. *
  51202. * @param {Texture} texture - The texture.
  51203. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51204. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51205. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  51206. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  51207. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  51208. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51209. * @return {string} The WGSL snippet.
  51210. */
  51211. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  51212. if ( shaderStage === 'fragment' ) {
  51213. if ( offsetSnippet ) {
  51214. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  51215. }
  51216. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  51217. } else {
  51218. error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  51219. }
  51220. }
  51221. /**
  51222. * Returns a WGSL snippet that represents the property name of the given node.
  51223. *
  51224. * @param {Node} node - The node.
  51225. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51226. * @return {string} The property name.
  51227. */
  51228. getPropertyName( node, shaderStage = this.shaderStage ) {
  51229. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  51230. if ( shaderStage === 'vertex' ) {
  51231. return `varyings.${ node.name }`;
  51232. }
  51233. } else if ( node.isNodeUniform === true ) {
  51234. const name = node.name;
  51235. const type = node.type;
  51236. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  51237. return name;
  51238. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  51239. if ( this.isCustomStruct( node ) ) {
  51240. return name;
  51241. }
  51242. return name + '.value';
  51243. } else {
  51244. return node.groupNode.name + '.' + name;
  51245. }
  51246. }
  51247. return super.getPropertyName( node );
  51248. }
  51249. /**
  51250. * Returns the output struct name.
  51251. *
  51252. * @return {string} The name of the output struct.
  51253. */
  51254. getOutputStructName() {
  51255. return 'output';
  51256. }
  51257. /**
  51258. * Returns the native shader operator name for a given generic name.
  51259. *
  51260. * @param {string} op - The operator name to resolve.
  51261. * @return {?string} The resolved operator name.
  51262. */
  51263. getFunctionOperator( op ) {
  51264. const fnOp = wgslFnOpLib[ op ];
  51265. if ( fnOp !== undefined ) {
  51266. this._include( fnOp );
  51267. return fnOp;
  51268. }
  51269. return null;
  51270. }
  51271. /**
  51272. * Returns the node access for the given node and shader stage.
  51273. *
  51274. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  51275. * @param {string} shaderStage - The shader stage.
  51276. * @return {string} The node access.
  51277. */
  51278. getNodeAccess( node, shaderStage ) {
  51279. if ( shaderStage !== 'compute' ) {
  51280. if ( node.isAtomic === true ) {
  51281. warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  51282. return NodeAccess.READ_WRITE;
  51283. }
  51284. return NodeAccess.READ_ONLY;
  51285. }
  51286. return node.access;
  51287. }
  51288. /**
  51289. * Returns A WGSL snippet representing the storage access.
  51290. *
  51291. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  51292. * @param {string} shaderStage - The shader stage.
  51293. * @return {string} The WGSL snippet representing the storage access.
  51294. */
  51295. getStorageAccess( node, shaderStage ) {
  51296. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  51297. }
  51298. /**
  51299. * This method is one of the more important ones since it's responsible
  51300. * for generating a matching binding instance for the given uniform node.
  51301. *
  51302. * These bindings are later used in the renderer to create bind groups
  51303. * and layouts.
  51304. *
  51305. * @param {UniformNode} node - The uniform node.
  51306. * @param {string} type - The node data type.
  51307. * @param {string} shaderStage - The shader stage.
  51308. * @param {?string} [name=null] - An optional uniform name.
  51309. * @return {NodeUniform} The node uniform object.
  51310. */
  51311. getUniformFromNode( node, type, shaderStage, name = null ) {
  51312. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  51313. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  51314. if ( nodeData.uniformGPU === undefined ) {
  51315. let uniformGPU;
  51316. const group = node.groupNode;
  51317. const groupName = group.name;
  51318. const bindings = this.getBindGroupArray( groupName, shaderStage );
  51319. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  51320. let texture = null;
  51321. const access = this.getNodeAccess( node, shaderStage );
  51322. if ( type === 'texture' || type === 'storageTexture' ) {
  51323. if ( node.value.is3DTexture === true ) {
  51324. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  51325. } else {
  51326. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  51327. }
  51328. } else if ( type === 'cubeTexture' ) {
  51329. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  51330. } else if ( type === 'texture3D' ) {
  51331. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  51332. }
  51333. texture.store = node.isStorageTextureNode === true;
  51334. texture.mipLevel = texture.store ? node.mipLevel : 0;
  51335. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  51336. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  51337. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  51338. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  51339. bindings.push( sampler, texture );
  51340. uniformGPU = [ sampler, texture ];
  51341. } else {
  51342. bindings.push( texture );
  51343. uniformGPU = [ texture ];
  51344. }
  51345. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  51346. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  51347. const buffer = new bufferClass( node, group );
  51348. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  51349. bindings.push( buffer );
  51350. uniformGPU = buffer;
  51351. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  51352. } else {
  51353. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  51354. let uniformsGroup = uniformsStage[ groupName ];
  51355. if ( uniformsGroup === undefined ) {
  51356. uniformsGroup = new NodeUniformsGroup( groupName, group );
  51357. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  51358. uniformsStage[ groupName ] = uniformsGroup;
  51359. bindings.push( uniformsGroup );
  51360. }
  51361. uniformGPU = this.getNodeUniform( uniformNode, type );
  51362. uniformsGroup.addUniform( uniformGPU );
  51363. }
  51364. nodeData.uniformGPU = uniformGPU;
  51365. }
  51366. return uniformNode;
  51367. }
  51368. /**
  51369. * This method should be used whenever builtins are required in nodes.
  51370. * The internal builtins data structure will make sure builtins are
  51371. * defined in the WGSL source.
  51372. *
  51373. * @param {string} name - The builtin name.
  51374. * @param {string} property - The property name.
  51375. * @param {string} type - The node data type.
  51376. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51377. * @return {string} The property name.
  51378. */
  51379. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  51380. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  51381. if ( map.has( name ) === false ) {
  51382. map.set( name, {
  51383. name,
  51384. property,
  51385. type
  51386. } );
  51387. }
  51388. return property;
  51389. }
  51390. /**
  51391. * Returns `true` if the given builtin is defined in the given shader stage.
  51392. *
  51393. * @param {string} name - The builtin name.
  51394. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51395. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  51396. */
  51397. hasBuiltin( name, shaderStage = this.shaderStage ) {
  51398. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  51399. }
  51400. /**
  51401. * Returns the vertex index builtin.
  51402. *
  51403. * @return {string} The vertex index.
  51404. */
  51405. getVertexIndex() {
  51406. if ( this.shaderStage === 'vertex' ) {
  51407. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  51408. }
  51409. return 'vertexIndex';
  51410. }
  51411. /**
  51412. * Builds the given shader node.
  51413. *
  51414. * @param {ShaderNodeInternal} shaderNode - The shader node.
  51415. * @return {string} The WGSL function code.
  51416. */
  51417. buildFunctionCode( shaderNode ) {
  51418. const layout = shaderNode.layout;
  51419. const flowData = this.flowShaderNode( shaderNode );
  51420. const parameters = [];
  51421. for ( const input of layout.inputs ) {
  51422. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  51423. }
  51424. //
  51425. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  51426. ${ flowData.vars }
  51427. ${ flowData.code }
  51428. `;
  51429. if ( flowData.result ) {
  51430. code += `\treturn ${ flowData.result };\n`;
  51431. }
  51432. code += '\n}\n';
  51433. //
  51434. return code;
  51435. }
  51436. /**
  51437. * Contextually returns either the vertex stage instance index builtin
  51438. * or the linearized index of an compute invocation within a grid of workgroups.
  51439. *
  51440. * @return {string} The instance index.
  51441. */
  51442. getInstanceIndex() {
  51443. if ( this.shaderStage === 'vertex' ) {
  51444. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  51445. }
  51446. return 'instanceIndex';
  51447. }
  51448. /**
  51449. * Returns a builtin representing the index of a compute invocation within the scope of a workgroup load.
  51450. *
  51451. * @return {string} The invocation local index.
  51452. */
  51453. getInvocationLocalIndex() {
  51454. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  51455. }
  51456. /**
  51457. * Returns a builtin representing the size of a subgroup within the current shader.
  51458. *
  51459. * @return {string} The subgroup size.
  51460. */
  51461. getSubgroupSize() {
  51462. this.enableSubGroups();
  51463. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  51464. }
  51465. /**
  51466. * Returns a builtin representing the index of a compute invocation within the scope of a subgroup.
  51467. *
  51468. * @return {string} The invocation subgroup index.
  51469. */
  51470. getInvocationSubgroupIndex() {
  51471. this.enableSubGroups();
  51472. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  51473. }
  51474. /**
  51475. * Returns a builtin representing the index of a compute invocation's subgroup within its workgroup.
  51476. *
  51477. * @return {string} The subgroup index.
  51478. */
  51479. getSubgroupIndex() {
  51480. this.enableSubGroups();
  51481. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  51482. }
  51483. /**
  51484. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  51485. *
  51486. * @return {null} Null.
  51487. */
  51488. getDrawIndex() {
  51489. return null;
  51490. }
  51491. /**
  51492. * Returns the front facing builtin.
  51493. *
  51494. * @return {string} The front facing builtin.
  51495. */
  51496. getFrontFacing() {
  51497. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  51498. }
  51499. /**
  51500. * Returns the frag coord builtin.
  51501. *
  51502. * @return {string} The frag coord builtin.
  51503. */
  51504. getFragCoord() {
  51505. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  51506. }
  51507. /**
  51508. * Returns the frag depth builtin.
  51509. *
  51510. * @return {string} The frag depth builtin.
  51511. */
  51512. getFragDepth() {
  51513. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  51514. }
  51515. /**
  51516. * Returns the clip distances builtin.
  51517. *
  51518. * @return {string} The clip distances builtin.
  51519. */
  51520. getClipDistance() {
  51521. return 'varyings.hw_clip_distances';
  51522. }
  51523. /**
  51524. * Whether to flip texture data along its vertical axis or not.
  51525. *
  51526. * @return {boolean} Returns always `false` in context of WGSL.
  51527. */
  51528. isFlipY() {
  51529. return false;
  51530. }
  51531. /**
  51532. * Enables the given directive for the given shader stage.
  51533. *
  51534. * @param {string} name - The directive name.
  51535. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  51536. */
  51537. enableDirective( name, shaderStage = this.shaderStage ) {
  51538. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  51539. stage.add( name );
  51540. }
  51541. /**
  51542. * Returns the directives of the given shader stage as a WGSL string.
  51543. *
  51544. * @param {string} shaderStage - The shader stage.
  51545. * @return {string} A WGSL snippet that enables the directives of the given stage.
  51546. */
  51547. getDirectives( shaderStage ) {
  51548. const snippets = [];
  51549. const directives = this.directives[ shaderStage ];
  51550. if ( directives !== undefined ) {
  51551. for ( const directive of directives ) {
  51552. snippets.push( `enable ${directive};` );
  51553. }
  51554. }
  51555. return snippets.join( '\n' );
  51556. }
  51557. /**
  51558. * Enables the 'subgroups' directive.
  51559. */
  51560. enableSubGroups() {
  51561. this.enableDirective( 'subgroups' );
  51562. }
  51563. /**
  51564. * Enables the 'subgroups-f16' directive.
  51565. */
  51566. enableSubgroupsF16() {
  51567. this.enableDirective( 'subgroups-f16' );
  51568. }
  51569. /**
  51570. * Enables the 'clip_distances' directive.
  51571. */
  51572. enableClipDistances() {
  51573. this.enableDirective( 'clip_distances' );
  51574. }
  51575. /**
  51576. * Enables the 'f16' directive.
  51577. */
  51578. enableShaderF16() {
  51579. this.enableDirective( 'f16' );
  51580. }
  51581. /**
  51582. * Enables the 'dual_source_blending' directive.
  51583. */
  51584. enableDualSourceBlending() {
  51585. this.enableDirective( 'dual_source_blending' );
  51586. }
  51587. /**
  51588. * Enables hardware clipping.
  51589. *
  51590. * @param {string} planeCount - The clipping plane count.
  51591. */
  51592. enableHardwareClipping( planeCount ) {
  51593. this.enableClipDistances();
  51594. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  51595. }
  51596. /**
  51597. * Returns the builtins of the given shader stage as a WGSL string.
  51598. *
  51599. * @param {string} shaderStage - The shader stage.
  51600. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  51601. */
  51602. getBuiltins( shaderStage ) {
  51603. const snippets = [];
  51604. const builtins = this.builtins[ shaderStage ];
  51605. if ( builtins !== undefined ) {
  51606. for ( const { name, property, type } of builtins.values() ) {
  51607. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  51608. }
  51609. }
  51610. return snippets.join( ',\n\t' );
  51611. }
  51612. /**
  51613. * This method should be used when a new scoped buffer is used in context of
  51614. * compute shaders. It adds the array to the internal data structure which is
  51615. * later used to generate the respective WGSL.
  51616. *
  51617. * @param {string} name - The array name.
  51618. * @param {string} scope - The scope.
  51619. * @param {string} bufferType - The buffer type.
  51620. * @param {string} bufferCount - The buffer count.
  51621. * @return {string} The array name.
  51622. */
  51623. getScopedArray( name, scope, bufferType, bufferCount ) {
  51624. if ( this.scopedArrays.has( name ) === false ) {
  51625. this.scopedArrays.set( name, {
  51626. name,
  51627. scope,
  51628. bufferType,
  51629. bufferCount
  51630. } );
  51631. }
  51632. return name;
  51633. }
  51634. /**
  51635. * Returns the scoped arrays of the given shader stage as a WGSL string.
  51636. *
  51637. * @param {string} shaderStage - The shader stage.
  51638. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  51639. * Returns `undefined` when used in the vertex or fragment stage.
  51640. */
  51641. getScopedArrays( shaderStage ) {
  51642. if ( shaderStage !== 'compute' ) {
  51643. return;
  51644. }
  51645. const snippets = [];
  51646. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  51647. const type = this.getType( bufferType );
  51648. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  51649. }
  51650. return snippets.join( '\n' );
  51651. }
  51652. /**
  51653. * Returns the shader attributes of the given shader stage as a WGSL string.
  51654. *
  51655. * @param {string} shaderStage - The shader stage.
  51656. * @return {string} The WGSL snippet that defines the shader attributes.
  51657. */
  51658. getAttributes( shaderStage ) {
  51659. const snippets = [];
  51660. if ( shaderStage === 'compute' ) {
  51661. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  51662. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  51663. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  51664. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  51665. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  51666. this.enableDirective( 'subgroups', shaderStage );
  51667. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  51668. }
  51669. }
  51670. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  51671. const builtins = this.getBuiltins( 'attribute' );
  51672. if ( builtins ) snippets.push( builtins );
  51673. const attributes = this.getAttributesArray();
  51674. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  51675. const attribute = attributes[ index ];
  51676. const name = attribute.name;
  51677. const type = this.getType( attribute.type );
  51678. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  51679. }
  51680. }
  51681. return snippets.join( ',\n\t' );
  51682. }
  51683. /**
  51684. * Returns the members of the given struct type node as a WGSL string.
  51685. *
  51686. * @param {StructTypeNode} struct - The struct type node.
  51687. * @return {string} The WGSL snippet that defines the struct members.
  51688. */
  51689. getStructMembers( struct ) {
  51690. const snippets = [];
  51691. for ( const member of struct.members ) {
  51692. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  51693. let type = this.getType( member.type );
  51694. if ( member.atomic ) {
  51695. type = 'atomic< ' + type + ' >';
  51696. }
  51697. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  51698. }
  51699. if ( struct.output ) {
  51700. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  51701. }
  51702. return snippets.join( ',\n' );
  51703. }
  51704. /**
  51705. * Returns the structs of the given shader stage as a WGSL string.
  51706. *
  51707. * @param {string} shaderStage - The shader stage.
  51708. * @return {string} The WGSL snippet that defines the structs.
  51709. */
  51710. getStructs( shaderStage ) {
  51711. let result = '';
  51712. const structs = this.structs[ shaderStage ];
  51713. if ( structs.length > 0 ) {
  51714. const snippets = [];
  51715. for ( const struct of structs ) {
  51716. let snippet = `struct ${ struct.name } {\n`;
  51717. snippet += this.getStructMembers( struct );
  51718. snippet += '\n};';
  51719. snippets.push( snippet );
  51720. }
  51721. result = '\n' + snippets.join( '\n\n' ) + '\n';
  51722. }
  51723. return result;
  51724. }
  51725. /**
  51726. * Returns a WGSL string representing a variable.
  51727. *
  51728. * @param {string} type - The variable's type.
  51729. * @param {string} name - The variable's name.
  51730. * @param {?number} [count=null] - The array length.
  51731. * @return {string} The WGSL snippet that defines a variable.
  51732. */
  51733. getVar( type, name, count = null ) {
  51734. let snippet = `var ${ name } : `;
  51735. if ( count !== null ) {
  51736. snippet += this.generateArrayDeclaration( type, count );
  51737. } else {
  51738. snippet += this.getType( type );
  51739. }
  51740. return snippet;
  51741. }
  51742. /**
  51743. * Returns the variables of the given shader stage as a WGSL string.
  51744. *
  51745. * @param {string} shaderStage - The shader stage.
  51746. * @return {string} The WGSL snippet that defines the variables.
  51747. */
  51748. getVars( shaderStage ) {
  51749. const snippets = [];
  51750. const vars = this.vars[ shaderStage ];
  51751. if ( vars !== undefined ) {
  51752. for ( const variable of vars ) {
  51753. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  51754. }
  51755. }
  51756. return `\n${ snippets.join( '\n' ) }\n`;
  51757. }
  51758. /**
  51759. * Returns the varyings of the given shader stage as a WGSL string.
  51760. *
  51761. * @param {string} shaderStage - The shader stage.
  51762. * @return {string} The WGSL snippet that defines the varyings.
  51763. */
  51764. getVaryings( shaderStage ) {
  51765. const snippets = [];
  51766. if ( shaderStage === 'vertex' ) {
  51767. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  51768. }
  51769. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  51770. const varyings = this.varyings;
  51771. const vars = this.vars[ shaderStage ];
  51772. for ( let index = 0; index < varyings.length; index ++ ) {
  51773. const varying = varyings[ index ];
  51774. if ( varying.needsInterpolation ) {
  51775. let attributesSnippet = `@location( ${index} )`;
  51776. if ( varying.interpolationType ) {
  51777. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  51778. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  51779. // Otherwise, optimize interpolation when sensible
  51780. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  51781. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  51782. }
  51783. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  51784. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  51785. vars.push( varying );
  51786. }
  51787. }
  51788. }
  51789. const builtins = this.getBuiltins( shaderStage );
  51790. if ( builtins ) snippets.push( builtins );
  51791. const code = snippets.join( ',\n\t' );
  51792. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  51793. }
  51794. isCustomStruct( nodeUniform ) {
  51795. const attribute = nodeUniform.value;
  51796. const bufferNode = nodeUniform.node;
  51797. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  51798. const isStructArray =
  51799. ( bufferNode.value && bufferNode.value.array ) &&
  51800. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  51801. return isAttributeStructType && ! isStructArray;
  51802. }
  51803. /**
  51804. * Returns the uniforms of the given shader stage as a WGSL string.
  51805. *
  51806. * @param {string} shaderStage - The shader stage.
  51807. * @return {string} The WGSL snippet that defines the uniforms.
  51808. */
  51809. getUniforms( shaderStage ) {
  51810. const uniforms = this.uniforms[ shaderStage ];
  51811. const bindingSnippets = [];
  51812. const bufferSnippets = [];
  51813. const structSnippets = [];
  51814. const uniformGroups = {};
  51815. for ( const uniform of uniforms ) {
  51816. const groupName = uniform.groupNode.name;
  51817. const uniformIndexes = this.bindingsIndexes[ groupName ];
  51818. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  51819. const texture = uniform.node.value;
  51820. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  51821. if ( this.isSampleCompare( texture ) ) {
  51822. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  51823. } else {
  51824. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  51825. }
  51826. }
  51827. let textureType;
  51828. let multisampled = '';
  51829. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  51830. if ( primarySamples > 1 ) {
  51831. multisampled = '_multisampled';
  51832. }
  51833. if ( texture.isCubeTexture === true ) {
  51834. textureType = 'texture_cube<f32>';
  51835. } else if ( texture.isDepthTexture === true ) {
  51836. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  51837. textureType = `texture${ multisampled }_2d<f32>`;
  51838. } else {
  51839. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  51840. }
  51841. } else if ( uniform.node.isStorageTextureNode === true ) {
  51842. const format = getFormat( texture );
  51843. const access = this.getStorageAccess( uniform.node, shaderStage );
  51844. const is3D = uniform.node.value.is3DTexture;
  51845. const isArrayTexture = uniform.node.value.isArrayTexture;
  51846. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  51847. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  51848. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  51849. textureType = 'texture_2d_array<f32>';
  51850. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  51851. textureType = 'texture_3d<f32>';
  51852. } else {
  51853. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  51854. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  51855. }
  51856. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  51857. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  51858. const bufferNode = uniform.node;
  51859. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  51860. const bufferCount = bufferNode.bufferCount;
  51861. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  51862. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  51863. if ( this.isCustomStruct( uniform ) ) {
  51864. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  51865. } else {
  51866. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  51867. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  51868. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  51869. }
  51870. } else {
  51871. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  51872. const groupName = uniform.groupNode.name;
  51873. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  51874. index: uniformIndexes.binding ++,
  51875. id: uniformIndexes.group,
  51876. snippets: []
  51877. } );
  51878. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  51879. }
  51880. }
  51881. for ( const name in uniformGroups ) {
  51882. const group = uniformGroups[ name ];
  51883. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  51884. }
  51885. let code = bindingSnippets.join( '\n' );
  51886. code += bufferSnippets.join( '\n' );
  51887. code += structSnippets.join( '\n' );
  51888. return code;
  51889. }
  51890. /**
  51891. * Controls the code build of the shader stages.
  51892. */
  51893. buildCode() {
  51894. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  51895. this.sortBindingGroups();
  51896. for ( const shaderStage in shadersData ) {
  51897. this.shaderStage = shaderStage;
  51898. const stageData = shadersData[ shaderStage ];
  51899. stageData.uniforms = this.getUniforms( shaderStage );
  51900. stageData.attributes = this.getAttributes( shaderStage );
  51901. stageData.varyings = this.getVaryings( shaderStage );
  51902. stageData.structs = this.getStructs( shaderStage );
  51903. stageData.vars = this.getVars( shaderStage );
  51904. stageData.codes = this.getCodes( shaderStage );
  51905. stageData.directives = this.getDirectives( shaderStage );
  51906. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  51907. //
  51908. let flow = '// code\n\n';
  51909. flow += this.flowCode[ shaderStage ];
  51910. const flowNodes = this.flowNodes[ shaderStage ];
  51911. const mainNode = flowNodes[ flowNodes.length - 1 ];
  51912. const outputNode = mainNode.outputNode;
  51913. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  51914. for ( const node of flowNodes ) {
  51915. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  51916. const slotName = node.name;
  51917. if ( slotName ) {
  51918. if ( flow.length > 0 ) flow += '\n';
  51919. flow += `\t// flow -> ${ slotName }\n`;
  51920. }
  51921. flow += `${ flowSlotData.code }\n\t`;
  51922. if ( node === mainNode && shaderStage !== 'compute' ) {
  51923. flow += '// result\n\n\t';
  51924. if ( shaderStage === 'vertex' ) {
  51925. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  51926. } else if ( shaderStage === 'fragment' ) {
  51927. if ( isOutputStruct ) {
  51928. stageData.returnType = outputNode.getNodeType( this );
  51929. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  51930. flow += `return ${ flowSlotData.result };`;
  51931. } else {
  51932. let structSnippet = '\t@location(0) color: vec4<f32>';
  51933. const builtins = this.getBuiltins( 'output' );
  51934. if ( builtins ) structSnippet += ',\n\t' + builtins;
  51935. stageData.returnType = 'OutputStruct';
  51936. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  51937. stageData.structs += '\nvar<private> output : OutputStruct;';
  51938. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  51939. }
  51940. }
  51941. }
  51942. }
  51943. stageData.flow = flow;
  51944. }
  51945. this.shaderStage = null;
  51946. if ( this.material !== null ) {
  51947. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  51948. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  51949. } else {
  51950. // Early strictly validated in computeNode
  51951. const workgroupSize = this.object.workgroupSize;
  51952. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  51953. }
  51954. }
  51955. /**
  51956. * Returns the native shader method name for a given generic name.
  51957. *
  51958. * @param {string} method - The method name to resolve.
  51959. * @param {?string} [output=null] - An optional output.
  51960. * @return {string} The resolved WGSL method name.
  51961. */
  51962. getMethod( method, output = null ) {
  51963. let wgslMethod;
  51964. if ( output !== null ) {
  51965. wgslMethod = this._getWGSLMethod( method + '_' + output );
  51966. }
  51967. if ( wgslMethod === undefined ) {
  51968. wgslMethod = this._getWGSLMethod( method );
  51969. }
  51970. return wgslMethod || method;
  51971. }
  51972. /**
  51973. * Returns the bitcast method name for a given input and outputType.
  51974. *
  51975. * @param {string} type - The output type to bitcast to.
  51976. * @return {string} The resolved WGSL bitcast invocation.
  51977. */
  51978. getBitcastMethod( type ) {
  51979. const dataType = this.getType( type );
  51980. return `bitcast<${ dataType }>`;
  51981. }
  51982. /**
  51983. * Returns the native snippet for a ternary operation.
  51984. *
  51985. * @param {string} condSnippet - The condition determining which expression gets resolved.
  51986. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  51987. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  51988. * @return {string} The resolved method name.
  51989. */
  51990. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  51991. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  51992. }
  51993. /**
  51994. * Returns the WGSL type of the given node data type.
  51995. *
  51996. * @param {string} type - The node data type.
  51997. * @return {string} The WGSL type.
  51998. */
  51999. getType( type ) {
  52000. return wgslTypeLib[ type ] || type;
  52001. }
  52002. /**
  52003. * Whether the requested feature is available or not.
  52004. *
  52005. * @param {string} name - The requested feature.
  52006. * @return {boolean} Whether the requested feature is supported or not.
  52007. */
  52008. isAvailable( name ) {
  52009. let result = supports[ name ];
  52010. if ( result === undefined ) {
  52011. if ( name === 'float32Filterable' ) {
  52012. result = this.renderer.hasFeature( 'float32-filterable' );
  52013. } else if ( name === 'clipDistance' ) {
  52014. result = this.renderer.hasFeature( 'clip-distances' );
  52015. }
  52016. supports[ name ] = result;
  52017. }
  52018. return result;
  52019. }
  52020. /**
  52021. * Returns the native shader method name for a given generic name.
  52022. *
  52023. * @private
  52024. * @param {string} method - The method name to resolve.
  52025. * @return {string} The resolved WGSL method name.
  52026. */
  52027. _getWGSLMethod( method ) {
  52028. if ( wgslPolyfill[ method ] !== undefined ) {
  52029. this._include( method );
  52030. }
  52031. return wgslMethods[ method ];
  52032. }
  52033. /**
  52034. * Includes the given method name into the current
  52035. * function node.
  52036. *
  52037. * @private
  52038. * @param {string} name - The method name to include.
  52039. * @return {CodeNode} The respective code node.
  52040. */
  52041. _include( name ) {
  52042. const codeNode = wgslPolyfill[ name ];
  52043. codeNode.build( this );
  52044. this.addInclude( codeNode );
  52045. return codeNode;
  52046. }
  52047. /**
  52048. * Returns a WGSL vertex shader based on the given shader data.
  52049. *
  52050. * @private
  52051. * @param {Object} shaderData - The shader data.
  52052. * @return {string} The vertex shader.
  52053. */
  52054. _getWGSLVertexCode( shaderData ) {
  52055. return `${ this.getSignature() }
  52056. // directives
  52057. ${shaderData.directives}
  52058. // structs
  52059. ${shaderData.structs}
  52060. // uniforms
  52061. ${shaderData.uniforms}
  52062. // varyings
  52063. ${shaderData.varyings}
  52064. var<private> varyings : VaryingsStruct;
  52065. // codes
  52066. ${shaderData.codes}
  52067. @vertex
  52068. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  52069. // vars
  52070. ${shaderData.vars}
  52071. // flow
  52072. ${shaderData.flow}
  52073. return varyings;
  52074. }
  52075. `;
  52076. }
  52077. /**
  52078. * Returns a WGSL fragment shader based on the given shader data.
  52079. *
  52080. * @private
  52081. * @param {Object} shaderData - The shader data.
  52082. * @return {string} The vertex shader.
  52083. */
  52084. _getWGSLFragmentCode( shaderData ) {
  52085. return `${ this.getSignature() }
  52086. // global
  52087. ${ diagnostics }
  52088. // structs
  52089. ${shaderData.structs}
  52090. // uniforms
  52091. ${shaderData.uniforms}
  52092. // codes
  52093. ${shaderData.codes}
  52094. @fragment
  52095. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  52096. // vars
  52097. ${shaderData.vars}
  52098. // flow
  52099. ${shaderData.flow}
  52100. }
  52101. `;
  52102. }
  52103. /**
  52104. * Returns a WGSL compute shader based on the given shader data.
  52105. *
  52106. * @private
  52107. * @param {Object} shaderData - The shader data.
  52108. * @param {string} workgroupSize - The workgroup size.
  52109. * @return {string} The vertex shader.
  52110. */
  52111. _getWGSLComputeCode( shaderData, workgroupSize ) {
  52112. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  52113. return `${ this.getSignature() }
  52114. // directives
  52115. ${ shaderData.directives }
  52116. // system
  52117. var<private> instanceIndex : u32;
  52118. // locals
  52119. ${ shaderData.scopedArrays }
  52120. // structs
  52121. ${ shaderData.structs }
  52122. // uniforms
  52123. ${ shaderData.uniforms }
  52124. // codes
  52125. ${ shaderData.codes }
  52126. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  52127. fn main( ${ shaderData.attributes } ) {
  52128. // system
  52129. instanceIndex = globalId.x
  52130. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  52131. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  52132. // vars
  52133. ${ shaderData.vars }
  52134. // flow
  52135. ${ shaderData.flow }
  52136. }
  52137. `;
  52138. }
  52139. /**
  52140. * Returns a WGSL struct based on the given name and variables.
  52141. *
  52142. * @private
  52143. * @param {string} name - The struct name.
  52144. * @param {string} vars - The struct variables.
  52145. * @return {string} The WGSL snippet representing a struct.
  52146. */
  52147. _getWGSLStruct( name, vars ) {
  52148. return `
  52149. struct ${name} {
  52150. ${vars}
  52151. };`;
  52152. }
  52153. /**
  52154. * Returns a WGSL struct binding.
  52155. *
  52156. * @private
  52157. * @param {string} name - The struct name.
  52158. * @param {string} vars - The struct variables.
  52159. * @param {string} access - The access.
  52160. * @param {number} [binding=0] - The binding index.
  52161. * @param {number} [group=0] - The group index.
  52162. * @return {string} The WGSL snippet representing a struct binding.
  52163. */
  52164. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  52165. const structName = name + 'Struct';
  52166. const structSnippet = this._getWGSLStruct( structName, vars );
  52167. return `${structSnippet}
  52168. @binding( ${ binding } ) @group( ${ group } )
  52169. var<${access}> ${ name } : ${ structName };`;
  52170. }
  52171. }
  52172. /**
  52173. * A WebGPU backend utility module with common helpers.
  52174. *
  52175. * @private
  52176. */
  52177. class WebGPUUtils {
  52178. /**
  52179. * Constructs a new utility object.
  52180. *
  52181. * @param {WebGPUBackend} backend - The WebGPU backend.
  52182. */
  52183. constructor( backend ) {
  52184. /**
  52185. * A reference to the WebGPU backend.
  52186. *
  52187. * @type {WebGPUBackend}
  52188. */
  52189. this.backend = backend;
  52190. }
  52191. /**
  52192. * Returns the depth/stencil GPU format for the given render context.
  52193. *
  52194. * @param {RenderContext} renderContext - The render context.
  52195. * @return {string} The depth/stencil GPU texture format.
  52196. */
  52197. getCurrentDepthStencilFormat( renderContext ) {
  52198. let format;
  52199. if ( renderContext.depthTexture !== null ) {
  52200. format = this.getTextureFormatGPU( renderContext.depthTexture );
  52201. } else if ( renderContext.depth && renderContext.stencil ) {
  52202. format = GPUTextureFormat.Depth24PlusStencil8;
  52203. } else if ( renderContext.depth ) {
  52204. format = GPUTextureFormat.Depth24Plus;
  52205. }
  52206. return format;
  52207. }
  52208. /**
  52209. * Returns the GPU format for the given texture.
  52210. *
  52211. * @param {Texture} texture - The texture.
  52212. * @return {string} The GPU texture format.
  52213. */
  52214. getTextureFormatGPU( texture ) {
  52215. return this.backend.get( texture ).format;
  52216. }
  52217. /**
  52218. * Returns an object that defines the multi-sampling state of the given texture.
  52219. *
  52220. * @param {Texture} texture - The texture.
  52221. * @return {Object} The multi-sampling state.
  52222. */
  52223. getTextureSampleData( texture ) {
  52224. let samples;
  52225. if ( texture.isFramebufferTexture ) {
  52226. samples = 1;
  52227. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  52228. const renderer = this.backend.renderer;
  52229. const renderTarget = renderer.getRenderTarget();
  52230. samples = renderTarget ? renderTarget.samples : renderer.currentSamples;
  52231. } else if ( texture.renderTarget ) {
  52232. samples = texture.renderTarget.samples;
  52233. }
  52234. samples = samples || 1;
  52235. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  52236. const primarySamples = isMSAA ? 1 : samples;
  52237. return { samples, primarySamples, isMSAA };
  52238. }
  52239. /**
  52240. * Returns the default color attachment's GPU format of the current render context.
  52241. *
  52242. * @param {RenderContext} renderContext - The render context.
  52243. * @return {string} The GPU texture format of the default color attachment.
  52244. */
  52245. getCurrentColorFormat( renderContext ) {
  52246. let format;
  52247. if ( renderContext.textures !== null ) {
  52248. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  52249. } else {
  52250. format = this.getPreferredCanvasFormat(); // default context format
  52251. }
  52252. return format;
  52253. }
  52254. /**
  52255. * Returns the GPU formats of all color attachments of the current render context.
  52256. *
  52257. * @param {RenderContext} renderContext - The render context.
  52258. * @return {Array<string>} The GPU texture formats of all color attachments.
  52259. */
  52260. getCurrentColorFormats( renderContext ) {
  52261. if ( renderContext.textures !== null ) {
  52262. return renderContext.textures.map( t => this.getTextureFormatGPU( t ) );
  52263. } else {
  52264. return [ this.getPreferredCanvasFormat() ]; // default context format
  52265. }
  52266. }
  52267. /**
  52268. * Returns the output color space of the current render context.
  52269. *
  52270. * @param {RenderContext} renderContext - The render context.
  52271. * @return {string} The output color space.
  52272. */
  52273. getCurrentColorSpace( renderContext ) {
  52274. if ( renderContext.textures !== null ) {
  52275. return renderContext.textures[ 0 ].colorSpace;
  52276. }
  52277. return this.backend.renderer.outputColorSpace;
  52278. }
  52279. /**
  52280. * Returns GPU primitive topology for the given object and material.
  52281. *
  52282. * @param {Object3D} object - The 3D object.
  52283. * @param {Material} material - The material.
  52284. * @return {string} The GPU primitive topology.
  52285. */
  52286. getPrimitiveTopology( object, material ) {
  52287. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  52288. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  52289. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  52290. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  52291. }
  52292. /**
  52293. * Returns a modified sample count from the given sample count value.
  52294. *
  52295. * That is required since WebGPU only supports either 1 or 4.
  52296. *
  52297. * @param {number} sampleCount - The input sample count.
  52298. * @return {number} The (potentially updated) output sample count.
  52299. */
  52300. getSampleCount( sampleCount ) {
  52301. return sampleCount >= 4 ? 4 : 1;
  52302. }
  52303. /**
  52304. * Returns the sample count of the given render context.
  52305. *
  52306. * @param {RenderContext} renderContext - The render context.
  52307. * @return {number} The sample count.
  52308. */
  52309. getSampleCountRenderContext( renderContext ) {
  52310. if ( renderContext.textures !== null ) {
  52311. return this.getSampleCount( renderContext.sampleCount );
  52312. }
  52313. return this.getSampleCount( this.backend.renderer.currentSamples );
  52314. }
  52315. /**
  52316. * Returns the preferred canvas format.
  52317. *
  52318. * There is a separate method for this so it's possible to
  52319. * honor edge cases for specific devices.
  52320. *
  52321. * @return {string} The GPU texture format of the canvas.
  52322. */
  52323. getPreferredCanvasFormat() {
  52324. const outputType = this.backend.parameters.outputType;
  52325. if ( outputType === undefined ) {
  52326. return navigator.gpu.getPreferredCanvasFormat();
  52327. } else if ( outputType === UnsignedByteType ) {
  52328. return GPUTextureFormat.BGRA8Unorm;
  52329. } else if ( outputType === HalfFloatType ) {
  52330. return GPUTextureFormat.RGBA16Float;
  52331. } else {
  52332. throw new Error( 'Unsupported outputType' );
  52333. }
  52334. }
  52335. }
  52336. const typedArraysToVertexFormatPrefix = new Map( [
  52337. [ Int8Array, [ 'sint8', 'snorm8' ]],
  52338. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  52339. [ Int16Array, [ 'sint16', 'snorm16' ]],
  52340. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  52341. [ Int32Array, [ 'sint32', 'snorm32' ]],
  52342. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  52343. [ Float32Array, [ 'float32', ]],
  52344. ] );
  52345. if ( typeof Float16Array !== 'undefined' ) {
  52346. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  52347. }
  52348. const typedAttributeToVertexFormatPrefix = new Map( [
  52349. [ Float16BufferAttribute, [ 'float16', ]],
  52350. ] );
  52351. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  52352. [ Int32Array, 'sint32' ],
  52353. [ Int16Array, 'sint32' ], // patch for INT16
  52354. [ Uint32Array, 'uint32' ],
  52355. [ Uint16Array, 'uint32' ], // patch for UINT16
  52356. [ Float32Array, 'float32' ]
  52357. ] );
  52358. /**
  52359. * A WebGPU backend utility module for managing shader attributes.
  52360. *
  52361. * @private
  52362. */
  52363. class WebGPUAttributeUtils {
  52364. /**
  52365. * Constructs a new utility object.
  52366. *
  52367. * @param {WebGPUBackend} backend - The WebGPU backend.
  52368. */
  52369. constructor( backend ) {
  52370. /**
  52371. * A reference to the WebGPU backend.
  52372. *
  52373. * @type {WebGPUBackend}
  52374. */
  52375. this.backend = backend;
  52376. }
  52377. /**
  52378. * Creates the GPU buffer for the given buffer attribute.
  52379. *
  52380. * @param {BufferAttribute} attribute - The buffer attribute.
  52381. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  52382. */
  52383. createAttribute( attribute, usage ) {
  52384. const bufferAttribute = this._getBufferAttribute( attribute );
  52385. const backend = this.backend;
  52386. const bufferData = backend.get( bufferAttribute );
  52387. let buffer = bufferData.buffer;
  52388. if ( buffer === undefined ) {
  52389. const device = backend.device;
  52390. let array = bufferAttribute.array;
  52391. // patch for INT16 and UINT16
  52392. if ( attribute.normalized === false ) {
  52393. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  52394. array = new Int32Array( array );
  52395. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  52396. array = new Uint32Array( array );
  52397. if ( usage & GPUBufferUsage.INDEX ) {
  52398. for ( let i = 0; i < array.length; i ++ ) {
  52399. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  52400. }
  52401. }
  52402. }
  52403. }
  52404. bufferAttribute.array = array;
  52405. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  52406. array = new array.constructor( bufferAttribute.count * 4 );
  52407. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  52408. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  52409. }
  52410. // Update BufferAttribute
  52411. bufferAttribute.itemSize = 4;
  52412. bufferAttribute.array = array;
  52413. bufferData._force3to4BytesAlignment = true;
  52414. }
  52415. // ensure 4 byte alignment
  52416. const byteLength = array.byteLength;
  52417. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  52418. buffer = device.createBuffer( {
  52419. label: bufferAttribute.name,
  52420. size: size,
  52421. usage: usage,
  52422. mappedAtCreation: true
  52423. } );
  52424. new array.constructor( buffer.getMappedRange() ).set( array );
  52425. buffer.unmap();
  52426. bufferData.buffer = buffer;
  52427. }
  52428. }
  52429. /**
  52430. * Updates the GPU buffer of the given buffer attribute.
  52431. *
  52432. * @param {BufferAttribute} attribute - The buffer attribute.
  52433. */
  52434. updateAttribute( attribute ) {
  52435. const bufferAttribute = this._getBufferAttribute( attribute );
  52436. const backend = this.backend;
  52437. const device = backend.device;
  52438. const bufferData = backend.get( bufferAttribute );
  52439. const buffer = backend.get( bufferAttribute ).buffer;
  52440. let array = bufferAttribute.array;
  52441. // if storage buffer ensure 4 byte alignment
  52442. if ( bufferData._force3to4BytesAlignment === true ) {
  52443. array = new array.constructor( bufferAttribute.count * 4 );
  52444. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  52445. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  52446. }
  52447. bufferAttribute.array = array;
  52448. }
  52449. const isTypedArray = this._isTypedArray( array );
  52450. const updateRanges = bufferAttribute.updateRanges;
  52451. if ( updateRanges.length === 0 ) {
  52452. // Not using update ranges
  52453. device.queue.writeBuffer(
  52454. buffer,
  52455. 0,
  52456. array,
  52457. 0
  52458. );
  52459. } else {
  52460. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  52461. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  52462. const range = updateRanges[ i ];
  52463. let dataOffset, size;
  52464. if ( bufferData._force3to4BytesAlignment === true ) {
  52465. const vertexStart = Math.floor( range.start / 3 );
  52466. const vertexCount = Math.ceil( range.count / 3 );
  52467. dataOffset = vertexStart * 4 * byteOffsetFactor;
  52468. size = vertexCount * 4 * byteOffsetFactor;
  52469. } else {
  52470. dataOffset = range.start * byteOffsetFactor;
  52471. size = range.count * byteOffsetFactor;
  52472. }
  52473. const bufferOffset = dataOffset * ( isTypedArray ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  52474. device.queue.writeBuffer(
  52475. buffer,
  52476. bufferOffset,
  52477. array,
  52478. dataOffset,
  52479. size
  52480. );
  52481. }
  52482. bufferAttribute.clearUpdateRanges();
  52483. }
  52484. }
  52485. /**
  52486. * This method creates the vertex buffer layout data which are
  52487. * require when creating a render pipeline for the given render object.
  52488. *
  52489. * @param {RenderObject} renderObject - The render object.
  52490. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  52491. */
  52492. createShaderVertexBuffers( renderObject ) {
  52493. const attributes = renderObject.getAttributes();
  52494. const vertexBuffers = new Map();
  52495. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  52496. const geometryAttribute = attributes[ slot ];
  52497. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  52498. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  52499. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  52500. if ( vertexBufferLayout === undefined ) {
  52501. let arrayStride, stepMode;
  52502. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  52503. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  52504. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  52505. } else {
  52506. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  52507. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  52508. }
  52509. // patch for INT16 and UINT16
  52510. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  52511. arrayStride = 4;
  52512. }
  52513. vertexBufferLayout = {
  52514. arrayStride,
  52515. attributes: [],
  52516. stepMode
  52517. };
  52518. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  52519. }
  52520. const format = this._getVertexFormat( geometryAttribute );
  52521. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  52522. vertexBufferLayout.attributes.push( {
  52523. shaderLocation: slot,
  52524. offset,
  52525. format
  52526. } );
  52527. }
  52528. return Array.from( vertexBuffers.values() );
  52529. }
  52530. /**
  52531. * Destroys the GPU buffer of the given buffer attribute.
  52532. *
  52533. * @param {BufferAttribute} attribute - The buffer attribute.
  52534. */
  52535. destroyAttribute( attribute ) {
  52536. const backend = this.backend;
  52537. const data = backend.get( this._getBufferAttribute( attribute ) );
  52538. data.buffer.destroy();
  52539. backend.delete( attribute );
  52540. }
  52541. /**
  52542. * This method performs a readback operation by moving buffer data from
  52543. * a storage buffer attribute from the GPU to the CPU.
  52544. *
  52545. * @async
  52546. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  52547. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  52548. */
  52549. async getArrayBufferAsync( attribute ) {
  52550. const backend = this.backend;
  52551. const device = backend.device;
  52552. const data = backend.get( this._getBufferAttribute( attribute ) );
  52553. const bufferGPU = data.buffer;
  52554. const size = bufferGPU.size;
  52555. const readBufferGPU = device.createBuffer( {
  52556. label: `${ attribute.name }_readback`,
  52557. size,
  52558. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  52559. } );
  52560. const cmdEncoder = device.createCommandEncoder( {
  52561. label: `readback_encoder_${ attribute.name }`
  52562. } );
  52563. cmdEncoder.copyBufferToBuffer(
  52564. bufferGPU,
  52565. 0,
  52566. readBufferGPU,
  52567. 0,
  52568. size
  52569. );
  52570. const gpuCommands = cmdEncoder.finish();
  52571. device.queue.submit( [ gpuCommands ] );
  52572. await readBufferGPU.mapAsync( GPUMapMode.READ );
  52573. const arrayBuffer = readBufferGPU.getMappedRange();
  52574. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  52575. readBufferGPU.unmap();
  52576. return dstBuffer.buffer;
  52577. }
  52578. /**
  52579. * Returns the vertex format of the given buffer attribute.
  52580. *
  52581. * @private
  52582. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  52583. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  52584. */
  52585. _getVertexFormat( geometryAttribute ) {
  52586. const { itemSize, normalized } = geometryAttribute;
  52587. const ArrayType = geometryAttribute.array.constructor;
  52588. const AttributeType = geometryAttribute.constructor;
  52589. let format;
  52590. if ( itemSize === 1 ) {
  52591. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  52592. } else {
  52593. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  52594. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  52595. if ( prefix ) {
  52596. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  52597. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  52598. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  52599. if ( paddedItemSize % 1 ) {
  52600. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  52601. }
  52602. format = `${prefix}x${paddedItemSize}`;
  52603. }
  52604. }
  52605. if ( ! format ) {
  52606. error( 'WebGPUAttributeUtils: Vertex format not supported yet.' );
  52607. }
  52608. return format;
  52609. }
  52610. /**
  52611. * Returns `true` if the given array is a typed array.
  52612. *
  52613. * @private
  52614. * @param {any} array - The array.
  52615. * @return {boolean} Whether the given array is a typed array or not.
  52616. */
  52617. _isTypedArray( array ) {
  52618. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  52619. }
  52620. /**
  52621. * Utility method for handling interleaved buffer attributes correctly.
  52622. * To process them, their `InterleavedBuffer` is returned.
  52623. *
  52624. * @private
  52625. * @param {BufferAttribute} attribute - The attribute.
  52626. * @return {BufferAttribute|InterleavedBuffer}
  52627. */
  52628. _getBufferAttribute( attribute ) {
  52629. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  52630. return attribute;
  52631. }
  52632. }
  52633. /**
  52634. * A WebGPU backend utility module for managing bindings.
  52635. *
  52636. * When reading the documentation it's helpful to keep in mind that
  52637. * all class definitions starting with 'GPU*' are modules from the
  52638. * WebGPU API. So for example `BindGroup` is a class from the engine
  52639. * whereas `GPUBindGroup` is a class from WebGPU.
  52640. *
  52641. * @private
  52642. */
  52643. class WebGPUBindingUtils {
  52644. /**
  52645. * Constructs a new utility object.
  52646. *
  52647. * @param {WebGPUBackend} backend - The WebGPU backend.
  52648. */
  52649. constructor( backend ) {
  52650. /**
  52651. * A reference to the WebGPU backend.
  52652. *
  52653. * @type {WebGPUBackend}
  52654. */
  52655. this.backend = backend;
  52656. /**
  52657. * A cache for managing bind group layouts.
  52658. *
  52659. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  52660. */
  52661. this.bindGroupLayoutCache = new WeakMap();
  52662. }
  52663. /**
  52664. * Creates a GPU bind group layout for the given bind group.
  52665. *
  52666. * @param {BindGroup} bindGroup - The bind group.
  52667. * @return {GPUBindGroupLayout} The GPU bind group layout.
  52668. */
  52669. createBindingsLayout( bindGroup ) {
  52670. const backend = this.backend;
  52671. const device = backend.device;
  52672. const entries = [];
  52673. let index = 0;
  52674. for ( const binding of bindGroup.bindings ) {
  52675. const bindingGPU = {
  52676. binding: index ++,
  52677. visibility: binding.visibility
  52678. };
  52679. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  52680. const buffer = {}; // GPUBufferBindingLayout
  52681. if ( binding.isStorageBuffer ) {
  52682. if ( binding.visibility & 4 ) {
  52683. // compute
  52684. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  52685. buffer.type = GPUBufferBindingType.Storage;
  52686. } else {
  52687. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  52688. }
  52689. } else {
  52690. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  52691. }
  52692. }
  52693. bindingGPU.buffer = buffer;
  52694. } else if ( binding.isSampledTexture && binding.store ) {
  52695. const storageTexture = {}; // GPUStorageTextureBindingLayout
  52696. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  52697. const access = binding.access;
  52698. if ( access === NodeAccess.READ_WRITE ) {
  52699. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  52700. } else if ( access === NodeAccess.WRITE_ONLY ) {
  52701. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  52702. } else {
  52703. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  52704. }
  52705. if ( binding.texture.isArrayTexture ) {
  52706. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  52707. } else if ( binding.texture.is3DTexture ) {
  52708. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  52709. }
  52710. bindingGPU.storageTexture = storageTexture;
  52711. } else if ( binding.isSampledTexture ) {
  52712. const texture = {}; // GPUTextureBindingLayout
  52713. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  52714. if ( primarySamples > 1 ) {
  52715. texture.multisampled = true;
  52716. if ( ! binding.texture.isDepthTexture ) {
  52717. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  52718. }
  52719. }
  52720. if ( binding.texture.isDepthTexture ) {
  52721. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  52722. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  52723. } else {
  52724. texture.sampleType = GPUTextureSampleType.Depth;
  52725. }
  52726. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  52727. const type = binding.texture.type;
  52728. if ( type === IntType ) {
  52729. texture.sampleType = GPUTextureSampleType.SInt;
  52730. } else if ( type === UnsignedIntType ) {
  52731. texture.sampleType = GPUTextureSampleType.UInt;
  52732. } else if ( type === FloatType ) {
  52733. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  52734. texture.sampleType = GPUTextureSampleType.Float;
  52735. } else {
  52736. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  52737. }
  52738. }
  52739. }
  52740. if ( binding.isSampledCubeTexture ) {
  52741. texture.viewDimension = GPUTextureViewDimension.Cube;
  52742. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  52743. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  52744. } else if ( binding.isSampledTexture3D ) {
  52745. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  52746. }
  52747. bindingGPU.texture = texture;
  52748. } else if ( binding.isSampler ) {
  52749. const sampler = {}; // GPUSamplerBindingLayout
  52750. if ( binding.texture.isDepthTexture ) {
  52751. if ( binding.texture.compareFunction !== null ) {
  52752. sampler.type = GPUSamplerBindingType.Comparison;
  52753. } else if ( backend.compatibilityMode ) {
  52754. sampler.type = GPUSamplerBindingType.NonFiltering;
  52755. }
  52756. }
  52757. bindingGPU.sampler = sampler;
  52758. } else {
  52759. error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  52760. }
  52761. entries.push( bindingGPU );
  52762. }
  52763. return device.createBindGroupLayout( { entries } );
  52764. }
  52765. /**
  52766. * Creates bindings from the given bind group definition.
  52767. *
  52768. * @param {BindGroup} bindGroup - The bind group.
  52769. * @param {Array<BindGroup>} bindings - Array of bind groups.
  52770. * @param {number} cacheIndex - The cache index.
  52771. * @param {number} version - The version.
  52772. */
  52773. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  52774. const { backend, bindGroupLayoutCache } = this;
  52775. const bindingsData = backend.get( bindGroup );
  52776. // setup (static) binding layout and (dynamic) binding group
  52777. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  52778. if ( bindLayoutGPU === undefined ) {
  52779. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  52780. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  52781. }
  52782. let bindGroupGPU;
  52783. if ( cacheIndex > 0 ) {
  52784. if ( bindingsData.groups === undefined ) {
  52785. bindingsData.groups = [];
  52786. bindingsData.versions = [];
  52787. }
  52788. if ( bindingsData.versions[ cacheIndex ] === version ) {
  52789. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  52790. }
  52791. }
  52792. if ( bindGroupGPU === undefined ) {
  52793. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  52794. if ( cacheIndex > 0 ) {
  52795. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  52796. bindingsData.versions[ cacheIndex ] = version;
  52797. }
  52798. }
  52799. bindingsData.group = bindGroupGPU;
  52800. bindingsData.layout = bindLayoutGPU;
  52801. }
  52802. /**
  52803. * Updates a buffer binding.
  52804. *
  52805. * @param {Buffer} binding - The buffer binding to update.
  52806. */
  52807. updateBinding( binding ) {
  52808. const backend = this.backend;
  52809. const device = backend.device;
  52810. const buffer = binding.buffer;
  52811. const bufferGPU = backend.get( binding ).buffer;
  52812. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  52813. }
  52814. /**
  52815. * Creates a GPU bind group for the camera index.
  52816. *
  52817. * @param {Uint32Array} data - The index data.
  52818. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  52819. * @return {GPUBindGroup} The GPU bind group.
  52820. */
  52821. createBindGroupIndex( data, layout ) {
  52822. const backend = this.backend;
  52823. const device = backend.device;
  52824. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  52825. const index = data[ 0 ];
  52826. const buffer = device.createBuffer( {
  52827. label: 'bindingCameraIndex_' + index,
  52828. size: 16, // uint(4) * 4
  52829. usage: usage
  52830. } );
  52831. device.queue.writeBuffer( buffer, 0, data, 0 );
  52832. const entries = [ { binding: 0, resource: { buffer } } ];
  52833. return device.createBindGroup( {
  52834. label: 'bindGroupCameraIndex_' + index,
  52835. layout,
  52836. entries
  52837. } );
  52838. }
  52839. /**
  52840. * Creates a GPU bind group for the given bind group and GPU layout.
  52841. *
  52842. * @param {BindGroup} bindGroup - The bind group.
  52843. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  52844. * @return {GPUBindGroup} The GPU bind group.
  52845. */
  52846. createBindGroup( bindGroup, layoutGPU ) {
  52847. const backend = this.backend;
  52848. const device = backend.device;
  52849. let bindingPoint = 0;
  52850. const entriesGPU = [];
  52851. for ( const binding of bindGroup.bindings ) {
  52852. if ( binding.isUniformBuffer ) {
  52853. const bindingData = backend.get( binding );
  52854. if ( bindingData.buffer === undefined ) {
  52855. const byteLength = binding.byteLength;
  52856. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  52857. const bufferGPU = device.createBuffer( {
  52858. label: 'bindingBuffer_' + binding.name,
  52859. size: byteLength,
  52860. usage: usage
  52861. } );
  52862. bindingData.buffer = bufferGPU;
  52863. }
  52864. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  52865. } else if ( binding.isStorageBuffer ) {
  52866. const bindingData = backend.get( binding );
  52867. if ( bindingData.buffer === undefined ) {
  52868. const attribute = binding.attribute;
  52869. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  52870. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  52871. bindingData.buffer = backend.get( attribute ).buffer;
  52872. }
  52873. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  52874. } else if ( binding.isSampledTexture ) {
  52875. const textureData = backend.get( binding.texture );
  52876. let resourceGPU;
  52877. if ( textureData.externalTexture !== undefined ) {
  52878. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  52879. } else {
  52880. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  52881. const baseMipLevel = binding.store ? binding.mipLevel : 0;
  52882. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  52883. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  52884. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  52885. }
  52886. propertyName += `-${ mipLevelCount }-${ baseMipLevel }`;
  52887. resourceGPU = textureData[ propertyName ];
  52888. if ( resourceGPU === undefined ) {
  52889. const aspectGPU = GPUTextureAspect.All;
  52890. let dimensionViewGPU;
  52891. if ( binding.isSampledCubeTexture ) {
  52892. dimensionViewGPU = GPUTextureViewDimension.Cube;
  52893. } else if ( binding.isSampledTexture3D ) {
  52894. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  52895. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  52896. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  52897. } else {
  52898. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  52899. }
  52900. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount, baseMipLevel } );
  52901. }
  52902. }
  52903. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  52904. } else if ( binding.isSampler ) {
  52905. const textureGPU = backend.get( binding.texture );
  52906. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  52907. }
  52908. bindingPoint ++;
  52909. }
  52910. return device.createBindGroup( {
  52911. label: 'bindGroup_' + bindGroup.name,
  52912. layout: layoutGPU,
  52913. entries: entriesGPU
  52914. } );
  52915. }
  52916. }
  52917. /**
  52918. * A WebGPU backend utility module for managing pipelines.
  52919. *
  52920. * @private
  52921. */
  52922. class WebGPUPipelineUtils {
  52923. /**
  52924. * Constructs a new utility object.
  52925. *
  52926. * @param {WebGPUBackend} backend - The WebGPU backend.
  52927. */
  52928. constructor( backend ) {
  52929. /**
  52930. * A reference to the WebGPU backend.
  52931. *
  52932. * @type {WebGPUBackend}
  52933. */
  52934. this.backend = backend;
  52935. /**
  52936. * A Weak Map that tracks the active pipeline for render or compute passes.
  52937. *
  52938. * @private
  52939. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  52940. */
  52941. this._activePipelines = new WeakMap();
  52942. }
  52943. /**
  52944. * Sets the given pipeline for the given pass. The method makes sure to only set the
  52945. * pipeline when necessary.
  52946. *
  52947. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  52948. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  52949. */
  52950. setPipeline( pass, pipeline ) {
  52951. const currentPipeline = this._activePipelines.get( pass );
  52952. if ( currentPipeline !== pipeline ) {
  52953. pass.setPipeline( pipeline );
  52954. this._activePipelines.set( pass, pipeline );
  52955. }
  52956. }
  52957. /**
  52958. * Returns the sample count derived from the given render context.
  52959. *
  52960. * @private
  52961. * @param {RenderContext} renderContext - The render context.
  52962. * @return {number} The sample count.
  52963. */
  52964. _getSampleCount( renderContext ) {
  52965. return this.backend.utils.getSampleCountRenderContext( renderContext );
  52966. }
  52967. /**
  52968. * Creates a render pipeline for the given render object.
  52969. *
  52970. * @param {RenderObject} renderObject - The render object.
  52971. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  52972. */
  52973. createRenderPipeline( renderObject, promises ) {
  52974. const { object, material, geometry, pipeline } = renderObject;
  52975. const { vertexProgram, fragmentProgram } = pipeline;
  52976. const backend = this.backend;
  52977. const device = backend.device;
  52978. const utils = backend.utils;
  52979. const pipelineData = backend.get( pipeline );
  52980. // bind group layouts
  52981. const bindGroupLayouts = [];
  52982. for ( const bindGroup of renderObject.getBindings() ) {
  52983. const bindingsData = backend.get( bindGroup );
  52984. bindGroupLayouts.push( bindingsData.layout );
  52985. }
  52986. // vertex buffers
  52987. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  52988. // blending
  52989. let blending;
  52990. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  52991. blending = this._getBlending( material );
  52992. }
  52993. // stencil
  52994. let stencilFront = {};
  52995. if ( material.stencilWrite === true ) {
  52996. stencilFront = {
  52997. compare: this._getStencilCompare( material ),
  52998. failOp: this._getStencilOperation( material.stencilFail ),
  52999. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  53000. passOp: this._getStencilOperation( material.stencilZPass )
  53001. };
  53002. }
  53003. const colorWriteMask = this._getColorWriteMask( material );
  53004. const targets = [];
  53005. if ( renderObject.context.textures !== null ) {
  53006. const textures = renderObject.context.textures;
  53007. for ( let i = 0; i < textures.length; i ++ ) {
  53008. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  53009. targets.push( {
  53010. format: colorFormat,
  53011. blend: blending,
  53012. writeMask: colorWriteMask
  53013. } );
  53014. }
  53015. } else {
  53016. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  53017. targets.push( {
  53018. format: colorFormat,
  53019. blend: blending,
  53020. writeMask: colorWriteMask
  53021. } );
  53022. }
  53023. const vertexModule = backend.get( vertexProgram ).module;
  53024. const fragmentModule = backend.get( fragmentProgram ).module;
  53025. const primitiveState = this._getPrimitiveState( object, geometry, material );
  53026. const depthCompare = this._getDepthCompare( material );
  53027. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  53028. const sampleCount = this._getSampleCount( renderObject.context );
  53029. const pipelineDescriptor = {
  53030. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  53031. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  53032. fragment: Object.assign( {}, fragmentModule, { targets } ),
  53033. primitive: primitiveState,
  53034. multisample: {
  53035. count: sampleCount,
  53036. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  53037. },
  53038. layout: device.createPipelineLayout( {
  53039. bindGroupLayouts
  53040. } )
  53041. };
  53042. const depthStencil = {};
  53043. const renderDepth = renderObject.context.depth;
  53044. const renderStencil = renderObject.context.stencil;
  53045. if ( renderDepth === true || renderStencil === true ) {
  53046. if ( renderDepth === true ) {
  53047. depthStencil.format = depthStencilFormat;
  53048. depthStencil.depthWriteEnabled = material.depthWrite;
  53049. depthStencil.depthCompare = depthCompare;
  53050. }
  53051. if ( renderStencil === true ) {
  53052. depthStencil.stencilFront = stencilFront;
  53053. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  53054. depthStencil.stencilReadMask = material.stencilFuncMask;
  53055. depthStencil.stencilWriteMask = material.stencilWriteMask;
  53056. }
  53057. if ( material.polygonOffset === true ) {
  53058. depthStencil.depthBias = material.polygonOffsetUnits;
  53059. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  53060. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  53061. }
  53062. pipelineDescriptor.depthStencil = depthStencil;
  53063. }
  53064. // create pipeline
  53065. device.pushErrorScope( 'validation' );
  53066. if ( promises === null ) {
  53067. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  53068. device.popErrorScope().then( ( err ) => {
  53069. if ( err !== null ) {
  53070. pipelineData.error = true;
  53071. error( err.message );
  53072. }
  53073. } );
  53074. } else {
  53075. const p = new Promise( async ( resolve /*, reject*/ ) => {
  53076. try {
  53077. pipelineData.pipeline = await device.createRenderPipelineAsync( pipelineDescriptor );
  53078. } catch ( err ) { }
  53079. const errorScope = await device.popErrorScope();
  53080. if ( errorScope !== null ) {
  53081. pipelineData.error = true;
  53082. error( errorScope.message );
  53083. }
  53084. resolve();
  53085. } );
  53086. promises.push( p );
  53087. }
  53088. }
  53089. /**
  53090. * Creates GPU render bundle encoder for the given render context.
  53091. *
  53092. * @param {RenderContext} renderContext - The render context.
  53093. * @param {?string} [label='renderBundleEncoder'] - The label.
  53094. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  53095. */
  53096. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  53097. const backend = this.backend;
  53098. const { utils, device } = backend;
  53099. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  53100. const colorFormats = utils.getCurrentColorFormats( renderContext );
  53101. const sampleCount = this._getSampleCount( renderContext );
  53102. const descriptor = {
  53103. label,
  53104. colorFormats,
  53105. depthStencilFormat,
  53106. sampleCount
  53107. };
  53108. return device.createRenderBundleEncoder( descriptor );
  53109. }
  53110. /**
  53111. * Creates a compute pipeline for the given compute node.
  53112. *
  53113. * @param {ComputePipeline} pipeline - The compute pipeline.
  53114. * @param {Array<BindGroup>} bindings - The bindings.
  53115. */
  53116. createComputePipeline( pipeline, bindings ) {
  53117. const backend = this.backend;
  53118. const device = backend.device;
  53119. const computeProgram = backend.get( pipeline.computeProgram ).module;
  53120. const pipelineGPU = backend.get( pipeline );
  53121. // bind group layouts
  53122. const bindGroupLayouts = [];
  53123. for ( const bindingsGroup of bindings ) {
  53124. const bindingsData = backend.get( bindingsGroup );
  53125. bindGroupLayouts.push( bindingsData.layout );
  53126. }
  53127. pipelineGPU.pipeline = device.createComputePipeline( {
  53128. compute: computeProgram,
  53129. layout: device.createPipelineLayout( {
  53130. bindGroupLayouts
  53131. } )
  53132. } );
  53133. }
  53134. /**
  53135. * Returns the blending state as a descriptor object required
  53136. * for the pipeline creation.
  53137. *
  53138. * @private
  53139. * @param {Material} material - The material.
  53140. * @return {Object} The blending state.
  53141. */
  53142. _getBlending( material ) {
  53143. let color, alpha;
  53144. const blending = material.blending;
  53145. const blendSrc = material.blendSrc;
  53146. const blendDst = material.blendDst;
  53147. const blendEquation = material.blendEquation;
  53148. if ( blending === CustomBlending ) {
  53149. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  53150. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  53151. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  53152. color = {
  53153. srcFactor: this._getBlendFactor( blendSrc ),
  53154. dstFactor: this._getBlendFactor( blendDst ),
  53155. operation: this._getBlendOperation( blendEquation )
  53156. };
  53157. alpha = {
  53158. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  53159. dstFactor: this._getBlendFactor( blendDstAlpha ),
  53160. operation: this._getBlendOperation( blendEquationAlpha )
  53161. };
  53162. } else {
  53163. const premultipliedAlpha = material.premultipliedAlpha;
  53164. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  53165. color = {
  53166. srcFactor: srcRGB,
  53167. dstFactor: dstRGB,
  53168. operation: GPUBlendOperation.Add
  53169. };
  53170. alpha = {
  53171. srcFactor: srcAlpha,
  53172. dstFactor: dstAlpha,
  53173. operation: GPUBlendOperation.Add
  53174. };
  53175. };
  53176. if ( premultipliedAlpha ) {
  53177. switch ( blending ) {
  53178. case NormalBlending:
  53179. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  53180. break;
  53181. case AdditiveBlending:
  53182. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  53183. break;
  53184. case SubtractiveBlending:
  53185. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  53186. break;
  53187. case MultiplyBlending:
  53188. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  53189. break;
  53190. }
  53191. } else {
  53192. switch ( blending ) {
  53193. case NormalBlending:
  53194. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  53195. break;
  53196. case AdditiveBlending:
  53197. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  53198. break;
  53199. case SubtractiveBlending:
  53200. error( 'WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true' );
  53201. break;
  53202. case MultiplyBlending:
  53203. error( 'WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true' );
  53204. break;
  53205. }
  53206. }
  53207. }
  53208. if ( color !== undefined && alpha !== undefined ) {
  53209. return { color, alpha };
  53210. } else {
  53211. error( 'WebGPURenderer: Invalid blending: ', blending );
  53212. }
  53213. }
  53214. /**
  53215. * Returns the GPU blend factor which is required for the pipeline creation.
  53216. *
  53217. * @private
  53218. * @param {number} blend - The blend factor as a three.js constant.
  53219. * @return {string} The GPU blend factor.
  53220. */
  53221. _getBlendFactor( blend ) {
  53222. let blendFactor;
  53223. switch ( blend ) {
  53224. case ZeroFactor:
  53225. blendFactor = GPUBlendFactor.Zero;
  53226. break;
  53227. case OneFactor:
  53228. blendFactor = GPUBlendFactor.One;
  53229. break;
  53230. case SrcColorFactor:
  53231. blendFactor = GPUBlendFactor.Src;
  53232. break;
  53233. case OneMinusSrcColorFactor:
  53234. blendFactor = GPUBlendFactor.OneMinusSrc;
  53235. break;
  53236. case SrcAlphaFactor:
  53237. blendFactor = GPUBlendFactor.SrcAlpha;
  53238. break;
  53239. case OneMinusSrcAlphaFactor:
  53240. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  53241. break;
  53242. case DstColorFactor:
  53243. blendFactor = GPUBlendFactor.Dst;
  53244. break;
  53245. case OneMinusDstColorFactor:
  53246. blendFactor = GPUBlendFactor.OneMinusDst;
  53247. break;
  53248. case DstAlphaFactor:
  53249. blendFactor = GPUBlendFactor.DstAlpha;
  53250. break;
  53251. case OneMinusDstAlphaFactor:
  53252. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  53253. break;
  53254. case SrcAlphaSaturateFactor:
  53255. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  53256. break;
  53257. case BlendColorFactor:
  53258. blendFactor = GPUBlendFactor.Constant;
  53259. break;
  53260. case OneMinusBlendColorFactor:
  53261. blendFactor = GPUBlendFactor.OneMinusConstant;
  53262. break;
  53263. default:
  53264. error( 'WebGPURenderer: Blend factor not supported.', blend );
  53265. }
  53266. return blendFactor;
  53267. }
  53268. /**
  53269. * Returns the GPU stencil compare function which is required for the pipeline creation.
  53270. *
  53271. * @private
  53272. * @param {Material} material - The material.
  53273. * @return {string} The GPU stencil compare function.
  53274. */
  53275. _getStencilCompare( material ) {
  53276. let stencilCompare;
  53277. const stencilFunc = material.stencilFunc;
  53278. switch ( stencilFunc ) {
  53279. case NeverStencilFunc:
  53280. stencilCompare = GPUCompareFunction.Never;
  53281. break;
  53282. case AlwaysStencilFunc:
  53283. stencilCompare = GPUCompareFunction.Always;
  53284. break;
  53285. case LessStencilFunc:
  53286. stencilCompare = GPUCompareFunction.Less;
  53287. break;
  53288. case LessEqualStencilFunc:
  53289. stencilCompare = GPUCompareFunction.LessEqual;
  53290. break;
  53291. case EqualStencilFunc:
  53292. stencilCompare = GPUCompareFunction.Equal;
  53293. break;
  53294. case GreaterEqualStencilFunc:
  53295. stencilCompare = GPUCompareFunction.GreaterEqual;
  53296. break;
  53297. case GreaterStencilFunc:
  53298. stencilCompare = GPUCompareFunction.Greater;
  53299. break;
  53300. case NotEqualStencilFunc:
  53301. stencilCompare = GPUCompareFunction.NotEqual;
  53302. break;
  53303. default:
  53304. error( 'WebGPURenderer: Invalid stencil function.', stencilFunc );
  53305. }
  53306. return stencilCompare;
  53307. }
  53308. /**
  53309. * Returns the GPU stencil operation which is required for the pipeline creation.
  53310. *
  53311. * @private
  53312. * @param {number} op - A three.js constant defining the stencil operation.
  53313. * @return {string} The GPU stencil operation.
  53314. */
  53315. _getStencilOperation( op ) {
  53316. let stencilOperation;
  53317. switch ( op ) {
  53318. case KeepStencilOp:
  53319. stencilOperation = GPUStencilOperation.Keep;
  53320. break;
  53321. case ZeroStencilOp:
  53322. stencilOperation = GPUStencilOperation.Zero;
  53323. break;
  53324. case ReplaceStencilOp:
  53325. stencilOperation = GPUStencilOperation.Replace;
  53326. break;
  53327. case InvertStencilOp:
  53328. stencilOperation = GPUStencilOperation.Invert;
  53329. break;
  53330. case IncrementStencilOp:
  53331. stencilOperation = GPUStencilOperation.IncrementClamp;
  53332. break;
  53333. case DecrementStencilOp:
  53334. stencilOperation = GPUStencilOperation.DecrementClamp;
  53335. break;
  53336. case IncrementWrapStencilOp:
  53337. stencilOperation = GPUStencilOperation.IncrementWrap;
  53338. break;
  53339. case DecrementWrapStencilOp:
  53340. stencilOperation = GPUStencilOperation.DecrementWrap;
  53341. break;
  53342. default:
  53343. error( 'WebGPURenderer: Invalid stencil operation.', stencilOperation );
  53344. }
  53345. return stencilOperation;
  53346. }
  53347. /**
  53348. * Returns the GPU blend operation which is required for the pipeline creation.
  53349. *
  53350. * @private
  53351. * @param {number} blendEquation - A three.js constant defining the blend equation.
  53352. * @return {string} The GPU blend operation.
  53353. */
  53354. _getBlendOperation( blendEquation ) {
  53355. let blendOperation;
  53356. switch ( blendEquation ) {
  53357. case AddEquation:
  53358. blendOperation = GPUBlendOperation.Add;
  53359. break;
  53360. case SubtractEquation:
  53361. blendOperation = GPUBlendOperation.Subtract;
  53362. break;
  53363. case ReverseSubtractEquation:
  53364. blendOperation = GPUBlendOperation.ReverseSubtract;
  53365. break;
  53366. case MinEquation:
  53367. blendOperation = GPUBlendOperation.Min;
  53368. break;
  53369. case MaxEquation:
  53370. blendOperation = GPUBlendOperation.Max;
  53371. break;
  53372. default:
  53373. error( 'WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  53374. }
  53375. return blendOperation;
  53376. }
  53377. /**
  53378. * Returns the primitive state as a descriptor object required
  53379. * for the pipeline creation.
  53380. *
  53381. * @private
  53382. * @param {Object3D} object - The 3D object.
  53383. * @param {BufferGeometry} geometry - The geometry.
  53384. * @param {Material} material - The material.
  53385. * @return {Object} The primitive state.
  53386. */
  53387. _getPrimitiveState( object, geometry, material ) {
  53388. const descriptor = {};
  53389. const utils = this.backend.utils;
  53390. //
  53391. descriptor.topology = utils.getPrimitiveTopology( object, material );
  53392. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  53393. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  53394. }
  53395. //
  53396. let flipSided = ( material.side === BackSide );
  53397. if ( object.isMesh && object.matrixWorld.determinant() < 0 ) flipSided = ! flipSided;
  53398. descriptor.frontFace = ( flipSided === true ) ? GPUFrontFace.CW : GPUFrontFace.CCW;
  53399. //
  53400. descriptor.cullMode = ( material.side === DoubleSide ) ? GPUCullMode.None : GPUCullMode.Back;
  53401. return descriptor;
  53402. }
  53403. /**
  53404. * Returns the GPU color write mask which is required for the pipeline creation.
  53405. *
  53406. * @private
  53407. * @param {Material} material - The material.
  53408. * @return {number} The GPU color write mask.
  53409. */
  53410. _getColorWriteMask( material ) {
  53411. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  53412. }
  53413. /**
  53414. * Returns the GPU depth compare function which is required for the pipeline creation.
  53415. *
  53416. * @private
  53417. * @param {Material} material - The material.
  53418. * @return {string} The GPU depth compare function.
  53419. */
  53420. _getDepthCompare( material ) {
  53421. let depthCompare;
  53422. if ( material.depthTest === false ) {
  53423. depthCompare = GPUCompareFunction.Always;
  53424. } else {
  53425. const depthFunc = material.depthFunc;
  53426. switch ( depthFunc ) {
  53427. case NeverDepth:
  53428. depthCompare = GPUCompareFunction.Never;
  53429. break;
  53430. case AlwaysDepth:
  53431. depthCompare = GPUCompareFunction.Always;
  53432. break;
  53433. case LessDepth:
  53434. depthCompare = GPUCompareFunction.Less;
  53435. break;
  53436. case LessEqualDepth:
  53437. depthCompare = GPUCompareFunction.LessEqual;
  53438. break;
  53439. case EqualDepth:
  53440. depthCompare = GPUCompareFunction.Equal;
  53441. break;
  53442. case GreaterEqualDepth:
  53443. depthCompare = GPUCompareFunction.GreaterEqual;
  53444. break;
  53445. case GreaterDepth:
  53446. depthCompare = GPUCompareFunction.Greater;
  53447. break;
  53448. case NotEqualDepth:
  53449. depthCompare = GPUCompareFunction.NotEqual;
  53450. break;
  53451. default:
  53452. error( 'WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  53453. }
  53454. }
  53455. return depthCompare;
  53456. }
  53457. }
  53458. /**
  53459. * Manages a pool of WebGPU timestamp queries for performance measurement.
  53460. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  53461. *
  53462. * @augments TimestampQueryPool
  53463. */
  53464. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  53465. /**
  53466. * Creates a new WebGPU timestamp query pool.
  53467. *
  53468. * @param {GPUDevice} device - The WebGPU device to create queries on.
  53469. * @param {string} type - The type identifier for this query pool.
  53470. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  53471. */
  53472. constructor( device, type, maxQueries = 2048 ) {
  53473. super( maxQueries );
  53474. this.device = device;
  53475. this.type = type;
  53476. this.querySet = this.device.createQuerySet( {
  53477. type: 'timestamp',
  53478. count: this.maxQueries,
  53479. label: `queryset_global_timestamp_${type}`
  53480. } );
  53481. const bufferSize = this.maxQueries * 8;
  53482. this.resolveBuffer = this.device.createBuffer( {
  53483. label: `buffer_timestamp_resolve_${type}`,
  53484. size: bufferSize,
  53485. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  53486. } );
  53487. this.resultBuffer = this.device.createBuffer( {
  53488. label: `buffer_timestamp_result_${type}`,
  53489. size: bufferSize,
  53490. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  53491. } );
  53492. }
  53493. /**
  53494. * Allocates a pair of queries for a given render context.
  53495. *
  53496. * @param {string} uid - A unique identifier for the render context.
  53497. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  53498. */
  53499. allocateQueriesForContext( uid ) {
  53500. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  53501. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  53502. 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() } ).` );
  53503. return null;
  53504. }
  53505. const baseOffset = this.currentQueryIndex;
  53506. this.currentQueryIndex += 2;
  53507. this.queryOffsets.set( uid, baseOffset );
  53508. return baseOffset;
  53509. }
  53510. /**
  53511. * Asynchronously resolves all pending queries and returns the total duration.
  53512. * If there's already a pending resolve operation, returns that promise instead.
  53513. *
  53514. * @async
  53515. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  53516. */
  53517. async resolveQueriesAsync() {
  53518. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  53519. return this.lastValue;
  53520. }
  53521. if ( this.pendingResolve ) {
  53522. return this.pendingResolve;
  53523. }
  53524. this.pendingResolve = this._resolveQueries();
  53525. try {
  53526. const result = await this.pendingResolve;
  53527. return result;
  53528. } finally {
  53529. this.pendingResolve = null;
  53530. }
  53531. }
  53532. /**
  53533. * Internal method to resolve queries and calculate total duration.
  53534. *
  53535. * @async
  53536. * @private
  53537. * @returns {Promise<number>} The total duration in milliseconds.
  53538. */
  53539. async _resolveQueries() {
  53540. if ( this.isDisposed ) {
  53541. return this.lastValue;
  53542. }
  53543. try {
  53544. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  53545. return this.lastValue;
  53546. }
  53547. const currentOffsets = new Map( this.queryOffsets );
  53548. const queryCount = this.currentQueryIndex;
  53549. const bytesUsed = queryCount * 8;
  53550. // Reset state before GPU work
  53551. this.currentQueryIndex = 0;
  53552. this.queryOffsets.clear();
  53553. const commandEncoder = this.device.createCommandEncoder();
  53554. commandEncoder.resolveQuerySet(
  53555. this.querySet,
  53556. 0,
  53557. queryCount,
  53558. this.resolveBuffer,
  53559. 0
  53560. );
  53561. commandEncoder.copyBufferToBuffer(
  53562. this.resolveBuffer,
  53563. 0,
  53564. this.resultBuffer,
  53565. 0,
  53566. bytesUsed
  53567. );
  53568. const commandBuffer = commandEncoder.finish();
  53569. this.device.queue.submit( [ commandBuffer ] );
  53570. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  53571. return this.lastValue;
  53572. }
  53573. // Create and track the mapping operation
  53574. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  53575. if ( this.isDisposed ) {
  53576. if ( this.resultBuffer.mapState === 'mapped' ) {
  53577. this.resultBuffer.unmap();
  53578. }
  53579. return this.lastValue;
  53580. }
  53581. //
  53582. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  53583. const framesDuration = {};
  53584. const frames = [];
  53585. for ( const [ uid, baseOffset ] of currentOffsets ) {
  53586. const match = uid.match( /^(.*):f(\d+)$/ );
  53587. const frame = parseInt( match[ 2 ] );
  53588. if ( frames.includes( frame ) === false ) {
  53589. frames.push( frame );
  53590. }
  53591. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  53592. const startTime = times[ baseOffset ];
  53593. const endTime = times[ baseOffset + 1 ];
  53594. const duration = Number( endTime - startTime ) / 1e6;
  53595. this.timestamps.set( uid, duration );
  53596. framesDuration[ frame ] += duration;
  53597. }
  53598. // Return the total duration of the last frame
  53599. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  53600. this.resultBuffer.unmap();
  53601. this.lastValue = totalDuration;
  53602. this.frames = frames;
  53603. return totalDuration;
  53604. } catch ( error ) {
  53605. error( 'Error resolving queries:', error );
  53606. if ( this.resultBuffer.mapState === 'mapped' ) {
  53607. this.resultBuffer.unmap();
  53608. }
  53609. return this.lastValue;
  53610. }
  53611. }
  53612. /**
  53613. * Dispose of the query pool.
  53614. *
  53615. * @async
  53616. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  53617. */
  53618. async dispose() {
  53619. if ( this.isDisposed ) {
  53620. return;
  53621. }
  53622. this.isDisposed = true;
  53623. // Wait for pending resolve operation
  53624. if ( this.pendingResolve ) {
  53625. try {
  53626. await this.pendingResolve;
  53627. } catch ( error ) {
  53628. error( 'Error waiting for pending resolve:', error );
  53629. }
  53630. }
  53631. // Ensure buffer is unmapped before destroying
  53632. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  53633. try {
  53634. this.resultBuffer.unmap();
  53635. } catch ( error ) {
  53636. error( 'Error unmapping buffer:', error );
  53637. }
  53638. }
  53639. // Destroy resources
  53640. if ( this.querySet ) {
  53641. this.querySet.destroy();
  53642. this.querySet = null;
  53643. }
  53644. if ( this.resolveBuffer ) {
  53645. this.resolveBuffer.destroy();
  53646. this.resolveBuffer = null;
  53647. }
  53648. if ( this.resultBuffer ) {
  53649. this.resultBuffer.destroy();
  53650. this.resultBuffer = null;
  53651. }
  53652. this.queryOffsets.clear();
  53653. this.pendingResolve = null;
  53654. }
  53655. }
  53656. /*// debugger tools
  53657. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  53658. //*/
  53659. /**
  53660. * A backend implementation targeting WebGPU.
  53661. *
  53662. * @private
  53663. * @augments Backend
  53664. */
  53665. class WebGPUBackend extends Backend {
  53666. /**
  53667. * WebGPUBackend options.
  53668. *
  53669. * @typedef {Object} WebGPUBackend~Options
  53670. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  53671. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  53672. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  53673. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  53674. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  53675. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  53676. * @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.
  53677. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  53678. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  53679. * @property {string} [powerPreference=undefined] - The power preference.
  53680. * @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.
  53681. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  53682. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  53683. */
  53684. /**
  53685. * Constructs a new WebGPU backend.
  53686. *
  53687. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  53688. */
  53689. constructor( parameters = {} ) {
  53690. super( parameters );
  53691. /**
  53692. * This flag can be used for type testing.
  53693. *
  53694. * @type {boolean}
  53695. * @readonly
  53696. * @default true
  53697. */
  53698. this.isWebGPUBackend = true;
  53699. // some parameters require default values other than "undefined"
  53700. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  53701. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  53702. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  53703. /**
  53704. * Indicates whether the backend is in compatibility mode or not.
  53705. * @type {boolean}
  53706. * @default false
  53707. */
  53708. this.compatibilityMode = this.parameters.compatibilityMode;
  53709. /**
  53710. * A reference to the device.
  53711. *
  53712. * @type {?GPUDevice}
  53713. * @default null
  53714. */
  53715. this.device = null;
  53716. /**
  53717. * A reference to the default render pass descriptor.
  53718. *
  53719. * @type {?Object}
  53720. * @default null
  53721. */
  53722. this.defaultRenderPassdescriptor = null;
  53723. /**
  53724. * A reference to a backend module holding common utility functions.
  53725. *
  53726. * @type {WebGPUUtils}
  53727. */
  53728. this.utils = new WebGPUUtils( this );
  53729. /**
  53730. * A reference to a backend module holding shader attribute-related
  53731. * utility functions.
  53732. *
  53733. * @type {WebGPUAttributeUtils}
  53734. */
  53735. this.attributeUtils = new WebGPUAttributeUtils( this );
  53736. /**
  53737. * A reference to a backend module holding shader binding-related
  53738. * utility functions.
  53739. *
  53740. * @type {WebGPUBindingUtils}
  53741. */
  53742. this.bindingUtils = new WebGPUBindingUtils( this );
  53743. /**
  53744. * A reference to a backend module holding shader pipeline-related
  53745. * utility functions.
  53746. *
  53747. * @type {WebGPUPipelineUtils}
  53748. */
  53749. this.pipelineUtils = new WebGPUPipelineUtils( this );
  53750. /**
  53751. * A reference to a backend module holding shader texture-related
  53752. * utility functions.
  53753. *
  53754. * @type {WebGPUTextureUtils}
  53755. */
  53756. this.textureUtils = new WebGPUTextureUtils( this );
  53757. /**
  53758. * A map that manages the resolve buffers for occlusion queries.
  53759. *
  53760. * @type {Map<number,GPUBuffer>}
  53761. */
  53762. this.occludedResolveCache = new Map();
  53763. }
  53764. /**
  53765. * Initializes the backend so it is ready for usage.
  53766. *
  53767. * @async
  53768. * @param {Renderer} renderer - The renderer.
  53769. * @return {Promise} A Promise that resolves when the backend has been initialized.
  53770. */
  53771. async init( renderer ) {
  53772. await super.init( renderer );
  53773. //
  53774. const parameters = this.parameters;
  53775. // create the device if it is not passed with parameters
  53776. let device;
  53777. if ( parameters.device === undefined ) {
  53778. const adapterOptions = {
  53779. powerPreference: parameters.powerPreference,
  53780. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  53781. };
  53782. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  53783. if ( adapter === null ) {
  53784. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  53785. }
  53786. // feature support
  53787. const features = Object.values( GPUFeatureName );
  53788. const supportedFeatures = [];
  53789. for ( const name of features ) {
  53790. if ( adapter.features.has( name ) ) {
  53791. supportedFeatures.push( name );
  53792. }
  53793. }
  53794. const deviceDescriptor = {
  53795. requiredFeatures: supportedFeatures,
  53796. requiredLimits: parameters.requiredLimits
  53797. };
  53798. device = await adapter.requestDevice( deviceDescriptor );
  53799. } else {
  53800. device = parameters.device;
  53801. }
  53802. device.lost.then( ( info ) => {
  53803. const deviceLossInfo = {
  53804. api: 'WebGPU',
  53805. message: info.message || 'Unknown reason',
  53806. reason: info.reason || null,
  53807. originalEvent: info
  53808. };
  53809. renderer.onDeviceLost( deviceLossInfo );
  53810. } );
  53811. this.device = device;
  53812. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  53813. this.updateSize();
  53814. }
  53815. /**
  53816. * A reference to the context.
  53817. *
  53818. * @type {?GPUCanvasContext}
  53819. * @default null
  53820. */
  53821. get context() {
  53822. const canvasTarget = this.renderer.getCanvasTarget();
  53823. const canvasData = this.get( canvasTarget );
  53824. let context = canvasData.context;
  53825. if ( context === undefined ) {
  53826. const parameters = this.parameters;
  53827. if ( canvasTarget.isDefaultCanvasTarget === true && parameters.context !== undefined ) {
  53828. context = parameters.context;
  53829. } else {
  53830. context = canvasTarget.domElement.getContext( 'webgpu' );
  53831. }
  53832. // OffscreenCanvas does not have setAttribute, see #22811
  53833. if ( 'setAttribute' in canvasTarget.domElement ) canvasTarget.domElement.setAttribute( 'data-engine', `three.js r${ REVISION } webgpu` );
  53834. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  53835. const toneMappingMode = parameters.outputType === HalfFloatType ? 'extended' : 'standard';
  53836. context.configure( {
  53837. device: this.device,
  53838. format: this.utils.getPreferredCanvasFormat(),
  53839. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  53840. alphaMode: alphaMode,
  53841. toneMapping: {
  53842. mode: toneMappingMode
  53843. }
  53844. } );
  53845. canvasData.context = context;
  53846. }
  53847. return context;
  53848. }
  53849. /**
  53850. * The coordinate system of the backend.
  53851. *
  53852. * @type {number}
  53853. * @readonly
  53854. */
  53855. get coordinateSystem() {
  53856. return WebGPUCoordinateSystem;
  53857. }
  53858. /**
  53859. * This method performs a readback operation by moving buffer data from
  53860. * a storage buffer attribute from the GPU to the CPU.
  53861. *
  53862. * @async
  53863. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  53864. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  53865. */
  53866. async getArrayBufferAsync( attribute ) {
  53867. return await this.attributeUtils.getArrayBufferAsync( attribute );
  53868. }
  53869. /**
  53870. * Returns the backend's rendering context.
  53871. *
  53872. * @return {GPUCanvasContext} The rendering context.
  53873. */
  53874. getContext() {
  53875. return this.context;
  53876. }
  53877. /**
  53878. * Returns the default render pass descriptor.
  53879. *
  53880. * In WebGPU, the default framebuffer must be configured
  53881. * like custom framebuffers so the backend needs a render
  53882. * pass descriptor even when rendering directly to screen.
  53883. *
  53884. * @private
  53885. * @return {Object} The render pass descriptor.
  53886. */
  53887. _getDefaultRenderPassDescriptor() {
  53888. const renderer = this.renderer;
  53889. const canvasTarget = renderer.getCanvasTarget();
  53890. const canvasData = this.get( canvasTarget );
  53891. const samples = renderer.currentSamples;
  53892. let descriptor = canvasData.descriptor;
  53893. if ( descriptor === undefined || canvasData.samples !== samples ) {
  53894. descriptor = {
  53895. colorAttachments: [ {
  53896. view: null
  53897. } ]
  53898. };
  53899. if ( renderer.depth === true || renderer.stencil === true ) {
  53900. descriptor.depthStencilAttachment = {
  53901. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  53902. };
  53903. }
  53904. const colorAttachment = descriptor.colorAttachments[ 0 ];
  53905. if ( samples > 0 ) {
  53906. colorAttachment.view = this.textureUtils.getColorBuffer().createView();
  53907. } else {
  53908. colorAttachment.resolveTarget = undefined;
  53909. }
  53910. canvasData.descriptor = descriptor;
  53911. canvasData.samples = samples;
  53912. }
  53913. const colorAttachment = descriptor.colorAttachments[ 0 ];
  53914. if ( samples > 0 ) {
  53915. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  53916. } else {
  53917. colorAttachment.view = this.context.getCurrentTexture().createView();
  53918. }
  53919. return descriptor;
  53920. }
  53921. /**
  53922. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  53923. *
  53924. * @param {RenderContext} renderContext - The render context.
  53925. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  53926. *
  53927. * @private
  53928. */
  53929. _isRenderCameraDepthArray( renderContext ) {
  53930. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  53931. }
  53932. /**
  53933. * Returns the render pass descriptor for the given render context.
  53934. *
  53935. * @private
  53936. * @param {RenderContext} renderContext - The render context.
  53937. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  53938. * @return {Object} The render pass descriptor.
  53939. */
  53940. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  53941. const renderTarget = renderContext.renderTarget;
  53942. const renderTargetData = this.get( renderTarget );
  53943. let descriptors = renderTargetData.descriptors;
  53944. if ( descriptors === undefined ||
  53945. renderTargetData.width !== renderTarget.width ||
  53946. renderTargetData.height !== renderTarget.height ||
  53947. renderTargetData.samples !== renderTarget.samples
  53948. ) {
  53949. descriptors = {};
  53950. renderTargetData.descriptors = descriptors;
  53951. }
  53952. const cacheKey = renderContext.getCacheKey();
  53953. let descriptorBase = descriptors[ cacheKey ];
  53954. if ( descriptorBase === undefined ) {
  53955. const textures = renderContext.textures;
  53956. const textureViews = [];
  53957. let sliceIndex;
  53958. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  53959. for ( let i = 0; i < textures.length; i ++ ) {
  53960. const textureData = this.get( textures[ i ] );
  53961. const viewDescriptor = {
  53962. label: `colorAttachment_${ i }`,
  53963. baseMipLevel: renderContext.activeMipmapLevel,
  53964. mipLevelCount: 1,
  53965. baseArrayLayer: renderContext.activeCubeFace,
  53966. arrayLayerCount: 1,
  53967. dimension: GPUTextureViewDimension.TwoD
  53968. };
  53969. if ( renderTarget.isRenderTarget3D ) {
  53970. sliceIndex = renderContext.activeCubeFace;
  53971. viewDescriptor.baseArrayLayer = 0;
  53972. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  53973. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  53974. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  53975. if ( isRenderCameraDepthArray === true ) {
  53976. const cameras = renderContext.camera.cameras;
  53977. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  53978. const layerViewDescriptor = {
  53979. ...viewDescriptor,
  53980. baseArrayLayer: layer,
  53981. arrayLayerCount: 1,
  53982. dimension: GPUTextureViewDimension.TwoD
  53983. };
  53984. const textureView = textureData.texture.createView( layerViewDescriptor );
  53985. textureViews.push( {
  53986. view: textureView,
  53987. resolveTarget: undefined,
  53988. depthSlice: undefined
  53989. } );
  53990. }
  53991. } else {
  53992. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  53993. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  53994. }
  53995. }
  53996. if ( isRenderCameraDepthArray !== true ) {
  53997. const textureView = textureData.texture.createView( viewDescriptor );
  53998. let view, resolveTarget;
  53999. if ( textureData.msaaTexture !== undefined ) {
  54000. view = textureData.msaaTexture.createView();
  54001. resolveTarget = textureView;
  54002. } else {
  54003. view = textureView;
  54004. resolveTarget = undefined;
  54005. }
  54006. textureViews.push( {
  54007. view,
  54008. resolveTarget,
  54009. depthSlice: sliceIndex
  54010. } );
  54011. }
  54012. }
  54013. descriptorBase = { textureViews };
  54014. if ( renderContext.depth ) {
  54015. const depthTextureData = this.get( renderContext.depthTexture );
  54016. const options = {};
  54017. if ( renderContext.depthTexture.isArrayTexture ) {
  54018. options.dimension = GPUTextureViewDimension.TwoD;
  54019. options.arrayLayerCount = 1;
  54020. options.baseArrayLayer = renderContext.activeCubeFace;
  54021. }
  54022. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  54023. }
  54024. descriptors[ cacheKey ] = descriptorBase;
  54025. renderTargetData.width = renderTarget.width;
  54026. renderTargetData.height = renderTarget.height;
  54027. renderTargetData.samples = renderTarget.samples;
  54028. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  54029. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  54030. }
  54031. const descriptor = {
  54032. colorAttachments: []
  54033. };
  54034. // Apply dynamic properties to cached views
  54035. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  54036. const viewInfo = descriptorBase.textureViews[ i ];
  54037. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  54038. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  54039. clearValue = colorAttachmentsConfig.clearValue;
  54040. }
  54041. descriptor.colorAttachments.push( {
  54042. view: viewInfo.view,
  54043. depthSlice: viewInfo.depthSlice,
  54044. resolveTarget: viewInfo.resolveTarget,
  54045. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  54046. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  54047. clearValue: clearValue
  54048. } );
  54049. }
  54050. if ( descriptorBase.depthStencilView ) {
  54051. descriptor.depthStencilAttachment = {
  54052. view: descriptorBase.depthStencilView
  54053. };
  54054. }
  54055. return descriptor;
  54056. }
  54057. /**
  54058. * This method is executed at the beginning of a render call and prepares
  54059. * the WebGPU state for upcoming render calls
  54060. *
  54061. * @param {RenderContext} renderContext - The render context.
  54062. */
  54063. beginRender( renderContext ) {
  54064. const renderContextData = this.get( renderContext );
  54065. //
  54066. const device = this.device;
  54067. const occlusionQueryCount = renderContext.occlusionQueryCount;
  54068. let occlusionQuerySet;
  54069. if ( occlusionQueryCount > 0 ) {
  54070. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  54071. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  54072. // Get a reference to the array of objects with queries. The renderContextData property
  54073. // can be changed by another render pass before the buffer.mapAsyc() completes.
  54074. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  54075. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  54076. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  54077. //
  54078. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  54079. renderContextData.occlusionQuerySet = occlusionQuerySet;
  54080. renderContextData.occlusionQueryIndex = 0;
  54081. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  54082. renderContextData.lastOcclusionObject = null;
  54083. }
  54084. let descriptor;
  54085. if ( renderContext.textures === null ) {
  54086. descriptor = this._getDefaultRenderPassDescriptor();
  54087. } else {
  54088. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  54089. }
  54090. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ), descriptor );
  54091. descriptor.occlusionQuerySet = occlusionQuerySet;
  54092. const depthStencilAttachment = descriptor.depthStencilAttachment;
  54093. if ( renderContext.textures !== null ) {
  54094. const colorAttachments = descriptor.colorAttachments;
  54095. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  54096. const colorAttachment = colorAttachments[ i ];
  54097. if ( renderContext.clearColor ) {
  54098. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  54099. colorAttachment.loadOp = GPULoadOp.Clear;
  54100. } else {
  54101. colorAttachment.loadOp = GPULoadOp.Load;
  54102. }
  54103. colorAttachment.storeOp = GPUStoreOp.Store;
  54104. }
  54105. } else {
  54106. const colorAttachment = descriptor.colorAttachments[ 0 ];
  54107. if ( renderContext.clearColor ) {
  54108. colorAttachment.clearValue = renderContext.clearColorValue;
  54109. colorAttachment.loadOp = GPULoadOp.Clear;
  54110. } else {
  54111. colorAttachment.loadOp = GPULoadOp.Load;
  54112. }
  54113. colorAttachment.storeOp = GPUStoreOp.Store;
  54114. }
  54115. //
  54116. if ( renderContext.depth ) {
  54117. if ( renderContext.clearDepth ) {
  54118. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  54119. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  54120. } else {
  54121. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  54122. }
  54123. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  54124. }
  54125. if ( renderContext.stencil ) {
  54126. if ( renderContext.clearStencil ) {
  54127. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  54128. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  54129. } else {
  54130. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  54131. }
  54132. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  54133. }
  54134. //
  54135. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  54136. // shadow arrays - prepare bundle encoders for each camera in an array camera
  54137. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  54138. const cameras = renderContext.camera.cameras;
  54139. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  54140. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  54141. } else {
  54142. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  54143. }
  54144. // Create bundle encoders for each layer
  54145. renderContextData.bundleEncoders = [];
  54146. renderContextData.bundleSets = [];
  54147. // Create separate bundle encoders for each camera in the array
  54148. for ( let i = 0; i < cameras.length; i ++ ) {
  54149. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  54150. renderContext,
  54151. 'renderBundleArrayCamera_' + i
  54152. );
  54153. // Initialize state tracking for this bundle
  54154. const bundleSets = {
  54155. attributes: {},
  54156. bindingGroups: [],
  54157. pipeline: null,
  54158. index: null
  54159. };
  54160. renderContextData.bundleEncoders.push( bundleEncoder );
  54161. renderContextData.bundleSets.push( bundleSets );
  54162. }
  54163. // We'll complete the bundles in finishRender
  54164. renderContextData.currentPass = null;
  54165. } else {
  54166. const currentPass = encoder.beginRenderPass( descriptor );
  54167. renderContextData.currentPass = currentPass;
  54168. if ( renderContext.viewport ) {
  54169. this.updateViewport( renderContext );
  54170. }
  54171. if ( renderContext.scissor ) {
  54172. this.updateScissor( renderContext );
  54173. }
  54174. }
  54175. //
  54176. renderContextData.descriptor = descriptor;
  54177. renderContextData.encoder = encoder;
  54178. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  54179. renderContextData.renderBundles = [];
  54180. }
  54181. /**
  54182. * This method creates layer descriptors for each camera in an array camera
  54183. * to prepare for rendering to a depth array texture.
  54184. *
  54185. * @param {RenderContext} renderContext - The render context.
  54186. * @param {Object} renderContextData - The render context data.
  54187. * @param {Object} descriptor - The render pass descriptor.
  54188. * @param {ArrayCamera} cameras - The array camera.
  54189. *
  54190. * @private
  54191. */
  54192. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  54193. const depthStencilAttachment = descriptor.depthStencilAttachment;
  54194. renderContextData.layerDescriptors = [];
  54195. const depthTextureData = this.get( renderContext.depthTexture );
  54196. if ( ! depthTextureData.viewCache ) {
  54197. depthTextureData.viewCache = [];
  54198. }
  54199. for ( let i = 0; i < cameras.length; i ++ ) {
  54200. const layerDescriptor = {
  54201. ...descriptor,
  54202. colorAttachments: [ {
  54203. ...descriptor.colorAttachments[ 0 ],
  54204. view: descriptor.colorAttachments[ i ].view
  54205. } ]
  54206. };
  54207. if ( descriptor.depthStencilAttachment ) {
  54208. const layerIndex = i;
  54209. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  54210. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  54211. dimension: GPUTextureViewDimension.TwoD,
  54212. baseArrayLayer: i,
  54213. arrayLayerCount: 1
  54214. } );
  54215. }
  54216. layerDescriptor.depthStencilAttachment = {
  54217. view: depthTextureData.viewCache[ layerIndex ],
  54218. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  54219. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  54220. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  54221. };
  54222. if ( renderContext.stencil ) {
  54223. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  54224. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  54225. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  54226. }
  54227. } else {
  54228. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  54229. }
  54230. renderContextData.layerDescriptors.push( layerDescriptor );
  54231. }
  54232. }
  54233. /**
  54234. * This method updates the layer descriptors for each camera in an array camera
  54235. * to prepare for rendering to a depth array texture.
  54236. *
  54237. * @param {RenderContext} renderContext - The render context.
  54238. * @param {Object} renderContextData - The render context data.
  54239. * @param {ArrayCamera} cameras - The array camera.
  54240. *
  54241. */
  54242. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  54243. for ( let i = 0; i < cameras.length; i ++ ) {
  54244. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  54245. if ( layerDescriptor.depthStencilAttachment ) {
  54246. const depthAttachment = layerDescriptor.depthStencilAttachment;
  54247. if ( renderContext.depth ) {
  54248. if ( renderContext.clearDepth ) {
  54249. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  54250. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  54251. } else {
  54252. depthAttachment.depthLoadOp = GPULoadOp.Load;
  54253. }
  54254. }
  54255. if ( renderContext.stencil ) {
  54256. if ( renderContext.clearStencil ) {
  54257. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  54258. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  54259. } else {
  54260. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  54261. }
  54262. }
  54263. }
  54264. }
  54265. }
  54266. /**
  54267. * This method is executed at the end of a render call and finalizes work
  54268. * after draw calls.
  54269. *
  54270. * @param {RenderContext} renderContext - The render context.
  54271. */
  54272. finishRender( renderContext ) {
  54273. const renderContextData = this.get( renderContext );
  54274. const occlusionQueryCount = renderContext.occlusionQueryCount;
  54275. if ( renderContextData.renderBundles.length > 0 ) {
  54276. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  54277. }
  54278. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  54279. renderContextData.currentPass.endOcclusionQuery();
  54280. }
  54281. // shadow arrays - Execute bundles for each layer
  54282. const encoder = renderContextData.encoder;
  54283. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  54284. const bundles = [];
  54285. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  54286. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  54287. bundles.push( bundleEncoder.finish() );
  54288. }
  54289. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  54290. if ( i < bundles.length ) {
  54291. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  54292. const renderPass = encoder.beginRenderPass( layerDescriptor );
  54293. if ( renderContext.viewport ) {
  54294. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  54295. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  54296. }
  54297. if ( renderContext.scissor ) {
  54298. const { x, y, width, height } = renderContext.scissorValue;
  54299. renderPass.setScissorRect( x, y, width, height );
  54300. }
  54301. renderPass.executeBundles( [ bundles[ i ] ] );
  54302. renderPass.end();
  54303. }
  54304. }
  54305. } else if ( renderContextData.currentPass ) {
  54306. renderContextData.currentPass.end();
  54307. }
  54308. if ( occlusionQueryCount > 0 ) {
  54309. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  54310. //
  54311. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  54312. if ( queryResolveBuffer === undefined ) {
  54313. queryResolveBuffer = this.device.createBuffer(
  54314. {
  54315. size: bufferSize,
  54316. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  54317. }
  54318. );
  54319. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  54320. }
  54321. //
  54322. const readBuffer = this.device.createBuffer(
  54323. {
  54324. size: bufferSize,
  54325. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  54326. }
  54327. );
  54328. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  54329. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  54330. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  54331. renderContextData.occlusionQueryBuffer = readBuffer;
  54332. //
  54333. this.resolveOccludedAsync( renderContext );
  54334. }
  54335. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  54336. //
  54337. if ( renderContext.textures !== null ) {
  54338. const textures = renderContext.textures;
  54339. for ( let i = 0; i < textures.length; i ++ ) {
  54340. const texture = textures[ i ];
  54341. if ( texture.generateMipmaps === true ) {
  54342. this.textureUtils.generateMipmaps( texture );
  54343. }
  54344. }
  54345. }
  54346. }
  54347. /**
  54348. * Returns `true` if the given 3D object is fully occluded by other
  54349. * 3D objects in the scene.
  54350. *
  54351. * @param {RenderContext} renderContext - The render context.
  54352. * @param {Object3D} object - The 3D object to test.
  54353. * @return {boolean} Whether the 3D object is fully occluded or not.
  54354. */
  54355. isOccluded( renderContext, object ) {
  54356. const renderContextData = this.get( renderContext );
  54357. return renderContextData.occluded && renderContextData.occluded.has( object );
  54358. }
  54359. /**
  54360. * This method processes the result of occlusion queries and writes it
  54361. * into render context data.
  54362. *
  54363. * @async
  54364. * @param {RenderContext} renderContext - The render context.
  54365. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  54366. */
  54367. async resolveOccludedAsync( renderContext ) {
  54368. const renderContextData = this.get( renderContext );
  54369. // handle occlusion query results
  54370. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  54371. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  54372. const occluded = new WeakSet();
  54373. renderContextData.currentOcclusionQueryObjects = null;
  54374. renderContextData.currentOcclusionQueryBuffer = null;
  54375. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  54376. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  54377. const results = new BigUint64Array( buffer );
  54378. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  54379. if ( results[ i ] === BigInt( 0 ) ) {
  54380. occluded.add( currentOcclusionQueryObjects[ i ] );
  54381. }
  54382. }
  54383. currentOcclusionQueryBuffer.destroy();
  54384. renderContextData.occluded = occluded;
  54385. }
  54386. }
  54387. /**
  54388. * Updates the viewport with the values from the given render context.
  54389. *
  54390. * @param {RenderContext} renderContext - The render context.
  54391. */
  54392. updateViewport( renderContext ) {
  54393. const { currentPass } = this.get( renderContext );
  54394. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  54395. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  54396. }
  54397. /**
  54398. * Updates the scissor with the values from the given render context.
  54399. *
  54400. * @param {RenderContext} renderContext - The render context.
  54401. */
  54402. updateScissor( renderContext ) {
  54403. const { currentPass } = this.get( renderContext );
  54404. const { x, y, width, height } = renderContext.scissorValue;
  54405. currentPass.setScissorRect( x, y, width, height );
  54406. }
  54407. /**
  54408. * Returns the clear color and alpha into a single
  54409. * color object.
  54410. *
  54411. * @return {Color4} The clear color.
  54412. */
  54413. getClearColor() {
  54414. const clearColor = super.getClearColor();
  54415. // only premultiply alpha when alphaMode is "premultiplied"
  54416. if ( this.renderer.alpha === true ) {
  54417. clearColor.r *= clearColor.a;
  54418. clearColor.g *= clearColor.a;
  54419. clearColor.b *= clearColor.a;
  54420. }
  54421. return clearColor;
  54422. }
  54423. /**
  54424. * Performs a clear operation.
  54425. *
  54426. * @param {boolean} color - Whether the color buffer should be cleared or not.
  54427. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  54428. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  54429. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  54430. */
  54431. clear( color, depth, stencil, renderTargetContext = null ) {
  54432. const device = this.device;
  54433. const renderer = this.renderer;
  54434. let colorAttachments = [];
  54435. let depthStencilAttachment;
  54436. let clearValue;
  54437. let supportsDepth;
  54438. let supportsStencil;
  54439. if ( color ) {
  54440. const clearColor = this.getClearColor();
  54441. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  54442. }
  54443. if ( renderTargetContext === null ) {
  54444. supportsDepth = renderer.depth;
  54445. supportsStencil = renderer.stencil;
  54446. const descriptor = this._getDefaultRenderPassDescriptor();
  54447. if ( color ) {
  54448. colorAttachments = descriptor.colorAttachments;
  54449. const colorAttachment = colorAttachments[ 0 ];
  54450. colorAttachment.clearValue = clearValue;
  54451. colorAttachment.loadOp = GPULoadOp.Clear;
  54452. colorAttachment.storeOp = GPUStoreOp.Store;
  54453. }
  54454. if ( supportsDepth || supportsStencil ) {
  54455. depthStencilAttachment = descriptor.depthStencilAttachment;
  54456. }
  54457. } else {
  54458. supportsDepth = renderTargetContext.depth;
  54459. supportsStencil = renderTargetContext.stencil;
  54460. const clearConfig = {
  54461. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  54462. clearValue: color ? clearValue : undefined
  54463. };
  54464. if ( supportsDepth ) {
  54465. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  54466. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  54467. clearConfig.depthStoreOp = GPUStoreOp.Store;
  54468. }
  54469. if ( supportsStencil ) {
  54470. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  54471. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  54472. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  54473. }
  54474. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  54475. colorAttachments = descriptor.colorAttachments;
  54476. depthStencilAttachment = descriptor.depthStencilAttachment;
  54477. }
  54478. if ( supportsDepth && depthStencilAttachment ) {
  54479. if ( depth ) {
  54480. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  54481. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  54482. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  54483. } else {
  54484. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  54485. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  54486. }
  54487. }
  54488. //
  54489. if ( supportsStencil && depthStencilAttachment ) {
  54490. if ( stencil ) {
  54491. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  54492. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  54493. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  54494. } else {
  54495. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  54496. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  54497. }
  54498. }
  54499. //
  54500. const encoder = device.createCommandEncoder( { label: 'clear' } );
  54501. const currentPass = encoder.beginRenderPass( {
  54502. colorAttachments,
  54503. depthStencilAttachment
  54504. } );
  54505. currentPass.end();
  54506. device.queue.submit( [ encoder.finish() ] );
  54507. }
  54508. // compute
  54509. /**
  54510. * This method is executed at the beginning of a compute call and
  54511. * prepares the state for upcoming compute tasks.
  54512. *
  54513. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  54514. */
  54515. beginCompute( computeGroup ) {
  54516. const groupGPU = this.get( computeGroup );
  54517. //
  54518. const descriptor = {
  54519. label: 'computeGroup_' + computeGroup.id
  54520. };
  54521. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ), descriptor );
  54522. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  54523. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  54524. }
  54525. /**
  54526. * Executes a compute command for the given compute node.
  54527. *
  54528. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  54529. * @param {Node} computeNode - The compute node.
  54530. * @param {Array<BindGroup>} bindings - The bindings.
  54531. * @param {ComputePipeline} pipeline - The compute pipeline.
  54532. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  54533. * - A single number representing count, or
  54534. * - An array [x, y, z] representing dispatch size, or
  54535. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  54536. */
  54537. compute( computeGroup, computeNode, bindings, pipeline, dispatchSize = null ) {
  54538. const computeNodeData = this.get( computeNode );
  54539. const { passEncoderGPU } = this.get( computeGroup );
  54540. // pipeline
  54541. const pipelineGPU = this.get( pipeline ).pipeline;
  54542. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  54543. // bind groups
  54544. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  54545. const bindGroup = bindings[ i ];
  54546. const bindingsData = this.get( bindGroup );
  54547. passEncoderGPU.setBindGroup( i, bindingsData.group );
  54548. }
  54549. if ( dispatchSize === null ) {
  54550. dispatchSize = computeNode.count;
  54551. }
  54552. // When the dispatchSize is set with a StorageBuffer from the GPU.
  54553. if ( dispatchSize && typeof dispatchSize === 'object' && dispatchSize.isIndirectStorageBufferAttribute ) {
  54554. const dispatchBuffer = this.get( dispatchSize ).buffer;
  54555. passEncoderGPU.dispatchWorkgroupsIndirect( dispatchBuffer, 0 );
  54556. return;
  54557. }
  54558. if ( typeof dispatchSize === 'number' ) {
  54559. // If a single number is given, we calculate the dispatch size based on the workgroup size
  54560. const count = dispatchSize;
  54561. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  54562. // cache dispatch size to avoid recalculating it every time
  54563. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  54564. computeNodeData.count = count;
  54565. const workgroupSize = computeNode.workgroupSize;
  54566. let size = workgroupSize[ 0 ];
  54567. for ( let i = 1; i < workgroupSize.length; i ++ )
  54568. size *= workgroupSize[ i ];
  54569. const dispatchCount = Math.ceil( count / size );
  54570. //
  54571. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  54572. dispatchSize = [ dispatchCount, 1, 1 ];
  54573. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  54574. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  54575. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  54576. }
  54577. computeNodeData.dispatchSize = dispatchSize;
  54578. }
  54579. dispatchSize = computeNodeData.dispatchSize;
  54580. }
  54581. //
  54582. passEncoderGPU.dispatchWorkgroups(
  54583. dispatchSize[ 0 ],
  54584. dispatchSize[ 1 ] || 1,
  54585. dispatchSize[ 2 ] || 1
  54586. );
  54587. }
  54588. /**
  54589. * This method is executed at the end of a compute call and
  54590. * finalizes work after compute tasks.
  54591. *
  54592. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  54593. */
  54594. finishCompute( computeGroup ) {
  54595. const groupData = this.get( computeGroup );
  54596. groupData.passEncoderGPU.end();
  54597. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  54598. }
  54599. // render object
  54600. /**
  54601. * Executes a draw command for the given render object.
  54602. *
  54603. * @param {RenderObject} renderObject - The render object to draw.
  54604. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  54605. */
  54606. draw( renderObject, info ) {
  54607. const { object, material, context, pipeline } = renderObject;
  54608. const bindings = renderObject.getBindings();
  54609. const renderContextData = this.get( context );
  54610. const pipelineData = this.get( pipeline );
  54611. const pipelineGPU = pipelineData.pipeline;
  54612. if ( pipelineData.error === true ) return;
  54613. const index = renderObject.getIndex();
  54614. const hasIndex = ( index !== null );
  54615. const drawParams = renderObject.getDrawParameters();
  54616. if ( drawParams === null ) return;
  54617. // pipeline
  54618. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  54619. // pipeline
  54620. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  54621. currentSets.pipeline = pipelineGPU;
  54622. // bind groups
  54623. const currentBindingGroups = currentSets.bindingGroups;
  54624. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  54625. const bindGroup = bindings[ i ];
  54626. const bindingsData = this.get( bindGroup );
  54627. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  54628. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  54629. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  54630. }
  54631. }
  54632. // attributes
  54633. // index
  54634. if ( hasIndex === true ) {
  54635. if ( currentSets.index !== index ) {
  54636. const buffer = this.get( index ).buffer;
  54637. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  54638. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  54639. currentSets.index = index;
  54640. }
  54641. }
  54642. // vertex buffers
  54643. const vertexBuffers = renderObject.getVertexBuffers();
  54644. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  54645. const vertexBuffer = vertexBuffers[ i ];
  54646. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  54647. const buffer = this.get( vertexBuffer ).buffer;
  54648. passEncoderGPU.setVertexBuffer( i, buffer );
  54649. currentSets.attributes[ i ] = vertexBuffer;
  54650. }
  54651. }
  54652. // stencil
  54653. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  54654. passEncoderGPU.setStencilReference( material.stencilRef );
  54655. renderContextData.currentStencilRef = material.stencilRef;
  54656. }
  54657. };
  54658. // Define draw function
  54659. const draw = ( passEncoderGPU, currentSets ) => {
  54660. setPipelineAndBindings( passEncoderGPU, currentSets );
  54661. if ( object.isBatchedMesh === true ) {
  54662. const starts = object._multiDrawStarts;
  54663. const counts = object._multiDrawCounts;
  54664. const drawCount = object._multiDrawCount;
  54665. const drawInstances = object._multiDrawInstances;
  54666. if ( drawInstances !== null ) {
  54667. // @deprecated, r174
  54668. warnOnce( 'WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  54669. }
  54670. for ( let i = 0; i < drawCount; i ++ ) {
  54671. const count = drawInstances ? drawInstances[ i ] : 1;
  54672. const firstInstance = count > 1 ? 0 : i;
  54673. if ( hasIndex === true ) {
  54674. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  54675. } else {
  54676. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  54677. }
  54678. info.update( object, counts[ i ], count );
  54679. }
  54680. } else if ( hasIndex === true ) {
  54681. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  54682. const indirect = renderObject.getIndirect();
  54683. if ( indirect !== null ) {
  54684. const buffer = this.get( indirect ).buffer;
  54685. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  54686. } else {
  54687. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  54688. }
  54689. info.update( object, indexCount, instanceCount );
  54690. } else {
  54691. const { vertexCount, instanceCount, firstVertex } = drawParams;
  54692. const indirect = renderObject.getIndirect();
  54693. if ( indirect !== null ) {
  54694. const buffer = this.get( indirect ).buffer;
  54695. passEncoderGPU.drawIndirect( buffer, 0 );
  54696. } else {
  54697. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  54698. }
  54699. info.update( object, vertexCount, instanceCount );
  54700. }
  54701. };
  54702. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  54703. const cameraData = this.get( renderObject.camera );
  54704. const cameras = renderObject.camera.cameras;
  54705. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  54706. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  54707. const bindingsData = this.get( cameraIndex );
  54708. const indexesGPU = [];
  54709. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  54710. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  54711. data[ 0 ] = i;
  54712. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  54713. indexesGPU.push( bindGroupIndex );
  54714. }
  54715. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  54716. }
  54717. const pixelRatio = this.renderer.getPixelRatio();
  54718. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  54719. const subCamera = cameras[ i ];
  54720. if ( object.layers.test( subCamera.layers ) ) {
  54721. const vp = subCamera.viewport;
  54722. let pass = renderContextData.currentPass;
  54723. let sets = renderContextData.currentSets;
  54724. if ( renderContextData.bundleEncoders ) {
  54725. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  54726. const bundleSets = renderContextData.bundleSets[ i ];
  54727. pass = bundleEncoder;
  54728. sets = bundleSets;
  54729. }
  54730. if ( vp ) {
  54731. pass.setViewport(
  54732. Math.floor( vp.x * pixelRatio ),
  54733. Math.floor( vp.y * pixelRatio ),
  54734. Math.floor( vp.width * pixelRatio ),
  54735. Math.floor( vp.height * pixelRatio ),
  54736. context.viewportValue.minDepth,
  54737. context.viewportValue.maxDepth
  54738. );
  54739. }
  54740. // Set camera index binding for this layer
  54741. if ( cameraIndex && cameraData.indexesGPU ) {
  54742. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  54743. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  54744. }
  54745. draw( pass, sets );
  54746. }
  54747. }
  54748. } else {
  54749. // Regular single camera rendering
  54750. if ( renderContextData.currentPass ) {
  54751. // Handle occlusion queries
  54752. if ( renderContextData.occlusionQuerySet !== undefined ) {
  54753. const lastObject = renderContextData.lastOcclusionObject;
  54754. if ( lastObject !== object ) {
  54755. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  54756. renderContextData.currentPass.endOcclusionQuery();
  54757. renderContextData.occlusionQueryIndex ++;
  54758. }
  54759. if ( object.occlusionTest === true ) {
  54760. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  54761. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  54762. }
  54763. renderContextData.lastOcclusionObject = object;
  54764. }
  54765. }
  54766. draw( renderContextData.currentPass, renderContextData.currentSets );
  54767. }
  54768. }
  54769. }
  54770. // cache key
  54771. /**
  54772. * Returns `true` if the render pipeline requires an update.
  54773. *
  54774. * @param {RenderObject} renderObject - The render object.
  54775. * @return {boolean} Whether the render pipeline requires an update or not.
  54776. */
  54777. needsRenderUpdate( renderObject ) {
  54778. const data = this.get( renderObject );
  54779. const { object, material } = renderObject;
  54780. const utils = this.utils;
  54781. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  54782. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  54783. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  54784. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  54785. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  54786. let needsUpdate = false;
  54787. if ( data.material !== material || data.materialVersion !== material.version ||
  54788. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  54789. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  54790. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  54791. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  54792. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  54793. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  54794. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  54795. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  54796. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  54797. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  54798. data.primitiveTopology !== primitiveTopology ||
  54799. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  54800. ) {
  54801. data.material = material; data.materialVersion = material.version;
  54802. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  54803. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  54804. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  54805. data.colorWrite = material.colorWrite;
  54806. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  54807. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  54808. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  54809. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  54810. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  54811. data.sampleCount = sampleCount;
  54812. data.colorSpace = colorSpace;
  54813. data.colorFormat = colorFormat;
  54814. data.depthStencilFormat = depthStencilFormat;
  54815. data.primitiveTopology = primitiveTopology;
  54816. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  54817. needsUpdate = true;
  54818. }
  54819. return needsUpdate;
  54820. }
  54821. /**
  54822. * Returns a cache key that is used to identify render pipelines.
  54823. *
  54824. * @param {RenderObject} renderObject - The render object.
  54825. * @return {string} The cache key.
  54826. */
  54827. getRenderCacheKey( renderObject ) {
  54828. const { object, material } = renderObject;
  54829. const utils = this.utils;
  54830. const renderContext = renderObject.context;
  54831. // meshes with negative scale have a different frontFace render pipeline
  54832. // descriptor value so the following must be honored in the cache key
  54833. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  54834. return [
  54835. material.transparent, material.blending, material.premultipliedAlpha,
  54836. material.blendSrc, material.blendDst, material.blendEquation,
  54837. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  54838. material.colorWrite,
  54839. material.depthWrite, material.depthTest, material.depthFunc,
  54840. material.stencilWrite, material.stencilFunc,
  54841. material.stencilFail, material.stencilZFail, material.stencilZPass,
  54842. material.stencilFuncMask, material.stencilWriteMask,
  54843. material.side,
  54844. frontFaceCW,
  54845. utils.getSampleCountRenderContext( renderContext ),
  54846. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  54847. utils.getPrimitiveTopology( object, material ),
  54848. renderObject.getGeometryCacheKey(),
  54849. renderObject.clippingContextCacheKey
  54850. ].join();
  54851. }
  54852. // textures
  54853. /**
  54854. * Updates a GPU sampler for the given texture.
  54855. *
  54856. * @param {Texture} texture - The texture to update the sampler for.
  54857. * @return {string} The current sampler key.
  54858. */
  54859. updateSampler( texture ) {
  54860. return this.textureUtils.updateSampler( texture );
  54861. }
  54862. /**
  54863. * Creates a default texture for the given texture that can be used
  54864. * as a placeholder until the actual texture is ready for usage.
  54865. *
  54866. * @param {Texture} texture - The texture to create a default texture for.
  54867. * @return {boolean} Whether the sampler has been updated or not.
  54868. */
  54869. createDefaultTexture( texture ) {
  54870. return this.textureUtils.createDefaultTexture( texture );
  54871. }
  54872. /**
  54873. * Defines a texture on the GPU for the given texture object.
  54874. *
  54875. * @param {Texture} texture - The texture.
  54876. * @param {Object} [options={}] - Optional configuration parameter.
  54877. */
  54878. createTexture( texture, options ) {
  54879. this.textureUtils.createTexture( texture, options );
  54880. }
  54881. /**
  54882. * Uploads the updated texture data to the GPU.
  54883. *
  54884. * @param {Texture} texture - The texture.
  54885. * @param {Object} [options={}] - Optional configuration parameter.
  54886. */
  54887. updateTexture( texture, options ) {
  54888. this.textureUtils.updateTexture( texture, options );
  54889. }
  54890. /**
  54891. * Generates mipmaps for the given texture.
  54892. *
  54893. * @param {Texture} texture - The texture.
  54894. */
  54895. generateMipmaps( texture ) {
  54896. this.textureUtils.generateMipmaps( texture );
  54897. }
  54898. /**
  54899. * Destroys the GPU data for the given texture object.
  54900. *
  54901. * @param {Texture} texture - The texture.
  54902. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  54903. */
  54904. destroyTexture( texture, isDefaultTexture = false ) {
  54905. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  54906. }
  54907. /**
  54908. * Returns texture data as a typed array.
  54909. *
  54910. * @async
  54911. * @param {Texture} texture - The texture to copy.
  54912. * @param {number} x - The x coordinate of the copy origin.
  54913. * @param {number} y - The y coordinate of the copy origin.
  54914. * @param {number} width - The width of the copy.
  54915. * @param {number} height - The height of the copy.
  54916. * @param {number} faceIndex - The face index.
  54917. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  54918. */
  54919. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  54920. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  54921. }
  54922. /**
  54923. * Inits a time stamp query for the given render context.
  54924. *
  54925. * @param {string} type - The type of the timestamp query (e.g. 'render', 'compute').
  54926. * @param {number} uid - Unique id for the context (e.g. render context id).
  54927. * @param {Object} descriptor - The query descriptor.
  54928. */
  54929. initTimestampQuery( type, uid, descriptor ) {
  54930. if ( ! this.trackTimestamp ) return;
  54931. if ( ! this.timestampQueryPool[ type ] ) {
  54932. // TODO: Variable maxQueries?
  54933. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  54934. }
  54935. const timestampQueryPool = this.timestampQueryPool[ type ];
  54936. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  54937. descriptor.timestampWrites = {
  54938. querySet: timestampQueryPool.querySet,
  54939. beginningOfPassWriteIndex: baseOffset,
  54940. endOfPassWriteIndex: baseOffset + 1,
  54941. };
  54942. }
  54943. // node builder
  54944. /**
  54945. * Returns a node builder for the given render object.
  54946. *
  54947. * @param {RenderObject} object - The render object.
  54948. * @param {Renderer} renderer - The renderer.
  54949. * @return {WGSLNodeBuilder} The node builder.
  54950. */
  54951. createNodeBuilder( object, renderer ) {
  54952. return new WGSLNodeBuilder( object, renderer );
  54953. }
  54954. // program
  54955. /**
  54956. * Creates a shader program from the given programmable stage.
  54957. *
  54958. * @param {ProgrammableStage} program - The programmable stage.
  54959. */
  54960. createProgram( program ) {
  54961. const programGPU = this.get( program );
  54962. programGPU.module = {
  54963. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  54964. entryPoint: 'main'
  54965. };
  54966. }
  54967. /**
  54968. * Destroys the shader program of the given programmable stage.
  54969. *
  54970. * @param {ProgrammableStage} program - The programmable stage.
  54971. */
  54972. destroyProgram( program ) {
  54973. this.delete( program );
  54974. }
  54975. // pipelines
  54976. /**
  54977. * Creates a render pipeline for the given render object.
  54978. *
  54979. * @param {RenderObject} renderObject - The render object.
  54980. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  54981. */
  54982. createRenderPipeline( renderObject, promises ) {
  54983. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  54984. }
  54985. /**
  54986. * Creates a compute pipeline for the given compute node.
  54987. *
  54988. * @param {ComputePipeline} computePipeline - The compute pipeline.
  54989. * @param {Array<BindGroup>} bindings - The bindings.
  54990. */
  54991. createComputePipeline( computePipeline, bindings ) {
  54992. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  54993. }
  54994. /**
  54995. * Prepares the state for encoding render bundles.
  54996. *
  54997. * @param {RenderContext} renderContext - The render context.
  54998. */
  54999. beginBundle( renderContext ) {
  55000. const renderContextData = this.get( renderContext );
  55001. renderContextData._currentPass = renderContextData.currentPass;
  55002. renderContextData._currentSets = renderContextData.currentSets;
  55003. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  55004. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  55005. }
  55006. /**
  55007. * After processing render bundles this method finalizes related work.
  55008. *
  55009. * @param {RenderContext} renderContext - The render context.
  55010. * @param {RenderBundle} bundle - The render bundle.
  55011. */
  55012. finishBundle( renderContext, bundle ) {
  55013. const renderContextData = this.get( renderContext );
  55014. const bundleEncoder = renderContextData.currentPass;
  55015. const bundleGPU = bundleEncoder.finish();
  55016. this.get( bundle ).bundleGPU = bundleGPU;
  55017. // restore render pass state
  55018. renderContextData.currentSets = renderContextData._currentSets;
  55019. renderContextData.currentPass = renderContextData._currentPass;
  55020. }
  55021. /**
  55022. * Adds a render bundle to the render context data.
  55023. *
  55024. * @param {RenderContext} renderContext - The render context.
  55025. * @param {RenderBundle} bundle - The render bundle to add.
  55026. */
  55027. addBundle( renderContext, bundle ) {
  55028. const renderContextData = this.get( renderContext );
  55029. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  55030. }
  55031. // bindings
  55032. /**
  55033. * Creates bindings from the given bind group definition.
  55034. *
  55035. * @param {BindGroup} bindGroup - The bind group.
  55036. * @param {Array<BindGroup>} bindings - Array of bind groups.
  55037. * @param {number} cacheIndex - The cache index.
  55038. * @param {number} version - The version.
  55039. */
  55040. createBindings( bindGroup, bindings, cacheIndex, version ) {
  55041. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  55042. }
  55043. /**
  55044. * Updates the given bind group definition.
  55045. *
  55046. * @param {BindGroup} bindGroup - The bind group.
  55047. * @param {Array<BindGroup>} bindings - Array of bind groups.
  55048. * @param {number} cacheIndex - The cache index.
  55049. * @param {number} version - The version.
  55050. */
  55051. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  55052. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  55053. }
  55054. /**
  55055. * Updates a buffer binding.
  55056. *
  55057. * @param {Buffer} binding - The buffer binding to update.
  55058. */
  55059. updateBinding( binding ) {
  55060. this.bindingUtils.updateBinding( binding );
  55061. }
  55062. // attributes
  55063. /**
  55064. * Creates the buffer of an indexed shader attribute.
  55065. *
  55066. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  55067. */
  55068. createIndexAttribute( attribute ) {
  55069. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  55070. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  55071. usage |= GPUBufferUsage.STORAGE;
  55072. }
  55073. this.attributeUtils.createAttribute( attribute, usage );
  55074. }
  55075. /**
  55076. * Creates the GPU buffer of a shader attribute.
  55077. *
  55078. * @param {BufferAttribute} attribute - The buffer attribute.
  55079. */
  55080. createAttribute( attribute ) {
  55081. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  55082. }
  55083. /**
  55084. * Creates the GPU buffer of a storage attribute.
  55085. *
  55086. * @param {BufferAttribute} attribute - The buffer attribute.
  55087. */
  55088. createStorageAttribute( attribute ) {
  55089. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  55090. }
  55091. /**
  55092. * Creates the GPU buffer of an indirect storage attribute.
  55093. *
  55094. * @param {BufferAttribute} attribute - The buffer attribute.
  55095. */
  55096. createIndirectStorageAttribute( attribute ) {
  55097. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  55098. }
  55099. /**
  55100. * Updates the GPU buffer of a shader attribute.
  55101. *
  55102. * @param {BufferAttribute} attribute - The buffer attribute to update.
  55103. */
  55104. updateAttribute( attribute ) {
  55105. this.attributeUtils.updateAttribute( attribute );
  55106. }
  55107. /**
  55108. * Destroys the GPU buffer of a shader attribute.
  55109. *
  55110. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  55111. */
  55112. destroyAttribute( attribute ) {
  55113. this.attributeUtils.destroyAttribute( attribute );
  55114. }
  55115. // canvas
  55116. /**
  55117. * Triggers an update of the default render pass descriptor.
  55118. */
  55119. updateSize() {
  55120. this.delete( this.renderer.getCanvasTarget() );
  55121. }
  55122. // utils public
  55123. /**
  55124. * Returns the maximum anisotropy texture filtering value.
  55125. *
  55126. * @return {number} The maximum anisotropy texture filtering value.
  55127. */
  55128. getMaxAnisotropy() {
  55129. return 16;
  55130. }
  55131. /**
  55132. * Checks if the given feature is supported by the backend.
  55133. *
  55134. * @param {string} name - The feature's name.
  55135. * @return {boolean} Whether the feature is supported or not.
  55136. */
  55137. hasFeature( name ) {
  55138. if ( GPUFeatureMap[ name ] !== undefined ) name = GPUFeatureMap[ name ];
  55139. return this.device.features.has( name );
  55140. }
  55141. /**
  55142. * Copies data of the given source texture to the given destination texture.
  55143. *
  55144. * @param {Texture} srcTexture - The source texture.
  55145. * @param {Texture} dstTexture - The destination texture.
  55146. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  55147. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  55148. * @param {number} [srcLevel=0] - The mipmap level to copy.
  55149. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  55150. */
  55151. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  55152. let dstX = 0;
  55153. let dstY = 0;
  55154. let dstZ = 0;
  55155. let srcX = 0;
  55156. let srcY = 0;
  55157. let srcZ = 0;
  55158. let srcWidth = srcTexture.image.width;
  55159. let srcHeight = srcTexture.image.height;
  55160. let srcDepth = 1;
  55161. if ( srcRegion !== null ) {
  55162. if ( srcRegion.isBox3 === true ) {
  55163. srcX = srcRegion.min.x;
  55164. srcY = srcRegion.min.y;
  55165. srcZ = srcRegion.min.z;
  55166. srcWidth = srcRegion.max.x - srcRegion.min.x;
  55167. srcHeight = srcRegion.max.y - srcRegion.min.y;
  55168. srcDepth = srcRegion.max.z - srcRegion.min.z;
  55169. } else {
  55170. // Assume it's a Box2
  55171. srcX = srcRegion.min.x;
  55172. srcY = srcRegion.min.y;
  55173. srcWidth = srcRegion.max.x - srcRegion.min.x;
  55174. srcHeight = srcRegion.max.y - srcRegion.min.y;
  55175. srcDepth = 1;
  55176. }
  55177. }
  55178. if ( dstPosition !== null ) {
  55179. dstX = dstPosition.x;
  55180. dstY = dstPosition.y;
  55181. dstZ = dstPosition.z || 0;
  55182. }
  55183. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  55184. const sourceGPU = this.get( srcTexture ).texture;
  55185. const destinationGPU = this.get( dstTexture ).texture;
  55186. encoder.copyTextureToTexture(
  55187. {
  55188. texture: sourceGPU,
  55189. mipLevel: srcLevel,
  55190. origin: { x: srcX, y: srcY, z: srcZ }
  55191. },
  55192. {
  55193. texture: destinationGPU,
  55194. mipLevel: dstLevel,
  55195. origin: { x: dstX, y: dstY, z: dstZ }
  55196. },
  55197. [
  55198. srcWidth,
  55199. srcHeight,
  55200. srcDepth
  55201. ]
  55202. );
  55203. this.device.queue.submit( [ encoder.finish() ] );
  55204. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  55205. this.textureUtils.generateMipmaps( dstTexture );
  55206. }
  55207. }
  55208. /**
  55209. * Copies the current bound framebuffer to the given texture.
  55210. *
  55211. * @param {Texture} texture - The destination texture.
  55212. * @param {RenderContext} renderContext - The render context.
  55213. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  55214. */
  55215. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  55216. const renderContextData = this.get( renderContext );
  55217. let sourceGPU = null;
  55218. if ( renderContext.renderTarget ) {
  55219. if ( texture.isDepthTexture ) {
  55220. sourceGPU = this.get( renderContext.depthTexture ).texture;
  55221. } else {
  55222. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  55223. }
  55224. } else {
  55225. if ( texture.isDepthTexture ) {
  55226. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  55227. } else {
  55228. sourceGPU = this.context.getCurrentTexture();
  55229. }
  55230. }
  55231. const destinationGPU = this.get( texture ).texture;
  55232. if ( sourceGPU.format !== destinationGPU.format ) {
  55233. error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  55234. return;
  55235. }
  55236. let encoder;
  55237. if ( renderContextData.currentPass ) {
  55238. renderContextData.currentPass.end();
  55239. encoder = renderContextData.encoder;
  55240. } else {
  55241. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  55242. }
  55243. encoder.copyTextureToTexture(
  55244. {
  55245. texture: sourceGPU,
  55246. origin: [ rectangle.x, rectangle.y, 0 ],
  55247. },
  55248. {
  55249. texture: destinationGPU
  55250. },
  55251. [
  55252. rectangle.z,
  55253. rectangle.w
  55254. ]
  55255. );
  55256. // mipmaps must be genereated with the same encoder otherwise the copied texture data
  55257. // might be out-of-sync, see #31768
  55258. if ( texture.generateMipmaps ) {
  55259. this.textureUtils.generateMipmaps( texture, encoder );
  55260. }
  55261. if ( renderContextData.currentPass ) {
  55262. const { descriptor } = renderContextData;
  55263. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  55264. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  55265. }
  55266. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  55267. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  55268. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  55269. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  55270. if ( renderContext.viewport ) {
  55271. this.updateViewport( renderContext );
  55272. }
  55273. if ( renderContext.scissor ) {
  55274. this.updateScissor( renderContext );
  55275. }
  55276. } else {
  55277. this.device.queue.submit( [ encoder.finish() ] );
  55278. }
  55279. }
  55280. dispose() {
  55281. this.textureUtils.dispose();
  55282. }
  55283. }
  55284. /**
  55285. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  55286. *
  55287. * @augments SpotLight
  55288. */
  55289. class IESSpotLight extends SpotLight {
  55290. /**
  55291. * Constructs a new IES spot light.
  55292. *
  55293. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  55294. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  55295. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  55296. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  55297. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  55298. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  55299. */
  55300. constructor( color, intensity, distance, angle, penumbra, decay ) {
  55301. super( color, intensity, distance, angle, penumbra, decay );
  55302. /**
  55303. * TODO
  55304. *
  55305. * @type {?Texture}
  55306. * @default null
  55307. */
  55308. this.iesMap = null;
  55309. }
  55310. copy( source, recursive ) {
  55311. super.copy( source, recursive );
  55312. this.iesMap = source.iesMap;
  55313. return this;
  55314. }
  55315. }
  55316. /**
  55317. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  55318. *
  55319. * @augments SpotLight
  55320. */
  55321. class ProjectorLight extends SpotLight {
  55322. /**
  55323. * Constructs a new projector light.
  55324. *
  55325. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  55326. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  55327. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  55328. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  55329. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  55330. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  55331. */
  55332. constructor( color, intensity, distance, angle, penumbra, decay ) {
  55333. super( color, intensity, distance, angle, penumbra, decay );
  55334. /**
  55335. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  55336. *
  55337. * @type {?number}
  55338. * @default null
  55339. */
  55340. this.aspect = null;
  55341. }
  55342. copy( source, recursive ) {
  55343. super.copy( source, recursive );
  55344. this.aspect = source.aspect;
  55345. return this;
  55346. }
  55347. }
  55348. /**
  55349. * This version of a node library represents the standard version
  55350. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  55351. * techniques and materials to node-based implementations.
  55352. *
  55353. * @private
  55354. * @augments NodeLibrary
  55355. */
  55356. class StandardNodeLibrary extends NodeLibrary {
  55357. /**
  55358. * Constructs a new standard node library.
  55359. */
  55360. constructor() {
  55361. super();
  55362. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  55363. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  55364. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  55365. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  55366. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  55367. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  55368. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  55369. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  55370. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  55371. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  55372. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  55373. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  55374. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  55375. this.addLight( PointLightNode, PointLight );
  55376. this.addLight( DirectionalLightNode, DirectionalLight );
  55377. this.addLight( RectAreaLightNode, RectAreaLight );
  55378. this.addLight( SpotLightNode, SpotLight );
  55379. this.addLight( AmbientLightNode, AmbientLight );
  55380. this.addLight( HemisphereLightNode, HemisphereLight );
  55381. this.addLight( LightProbeNode, LightProbe );
  55382. this.addLight( IESSpotLightNode, IESSpotLight );
  55383. this.addLight( ProjectorLightNode, ProjectorLight );
  55384. this.addToneMapping( linearToneMapping, LinearToneMapping );
  55385. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  55386. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  55387. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  55388. this.addToneMapping( agxToneMapping, AgXToneMapping );
  55389. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  55390. }
  55391. }
  55392. /*
  55393. const debugHandler = {
  55394. get: function ( target, name ) {
  55395. // Add |update
  55396. if ( /^(create|destroy)/.test( name ) ) log( 'WebGPUBackend.' + name );
  55397. return target[ name ];
  55398. }
  55399. };
  55400. */
  55401. /**
  55402. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  55403. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  55404. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  55405. *
  55406. * @augments Renderer
  55407. */
  55408. class WebGPURenderer extends Renderer {
  55409. /**
  55410. * WebGPURenderer options.
  55411. *
  55412. * @typedef {Object} WebGPURenderer~Options
  55413. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  55414. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  55415. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  55416. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  55417. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  55418. * @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.
  55419. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  55420. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  55421. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  55422. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  55423. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  55424. */
  55425. /**
  55426. * Constructs a new WebGPU renderer.
  55427. *
  55428. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  55429. */
  55430. constructor( parameters = {} ) {
  55431. let BackendClass;
  55432. if ( parameters.forceWebGL ) {
  55433. BackendClass = WebGLBackend;
  55434. } else {
  55435. BackendClass = WebGPUBackend;
  55436. parameters.getFallback = () => {
  55437. warn( 'WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  55438. return new WebGLBackend( parameters );
  55439. };
  55440. }
  55441. const backend = new BackendClass( parameters );
  55442. //super( new Proxy( backend, debugHandler ) );
  55443. super( backend, parameters );
  55444. /**
  55445. * The generic default value is overwritten with the
  55446. * standard node library for type mapping.
  55447. *
  55448. * @type {StandardNodeLibrary}
  55449. */
  55450. this.library = new StandardNodeLibrary();
  55451. /**
  55452. * This flag can be used for type testing.
  55453. *
  55454. * @type {boolean}
  55455. * @readonly
  55456. * @default true
  55457. */
  55458. this.isWebGPURenderer = true;
  55459. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  55460. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  55461. }
  55462. }
  55463. }
  55464. /**
  55465. * A specialized group which enables applications access to the
  55466. * Render Bundle API of WebGPU. The group with all its descendant nodes
  55467. * are considered as one render bundle and processed as such by
  55468. * the renderer.
  55469. *
  55470. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  55471. * With a WebGL backend, the group can technically be rendered but without
  55472. * any performance improvements.
  55473. *
  55474. * @augments Group
  55475. */
  55476. class BundleGroup extends Group {
  55477. /**
  55478. * Constructs a new bundle group.
  55479. */
  55480. constructor() {
  55481. super();
  55482. /**
  55483. * This flag can be used for type testing.
  55484. *
  55485. * @type {boolean}
  55486. * @readonly
  55487. * @default true
  55488. */
  55489. this.isBundleGroup = true;
  55490. /**
  55491. * This property is only relevant for detecting types
  55492. * during serialization/deserialization. It should always
  55493. * match the class name.
  55494. *
  55495. * @type {string}
  55496. * @readonly
  55497. * @default 'BundleGroup'
  55498. */
  55499. this.type = 'BundleGroup';
  55500. /**
  55501. * Whether the bundle is static or not. When set to `true`, the structure
  55502. * is assumed to be static and does not change. E.g. no new objects are
  55503. * added to the group
  55504. *
  55505. * If a change is required, an update can still be forced by setting the
  55506. * `needsUpdate` flag to `true`.
  55507. *
  55508. * @type {boolean}
  55509. * @default true
  55510. */
  55511. this.static = true;
  55512. /**
  55513. * The bundle group's version.
  55514. *
  55515. * @type {number}
  55516. * @readonly
  55517. * @default 0
  55518. */
  55519. this.version = 0;
  55520. }
  55521. /**
  55522. * Set this property to `true` when the bundle group has changed.
  55523. *
  55524. * @type {boolean}
  55525. * @default false
  55526. * @param {boolean} value
  55527. */
  55528. set needsUpdate( value ) {
  55529. if ( value === true ) this.version ++;
  55530. }
  55531. }
  55532. /**
  55533. * This module is responsible to manage the post processing setups in apps.
  55534. * You usually create a single instance of this class and use it to define
  55535. * the output of your post processing effect chain.
  55536. * ```js
  55537. * const postProcessing = new PostProcessing( renderer );
  55538. *
  55539. * const scenePass = pass( scene, camera );
  55540. *
  55541. * postProcessing.outputNode = scenePass;
  55542. * ```
  55543. *
  55544. * Note: This module can only be used with `WebGPURenderer`.
  55545. */
  55546. class PostProcessing {
  55547. /**
  55548. * Constructs a new post processing management module.
  55549. *
  55550. * @param {Renderer} renderer - A reference to the renderer.
  55551. * @param {Node<vec4>} outputNode - An optional output node.
  55552. */
  55553. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  55554. /**
  55555. * A reference to the renderer.
  55556. *
  55557. * @type {Renderer}
  55558. */
  55559. this.renderer = renderer;
  55560. /**
  55561. * A node which defines the final output of the post
  55562. * processing. This is usually the last node in a chain
  55563. * of effect nodes.
  55564. *
  55565. * @type {Node<vec4>}
  55566. */
  55567. this.outputNode = outputNode;
  55568. /**
  55569. * Whether the default output tone mapping and color
  55570. * space transformation should be enabled or not.
  55571. *
  55572. * It is enabled by default by it must be disabled when
  55573. * effects must be executed after tone mapping and color
  55574. * space conversion. A typical example is FXAA which
  55575. * requires sRGB input.
  55576. *
  55577. * When set to `false`, the app must control the output
  55578. * transformation with `RenderOutputNode`.
  55579. *
  55580. * ```js
  55581. * const outputPass = renderOutput( scenePass );
  55582. * ```
  55583. *
  55584. * @type {boolean}
  55585. */
  55586. this.outputColorTransform = true;
  55587. /**
  55588. * Must be set to `true` when the output node changes.
  55589. *
  55590. * @type {Node<vec4>}
  55591. */
  55592. this.needsUpdate = true;
  55593. const material = new NodeMaterial();
  55594. material.name = 'PostProcessing';
  55595. /**
  55596. * The full screen quad that is used to render
  55597. * the effects.
  55598. *
  55599. * @private
  55600. * @type {QuadMesh}
  55601. */
  55602. this._quadMesh = new QuadMesh( material );
  55603. this._quadMesh.name = 'Post-Processing';
  55604. /**
  55605. * The context of the post processing stack.
  55606. *
  55607. * @private
  55608. * @type {?Object}
  55609. * @default null
  55610. */
  55611. this._context = null;
  55612. }
  55613. /**
  55614. * When `PostProcessing` is used to apply post processing effects,
  55615. * the application must use this version of `render()` inside
  55616. * its animation loop (not the one from the renderer).
  55617. */
  55618. render() {
  55619. const renderer = this.renderer;
  55620. this._update();
  55621. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  55622. const toneMapping = renderer.toneMapping;
  55623. const outputColorSpace = renderer.outputColorSpace;
  55624. renderer.toneMapping = NoToneMapping;
  55625. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  55626. //
  55627. const currentXR = renderer.xr.enabled;
  55628. renderer.xr.enabled = false;
  55629. this._quadMesh.render( renderer );
  55630. renderer.xr.enabled = currentXR;
  55631. //
  55632. renderer.toneMapping = toneMapping;
  55633. renderer.outputColorSpace = outputColorSpace;
  55634. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  55635. }
  55636. /**
  55637. * Returns the current context of the post processing stack.
  55638. *
  55639. * @readonly
  55640. * @type {?Object}
  55641. */
  55642. get context() {
  55643. return this._context;
  55644. }
  55645. /**
  55646. * Frees internal resources.
  55647. */
  55648. dispose() {
  55649. this._quadMesh.material.dispose();
  55650. }
  55651. /**
  55652. * Updates the state of the module.
  55653. *
  55654. * @private
  55655. */
  55656. _update() {
  55657. if ( this.needsUpdate === true ) {
  55658. const renderer = this.renderer;
  55659. const toneMapping = renderer.toneMapping;
  55660. const outputColorSpace = renderer.outputColorSpace;
  55661. const context = {
  55662. postProcessing: this,
  55663. onBeforePostProcessing: null,
  55664. onAfterPostProcessing: null
  55665. };
  55666. let outputNode = this.outputNode;
  55667. if ( this.outputColorTransform === true ) {
  55668. outputNode = outputNode.context( context );
  55669. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  55670. } else {
  55671. context.toneMapping = toneMapping;
  55672. context.outputColorSpace = outputColorSpace;
  55673. outputNode = outputNode.context( context );
  55674. }
  55675. this._context = context;
  55676. this._quadMesh.material.fragmentNode = outputNode;
  55677. this._quadMesh.material.needsUpdate = true;
  55678. this.needsUpdate = false;
  55679. }
  55680. }
  55681. /**
  55682. * When `PostProcessing` is used to apply post processing effects,
  55683. * the application must use this version of `renderAsync()` inside
  55684. * its animation loop (not the one from the renderer).
  55685. *
  55686. * @async
  55687. * @deprecated
  55688. * @return {Promise} A Promise that resolves when the render has been finished.
  55689. */
  55690. async renderAsync() {
  55691. warnOnce( 'PostProcessing: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  55692. await this.renderer.init();
  55693. this.render();
  55694. }
  55695. }
  55696. /**
  55697. * This special type of texture is intended for compute shaders.
  55698. * It can be used to compute the data of a texture with a compute shader.
  55699. *
  55700. * Note: This type of texture can only be used with `WebGPURenderer`
  55701. * and a WebGPU backend.
  55702. *
  55703. * @augments Texture
  55704. */
  55705. class StorageTexture extends Texture {
  55706. /**
  55707. * Constructs a new storage texture.
  55708. *
  55709. * @param {number} [width=1] - The storage texture's width.
  55710. * @param {number} [height=1] - The storage texture's height.
  55711. */
  55712. constructor( width = 1, height = 1 ) {
  55713. super();
  55714. /**
  55715. * The image object which just represents the texture's dimension.
  55716. *
  55717. * @type {{width: number, height: number}}
  55718. */
  55719. this.image = { width, height };
  55720. /**
  55721. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  55722. *
  55723. * @type {number}
  55724. */
  55725. this.magFilter = LinearFilter;
  55726. /**
  55727. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  55728. *
  55729. * @type {number}
  55730. */
  55731. this.minFilter = LinearFilter;
  55732. /**
  55733. * This flag can be used for type testing.
  55734. *
  55735. * @type {boolean}
  55736. * @readonly
  55737. * @default true
  55738. */
  55739. this.isStorageTexture = true;
  55740. /**
  55741. * When `true`, mipmaps will be auto-generated after compute writes.
  55742. * When `false`, mipmaps must be written manually via compute shaders.
  55743. *
  55744. * @type {boolean}
  55745. * @default true
  55746. */
  55747. this.mipmapsAutoUpdate = true;
  55748. }
  55749. /**
  55750. * Sets the size of the storage texture.
  55751. *
  55752. * @param {number} width - The new width of the storage texture.
  55753. * @param {number} height - The new height of the storage texture.
  55754. */
  55755. setSize( width, height ) {
  55756. if ( this.image.width !== width || this.image.height !== height ) {
  55757. this.image.width = width;
  55758. this.image.height = height;
  55759. this.dispose();
  55760. }
  55761. }
  55762. }
  55763. /**
  55764. * This special type of texture is intended for compute shaders.
  55765. * It can be used to compute the data of a texture with a compute shader.
  55766. *
  55767. * Note: This type of texture can only be used with `WebGPURenderer`
  55768. * and a WebGPU backend.
  55769. *
  55770. * @augments Texture
  55771. */
  55772. class Storage3DTexture extends Texture {
  55773. /**
  55774. * Constructs a new storage texture.
  55775. *
  55776. * @param {number} [width=1] - The storage texture's width.
  55777. * @param {number} [height=1] - The storage texture's height.
  55778. * @param {number} [depth=1] - The storage texture's depth.
  55779. */
  55780. constructor( width = 1, height = 1, depth = 1 ) {
  55781. super();
  55782. //inherited from texture. Must be false for 3DTexture
  55783. this.isArrayTexture = false;
  55784. /**
  55785. * The image object which just represents the texture's dimension.
  55786. *
  55787. * @type {{width: number, height: number, depth: number}}
  55788. */
  55789. this.image = { width, height, depth };
  55790. /**
  55791. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  55792. *
  55793. * @type {number}
  55794. */
  55795. this.magFilter = LinearFilter;
  55796. /**
  55797. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  55798. *
  55799. * @type {number}
  55800. */
  55801. this.minFilter = LinearFilter;
  55802. /**
  55803. * This defines how the texture is wrapped in the depth direction and corresponds to
  55804. * *W* in UVW mapping.
  55805. *
  55806. * @type {number}
  55807. */
  55808. this.wrapR = ClampToEdgeWrapping;
  55809. /**
  55810. * This flag can be used for type testing.
  55811. *
  55812. * @type {boolean}
  55813. * @readonly
  55814. * @default true
  55815. */
  55816. this.isStorageTexture = true;
  55817. /**
  55818. * Indicates whether this texture is a 3D texture.
  55819. *
  55820. * @type {boolean}
  55821. *
  55822. */
  55823. this.is3DTexture = true;
  55824. }
  55825. /**
  55826. * Sets the size of the storage 3d texture.
  55827. *
  55828. * @param {number} width - The new width of the storage texture.
  55829. * @param {number} height - The new height of the storage texture.
  55830. * @param {number} depth - The new depth of the storage texture.
  55831. */
  55832. setSize( width, height, depth ) {
  55833. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  55834. this.image.width = width;
  55835. this.image.height = height;
  55836. this.image.depth = depth;
  55837. this.dispose();
  55838. }
  55839. }
  55840. }
  55841. /**
  55842. * This special type of texture is intended for compute shaders.
  55843. * It can be used to compute the data of a texture with a compute shader.
  55844. *
  55845. * Note: This type of texture can only be used with `WebGPURenderer`
  55846. * and a WebGPU backend.
  55847. *
  55848. * @augments Texture
  55849. */
  55850. class StorageArrayTexture extends Texture {
  55851. /**
  55852. * Constructs a new storage texture.
  55853. *
  55854. * @param {number} [width=1] - The storage texture's width.
  55855. * @param {number} [height=1] - The storage texture's height.
  55856. * @param {number} [depth=1] - The storage texture's depth.
  55857. */
  55858. constructor( width = 1, height = 1, depth = 1 ) {
  55859. super();
  55860. //inherited from texture
  55861. this.isArrayTexture = true;
  55862. /**
  55863. * The image object which just represents the texture's dimension.
  55864. *
  55865. * @type {{width: number, height: number, depth: number}}
  55866. */
  55867. this.image = { width, height, depth };
  55868. /**
  55869. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  55870. *
  55871. * @type {number}
  55872. */
  55873. this.magFilter = LinearFilter;
  55874. /**
  55875. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  55876. *
  55877. * @type {number}
  55878. */
  55879. this.minFilter = LinearFilter;
  55880. /**
  55881. * This flag can be used for type testing.
  55882. *
  55883. * @type {boolean}
  55884. * @readonly
  55885. * @default true
  55886. */
  55887. this.isStorageTexture = true;
  55888. }
  55889. /**
  55890. * Sets the size of the storage array texture.
  55891. *
  55892. * @param {number} width - The new width of the storage texture.
  55893. * @param {number} height - The new height of the storage texture.
  55894. * @param {number} depth - The new depth of the storage texture.
  55895. */
  55896. setSize( width, height, depth ) {
  55897. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  55898. this.image.width = width;
  55899. this.image.height = height;
  55900. this.image.depth = depth;
  55901. this.dispose();
  55902. }
  55903. }
  55904. }
  55905. /**
  55906. * This special type of buffer attribute is intended for compute shaders.
  55907. * It can be used to encode draw parameters for indirect draw calls.
  55908. *
  55909. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  55910. * and a WebGPU backend.
  55911. *
  55912. * @augments StorageBufferAttribute
  55913. */
  55914. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  55915. /**
  55916. * Constructs a new storage buffer attribute.
  55917. *
  55918. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  55919. * The subsequent parameter is then obsolete.
  55920. * @param {number} itemSize - The item size.
  55921. */
  55922. constructor( count, itemSize ) {
  55923. super( count, itemSize, Uint32Array );
  55924. /**
  55925. * This flag can be used for type testing.
  55926. *
  55927. * @type {boolean}
  55928. * @readonly
  55929. * @default true
  55930. */
  55931. this.isIndirectStorageBufferAttribute = true;
  55932. }
  55933. }
  55934. /**
  55935. * A loader for loading node objects in the three.js JSON Object/Scene format.
  55936. *
  55937. * @augments Loader
  55938. */
  55939. class NodeLoader extends Loader {
  55940. /**
  55941. * Constructs a new node loader.
  55942. *
  55943. * @param {LoadingManager} [manager] - A reference to a loading manager.
  55944. */
  55945. constructor( manager ) {
  55946. super( manager );
  55947. /**
  55948. * Represents a dictionary of textures.
  55949. *
  55950. * @type {Object<string,Texture>}
  55951. */
  55952. this.textures = {};
  55953. /**
  55954. * Represents a dictionary of node types.
  55955. *
  55956. * @type {Object<string,Node.constructor>}
  55957. */
  55958. this.nodes = {};
  55959. }
  55960. /**
  55961. * Loads the node definitions from the given URL.
  55962. *
  55963. * @param {string} url - The path/URL of the file to be loaded.
  55964. * @param {Function} onLoad - Will be called when load completes.
  55965. * @param {Function} onProgress - Will be called while load progresses.
  55966. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  55967. */
  55968. load( url, onLoad, onProgress, onError ) {
  55969. const loader = new FileLoader( this.manager );
  55970. loader.setPath( this.path );
  55971. loader.setRequestHeader( this.requestHeader );
  55972. loader.setWithCredentials( this.withCredentials );
  55973. loader.load( url, ( text ) => {
  55974. try {
  55975. onLoad( this.parse( JSON.parse( text ) ) );
  55976. } catch ( e ) {
  55977. if ( onError ) {
  55978. onError( e );
  55979. } else {
  55980. error( e );
  55981. }
  55982. this.manager.itemError( url );
  55983. }
  55984. }, onProgress, onError );
  55985. }
  55986. /**
  55987. * Parse the node dependencies for the loaded node.
  55988. *
  55989. * @param {Array<Object>} [json] - The JSON definition
  55990. * @return {Object<string,Node>} A dictionary with node dependencies.
  55991. */
  55992. parseNodes( json ) {
  55993. const nodes = {};
  55994. if ( json !== undefined ) {
  55995. for ( const nodeJSON of json ) {
  55996. const { uuid, type } = nodeJSON;
  55997. nodes[ uuid ] = this.createNodeFromType( type );
  55998. nodes[ uuid ].uuid = uuid;
  55999. }
  56000. const meta = { nodes, textures: this.textures };
  56001. for ( const nodeJSON of json ) {
  56002. nodeJSON.meta = meta;
  56003. const node = nodes[ nodeJSON.uuid ];
  56004. node.deserialize( nodeJSON );
  56005. delete nodeJSON.meta;
  56006. }
  56007. }
  56008. return nodes;
  56009. }
  56010. /**
  56011. * Parses the node from the given JSON.
  56012. *
  56013. * @param {Object} json - The JSON definition
  56014. * @param {string} json.type - The node type.
  56015. * @param {string} json.uuid - The node UUID.
  56016. * @param {Array<Object>} [json.nodes] - The node dependencies.
  56017. * @param {Object} [json.meta] - The meta data.
  56018. * @return {Node} The parsed node.
  56019. */
  56020. parse( json ) {
  56021. const node = this.createNodeFromType( json.type );
  56022. node.uuid = json.uuid;
  56023. const nodes = this.parseNodes( json.nodes );
  56024. const meta = { nodes, textures: this.textures };
  56025. json.meta = meta;
  56026. node.deserialize( json );
  56027. delete json.meta;
  56028. return node;
  56029. }
  56030. /**
  56031. * Defines the dictionary of textures.
  56032. *
  56033. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  56034. * @return {NodeLoader} A reference to this loader.
  56035. */
  56036. setTextures( value ) {
  56037. this.textures = value;
  56038. return this;
  56039. }
  56040. /**
  56041. * Defines the dictionary of node types.
  56042. *
  56043. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  56044. * @return {NodeLoader} A reference to this loader.
  56045. */
  56046. setNodes( value ) {
  56047. this.nodes = value;
  56048. return this;
  56049. }
  56050. /**
  56051. * Creates a node object from the given type.
  56052. *
  56053. * @param {string} type - The node type.
  56054. * @return {Node} The created node instance.
  56055. */
  56056. createNodeFromType( type ) {
  56057. if ( this.nodes[ type ] === undefined ) {
  56058. error( 'NodeLoader: Node type not found:', type );
  56059. return float();
  56060. }
  56061. return nodeObject( new this.nodes[ type ]() );
  56062. }
  56063. }
  56064. /**
  56065. * A special type of material loader for loading node materials.
  56066. *
  56067. * @augments MaterialLoader
  56068. */
  56069. class NodeMaterialLoader extends MaterialLoader {
  56070. /**
  56071. * Constructs a new node material loader.
  56072. *
  56073. * @param {LoadingManager} [manager] - A reference to a loading manager.
  56074. */
  56075. constructor( manager ) {
  56076. super( manager );
  56077. /**
  56078. * Represents a dictionary of node types.
  56079. *
  56080. * @type {Object<string,Node.constructor>}
  56081. */
  56082. this.nodes = {};
  56083. /**
  56084. * Represents a dictionary of node material types.
  56085. *
  56086. * @type {Object<string,NodeMaterial.constructor>}
  56087. */
  56088. this.nodeMaterials = {};
  56089. }
  56090. /**
  56091. * Parses the node material from the given JSON.
  56092. *
  56093. * @param {Object} json - The JSON definition
  56094. * @return {NodeMaterial}. The parsed material.
  56095. */
  56096. parse( json ) {
  56097. const material = super.parse( json );
  56098. const nodes = this.nodes;
  56099. const inputNodes = json.inputNodes;
  56100. for ( const property in inputNodes ) {
  56101. const uuid = inputNodes[ property ];
  56102. material[ property ] = nodes[ uuid ];
  56103. }
  56104. return material;
  56105. }
  56106. /**
  56107. * Defines the dictionary of node types.
  56108. *
  56109. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  56110. * @return {NodeLoader} A reference to this loader.
  56111. */
  56112. setNodes( value ) {
  56113. this.nodes = value;
  56114. return this;
  56115. }
  56116. /**
  56117. * Defines the dictionary of node material types.
  56118. *
  56119. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  56120. * @return {NodeLoader} A reference to this loader.
  56121. */
  56122. setNodeMaterials( value ) {
  56123. this.nodeMaterials = value;
  56124. return this;
  56125. }
  56126. /**
  56127. * Creates a node material from the given type.
  56128. *
  56129. * @param {string} type - The node material type.
  56130. * @return {Node} The created node material instance.
  56131. */
  56132. createMaterialFromType( type ) {
  56133. const materialClass = this.nodeMaterials[ type ];
  56134. if ( materialClass !== undefined ) {
  56135. return new materialClass();
  56136. }
  56137. return super.createMaterialFromType( type );
  56138. }
  56139. }
  56140. /**
  56141. * A special type of object loader for loading 3D objects using
  56142. * node materials.
  56143. *
  56144. * @augments ObjectLoader
  56145. */
  56146. class NodeObjectLoader extends ObjectLoader {
  56147. /**
  56148. * Constructs a new node object loader.
  56149. *
  56150. * @param {LoadingManager} [manager] - A reference to a loading manager.
  56151. */
  56152. constructor( manager ) {
  56153. super( manager );
  56154. /**
  56155. * Represents a dictionary of node types.
  56156. *
  56157. * @type {Object<string,Node.constructor>}
  56158. */
  56159. this.nodes = {};
  56160. /**
  56161. * Represents a dictionary of node material types.
  56162. *
  56163. * @type {Object<string,NodeMaterial.constructor>}
  56164. */
  56165. this.nodeMaterials = {};
  56166. /**
  56167. * A reference to hold the `nodes` JSON property.
  56168. *
  56169. * @private
  56170. * @type {?Object[]}
  56171. */
  56172. this._nodesJSON = null;
  56173. }
  56174. /**
  56175. * Defines the dictionary of node types.
  56176. *
  56177. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  56178. * @return {NodeObjectLoader} A reference to this loader.
  56179. */
  56180. setNodes( value ) {
  56181. this.nodes = value;
  56182. return this;
  56183. }
  56184. /**
  56185. * Defines the dictionary of node material types.
  56186. *
  56187. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  56188. * @return {NodeObjectLoader} A reference to this loader.
  56189. */
  56190. setNodeMaterials( value ) {
  56191. this.nodeMaterials = value;
  56192. return this;
  56193. }
  56194. /**
  56195. * Parses the node objects from the given JSON.
  56196. *
  56197. * @param {Object} json - The JSON definition
  56198. * @param {Function} onLoad - The onLoad callback function.
  56199. * @return {Object3D}. The parsed 3D object.
  56200. */
  56201. parse( json, onLoad ) {
  56202. this._nodesJSON = json.nodes;
  56203. const data = super.parse( json, onLoad );
  56204. this._nodesJSON = null; // dispose
  56205. return data;
  56206. }
  56207. /**
  56208. * Parses the node objects from the given JSON and textures.
  56209. *
  56210. * @param {Object[]} json - The JSON definition
  56211. * @param {Object<string,Texture>} textures - The texture library.
  56212. * @return {Object<string,Node>}. The parsed nodes.
  56213. */
  56214. parseNodes( json, textures ) {
  56215. if ( json !== undefined ) {
  56216. const loader = new NodeLoader();
  56217. loader.setNodes( this.nodes );
  56218. loader.setTextures( textures );
  56219. return loader.parseNodes( json );
  56220. }
  56221. return {};
  56222. }
  56223. /**
  56224. * Parses the node objects from the given JSON and textures.
  56225. *
  56226. * @param {Object} json - The JSON definition
  56227. * @param {Object<string,Texture>} textures - The texture library.
  56228. * @return {Object<string,NodeMaterial>}. The parsed materials.
  56229. */
  56230. parseMaterials( json, textures ) {
  56231. const materials = {};
  56232. if ( json !== undefined ) {
  56233. const nodes = this.parseNodes( this._nodesJSON, textures );
  56234. const loader = new NodeMaterialLoader();
  56235. loader.setTextures( textures );
  56236. loader.setNodes( nodes );
  56237. loader.setNodeMaterials( this.nodeMaterials );
  56238. for ( let i = 0, l = json.length; i < l; i ++ ) {
  56239. const data = json[ i ];
  56240. materials[ data.uuid ] = loader.parse( data );
  56241. }
  56242. }
  56243. return materials;
  56244. }
  56245. }
  56246. /**
  56247. * In earlier three.js versions, clipping was defined globally
  56248. * on the renderer or on material level. This special version of
  56249. * `THREE.Group` allows to encode the clipping state into the scene
  56250. * graph. Meaning if you create an instance of this group, all
  56251. * descendant 3D objects will be affected by the respective clipping
  56252. * planes.
  56253. *
  56254. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  56255. *
  56256. * @augments Group
  56257. */
  56258. class ClippingGroup extends Group {
  56259. /**
  56260. * Constructs a new clipping group.
  56261. */
  56262. constructor() {
  56263. super();
  56264. /**
  56265. * This flag can be used for type testing.
  56266. *
  56267. * @type {boolean}
  56268. * @readonly
  56269. * @default true
  56270. */
  56271. this.isClippingGroup = true;
  56272. /**
  56273. * An array with clipping planes.
  56274. *
  56275. * @type {Array<Plane>}
  56276. */
  56277. this.clippingPlanes = [];
  56278. /**
  56279. * Whether clipping should be enabled or not.
  56280. *
  56281. * @type {boolean}
  56282. * @default true
  56283. */
  56284. this.enabled = true;
  56285. /**
  56286. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  56287. *
  56288. * @type {boolean}
  56289. * @default false
  56290. */
  56291. this.clipIntersection = false;
  56292. /**
  56293. * Whether shadows should be clipped or not.
  56294. *
  56295. * @type {boolean}
  56296. * @default false
  56297. */
  56298. this.clipShadows = false;
  56299. }
  56300. }
  56301. 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, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, 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, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, 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_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, Sphere, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, Storage3DTexture, StorageArrayElementNode, StorageArrayTexture, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubBuildNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, TimestampQuery, ToneMappingNode, ToonOutlinePassNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, error, log$1 as log, shaderStages, vectorComponents, warn, warnOnce };
粤ICP备19079148号